filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
894038.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53a.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-53a.tmpl.c
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: file Read input from a file
* GoodSource: Copy a fixed string into data
* Sinks: printf
* GoodSink: wprintf with "%s" as the first argument and data as the second
* BadSink : wprintf with only data as an argument
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifndef OMITBAD
/* bad function declaration */
void CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_badSink(wchar_t * data);
void CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
/* Read input from a file */
size_t dataLen = wcslen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (100-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
fclose(pFile);
}
}
}
CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_goodG2BSink(wchar_t * data);
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
wcscpy(data, L"fixedstringtest");
CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_goodG2BSink(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_goodB2GSink(wchar_t * data);
static void goodB2G()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
/* Read input from a file */
size_t dataLen = wcslen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (100-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
fclose(pFile);
}
}
}
CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53b_goodB2GSink(data);
}
void CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53_good()
{
goodG2B();
goodB2G();
}
#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()...");
CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE134_Uncontrolled_Format_String__wchar_t_file_printf_53_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
76430.c | /*
* driver/clk-rk3128-factor.c
*
* Copyright(c) 2007-2018 Jianjun Jiang <[email protected]>
* Official site: http://xboot.org
* Mobile phone: +86-18665388956
* QQ: 8192542
*
* 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 <xboot.h>
#include <clk/clk.h>
struct clk_rk3128_factor_pdata_t {
virtual_addr_t virt;
char * parent;
};
static void clk_rk3128_factor_set_parent(struct clk_t * clk, const char * pname)
{
}
static const char * clk_rk3128_factor_get_parent(struct clk_t * clk)
{
struct clk_rk3128_factor_pdata_t * pdat = (struct clk_rk3128_factor_pdata_t *)clk->priv;
return pdat->parent;
}
static void clk_rk3128_factor_set_enable(struct clk_t * clk, bool_t enable)
{
}
static bool_t clk_rk3128_factor_get_enable(struct clk_t * clk)
{
return TRUE;
}
static u64_t clk_rk3128_gcd(u64_t a, u64_t b)
{
u64_t c;
while(b != 0)
{
c = a % b;
a = b;
b = c;
}
return a;
}
static void clk_rk3128_factor_set_rate(struct clk_t * clk, u64_t prate, u64_t rate)
{
struct clk_rk3128_factor_pdata_t * pdat = (struct clk_rk3128_factor_pdata_t *)clk->priv;
u64_t cdiv;
u32_t mult, div;
if(rate == 0)
rate = prate;
cdiv = clk_rk3128_gcd(prate, rate);
div = (prate / cdiv) & 0xffff;
mult = (rate / cdiv) & 0xffff;
write32(pdat->virt, (mult << 16) | (div << 0));
}
static u64_t clk_rk3128_factor_get_rate(struct clk_t * clk, u64_t prate)
{
struct clk_rk3128_factor_pdata_t * pdat = (struct clk_rk3128_factor_pdata_t *)clk->priv;
u32_t val = read32(pdat->virt);
return (prate * ((val >> 16) & 0xffff)) / ((val >> 0) & 0xffff);
}
static struct device_t * clk_rk3128_factor_probe(struct driver_t * drv, struct dtnode_t * n)
{
struct clk_rk3128_factor_pdata_t * pdat;
struct clk_t * clk;
struct device_t * dev;
struct dtnode_t o;
virtual_addr_t virt = phys_to_virt(dt_read_address(n));
char * parent = dt_read_string(n, "parent", NULL);
char * name = dt_read_string(n, "name", NULL);
if(!parent || !name)
return NULL;
if(!search_clk(parent) || search_clk(name))
return NULL;
pdat = malloc(sizeof(struct clk_rk3128_factor_pdata_t));
if(!pdat)
return NULL;
clk = malloc(sizeof(struct clk_t));
if(!clk)
{
free(pdat);
return NULL;
}
pdat->virt = virt;
pdat->parent = strdup(parent);
clk->name = strdup(name);
clk->count = 0;
clk->set_parent = clk_rk3128_factor_set_parent;
clk->get_parent = clk_rk3128_factor_get_parent;
clk->set_enable = clk_rk3128_factor_set_enable;
clk->get_enable = clk_rk3128_factor_get_enable;
clk->set_rate = clk_rk3128_factor_set_rate;
clk->get_rate = clk_rk3128_factor_get_rate;
clk->priv = pdat;
if(!register_clk(&dev, clk))
{
free(pdat->parent);
free(clk->name);
free(clk->priv);
free(clk);
return NULL;
}
dev->driver = drv;
if(dt_read_object(n, "default", &o))
{
char * c = clk->name;
char * p;
u64_t r;
int e;
if((p = dt_read_string(&o, "parent", NULL)) && search_clk(p))
clk_set_parent(c, p);
if((r = (u64_t)dt_read_long(&o, "rate", 0)) > 0)
clk_set_rate(c, r);
if((e = dt_read_bool(&o, "enable", -1)) != -1)
{
if(e > 0)
clk_enable(c);
else
clk_disable(c);
}
}
return dev;
}
static void clk_rk3128_factor_remove(struct device_t * dev)
{
struct clk_t * clk = (struct clk_t *)dev->priv;
struct clk_rk3128_factor_pdata_t * pdat = (struct clk_rk3128_factor_pdata_t *)clk->priv;
if(clk && unregister_clk(clk))
{
free(pdat->parent);
free(clk->name);
free(clk->priv);
free(clk);
}
}
static void clk_rk3128_factor_suspend(struct device_t * dev)
{
}
static void clk_rk3128_factor_resume(struct device_t * dev)
{
}
static struct driver_t clk_rk3128_factor = {
.name = "clk-rk3128-factor",
.probe = clk_rk3128_factor_probe,
.remove = clk_rk3128_factor_remove,
.suspend = clk_rk3128_factor_suspend,
.resume = clk_rk3128_factor_resume,
};
static __init void clk_rk3128_factor_driver_init(void)
{
register_driver(&clk_rk3128_factor);
}
static __exit void clk_rk3128_factor_driver_exit(void)
{
unregister_driver(&clk_rk3128_factor);
}
driver_initcall(clk_rk3128_factor_driver_init);
driver_exitcall(clk_rk3128_factor_driver_exit);
|
741612.c | /* definition of standard geoids */
#define PJ_ELLPS__
#include "projects.h"
C_NAMESPACE_VAR struct PJ_ELLPS
pj_ellps[] = {
"MERIT", "a=6378137.0", "rf=298.257", "MERIT 1983",
"SGS85", "a=6378136.0", "rf=298.257", "Soviet Geodetic System 85",
"GRS80", "a=6378137.0", "rf=298.257222101", "GRS 1980(IUGG, 1980)",
"IAU76", "a=6378140.0", "rf=298.257", "IAU 1976",
"airy", "a=6377563.396", "b=6356256.910", "Airy 1830",
"APL4.9", "a=6378137.0.", "rf=298.25", "Appl. Physics. 1965",
"NWL9D", "a=6378145.0.", "rf=298.25", "Naval Weapons Lab., 1965",
"mod_airy", "a=6377340.189", "b=6356034.446", "Modified Airy",
"andrae", "a=6377104.43", "rf=300.0", "Andrae 1876 (Den., Iclnd.)",
"aust_SA", "a=6378160.0", "rf=298.25", "Australian Natl & S. Amer. 1969",
"GRS67", "a=6378160.0", "rf=298.2471674270", "GRS 67(IUGG 1967)",
"bessel", "a=6377397.155", "rf=299.1528128", "Bessel 1841",
"bess_nam", "a=6377483.865", "rf=299.1528128", "Bessel 1841 (Namibia)",
"clrk66", "a=6378206.4", "b=6356583.8", "Clarke 1866",
"clrk80", "a=6378249.145", "rf=293.4663", "Clarke 1880 mod.",
"CPM", "a=6375738.7", "rf=334.29", "Comm. des Poids et Mesures 1799",
"delmbr", "a=6376428.", "rf=311.5", "Delambre 1810 (Belgium)",
"engelis", "a=6378136.05", "rf=298.2566", "Engelis 1985",
"evrst30", "a=6377276.345", "rf=300.8017", "Everest 1830",
"evrst48", "a=6377304.063", "rf=300.8017", "Everest 1948",
"evrst56", "a=6377301.243", "rf=300.8017", "Everest 1956",
"evrst69", "a=6377295.664", "rf=300.8017", "Everest 1969",
"evrstSS", "a=6377298.556", "rf=300.8017", "Everest (Sabah & Sarawak)",
"fschr60", "a=6378166.", "rf=298.3", "Fischer (Mercury Datum) 1960",
"fschr60m", "a=6378155.", "rf=298.3", "Modified Fischer 1960",
"fschr68", "a=6378150.", "rf=298.3", "Fischer 1968",
"helmert", "a=6378200.", "rf=298.3", "Helmert 1906",
"hough", "a=6378270.0", "rf=297.", "Hough",
"intl", "a=6378388.0", "rf=297.", "International 1909 (Hayford)",
"krass", "a=6378245.0", "rf=298.3", "Krassovsky, 1942",
"kaula", "a=6378163.", "rf=298.24", "Kaula 1961",
"lerch", "a=6378139.", "rf=298.257", "Lerch 1979",
"mprts", "a=6397300.", "rf=191.", "Maupertius 1738",
"new_intl", "a=6378157.5", "b=6356772.2", "New International 1967",
"plessis", "a=6376523.", "b=6355863.", "Plessis 1817 (France)",
"SEasia", "a=6378155.0", "b=6356773.3205", "Southeast Asia",
"walbeck", "a=6376896.0", "b=6355834.8467", "Walbeck",
"WGS60", "a=6378165.0", "rf=298.3", "WGS 60",
"WGS66", "a=6378145.0", "rf=298.25", "WGS 66",
"WGS72", "a=6378135.0", "rf=298.26", "WGS 72",
"WGS84", "a=6378137.0", "rf=298.257223563", "WGS 84",
"sphere", "a=6370997.0", "b=6370997.0", "Normal Sphere (r=6370997)",
0,0,0,0
};
struct PJ_ELLPS *pj_get_ellps_ref()
{
return pj_ellps;
}
|
766154.c | /**
* gesummv.c: This file is part of the PolyBench/GPU 1.0 test suite.
*
*
* Contact: Scott Grauer-Gray <[email protected]>
* Louis-Noel Pouchet <[email protected]>
* Web address: http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdarg.h>
#include "../../../common/polybenchUtilFuncts.h"
//define the error threshold for the results "not matching"
#define PERCENT_DIFF_ERROR_THRESHOLD 0.05
/* Problem size. */
#define N 4096
/* Can switch DATA_TYPE between float and double */
typedef float DATA_TYPE;
#pragma hmpp gesummv codelet, target=CUDA, args[a, b, x1, y1, tmp1].io=inout
void runGesummv(DATA_TYPE a[N][N], DATA_TYPE b[N][N], DATA_TYPE x1[N], DATA_TYPE y1[N], DATA_TYPE tmp1[N])
{
int i, j;
DATA_TYPE alpha = 43532;
DATA_TYPE beta = 12313;
#pragma hmppcg grid blocksize 32 X 8
#pragma hmppcg permute i, j
#pragma hmppcg tile i:4
#pragma hmppcg parallel
for (i = 0; i < N; i++)
{
tmp1[i] = 0;
y1[i] = 0;
#pragma hmppcg tile j:2
#pragma hmppcg noParallel
for (j = 0; j < N; j++)
{
tmp1[i] = a[i][j] * x1[j] + tmp1[i];
y1[i] = b[i][j] * x1[j] + y1[i];
}
y1[i] = alpha * tmp1[i] + beta * y1[i];
}
}
void init(DATA_TYPE A[N][N], DATA_TYPE x[N])
{
int i, j;
for (i = 0; i < N; i++)
{
x[i] = ((DATA_TYPE) i) / N;
for (j = 0; j < N; j++)
{
A[i][j] = ((DATA_TYPE) i*j) / N;
}
}
}
void compareResults(DATA_TYPE y[N], DATA_TYPE y_outputFromGpu[N])
{
int i, fail;
fail = 0;
for (i=0; i< N; i++)
{
if (percentDiff(y[i], y_outputFromGpu[i]) > PERCENT_DIFF_ERROR_THRESHOLD)
{
fail++;
}
}
// Print results
printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail);
}
int main(int argc, char** argv)
{
double t_start, t_end;
/* Array declaration */
DATA_TYPE A[N][N];
DATA_TYPE B[N][N];
DATA_TYPE x[N];
DATA_TYPE y[N];
DATA_TYPE y_outputFromGpu[N];
DATA_TYPE tmp[N];
/* Initialize array. */
init(A, x);
#pragma hmpp gesummv allocate
#pragma hmpp gesummv advancedload, args[a, b, x1, y1, tmp1]
t_start = rtclock();
#pragma hmpp gesummv callsite, args[a, b, x1, y1, tmp1].advancedload=true, asynchronous
runGesummv(A, B, x, y_outputFromGpu, tmp);
#pragma hmpp gesummv synchronize
t_end = rtclock();
fprintf(stderr, "GPU Runtime: %0.6lfs\n", t_end - t_start);
#pragma hmpp gesummv delegatedstore, args[a, b, x1, y1, tmp1]
#pragma hmpp gesummv release
t_start = rtclock();
runGesummv(A, B, x, y, tmp);
t_end = rtclock();
fprintf(stderr, "CPU Runtime: %0.6lfs\n", t_end - t_start);
compareResults(y, y_outputFromGpu);
return 0;
}
|
648667.c | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/checks.h"
#include "modules/audio_coding/codecs/isac/fix/source/codec.h"
// Autocorrelation function in fixed point.
// NOTE! Different from SPLIB-version in how it scales the signal.
int WebRtcIsacfix_AutocorrC(int32_t* __restrict r,
const int16_t* __restrict x,
int16_t N,
int16_t order,
int16_t* __restrict scale) {
int i = 0;
int j = 0;
int16_t scaling = 0;
int32_t sum = 0;
uint32_t temp = 0;
int64_t prod = 0;
// The ARM assembly code assumptoins.
RTC_DCHECK_EQ(0, N % 4);
RTC_DCHECK_GE(N, 8);
// Calculate r[0].
for (i = 0; i < N; i++) {
prod += x[i] * x[i];
}
// Calculate scaling (the value of shifting).
temp = (uint32_t)(prod >> 31);
if(temp == 0) {
scaling = 0;
} else {
scaling = 32 - WebRtcSpl_NormU32(temp);
}
r[0] = (int32_t)(prod >> scaling);
// Perform the actual correlation calculation.
for (i = 1; i < order + 1; i++) {
prod = 0;
for (j = 0; j < N - i; j++) {
prod += x[j] * x[i + j];
}
sum = (int32_t)(prod >> scaling);
r[i] = sum;
}
*scale = scaling;
return(order + 1);
}
static const int32_t kApUpperQ15[ALLPASSSECTIONS] = { 1137, 12537 };
static const int32_t kApLowerQ15[ALLPASSSECTIONS] = { 5059, 24379 };
static void AllpassFilterForDec32(int16_t *InOut16, //Q0
const int32_t *APSectionFactors, //Q15
int16_t lengthInOut,
int32_t *FilterState) //Q16
{
int n, j;
int32_t a, b;
for (j=0; j<ALLPASSSECTIONS; j++) {
for (n=0;n<lengthInOut;n+=2){
a = WEBRTC_SPL_MUL_16_32_RSFT16(InOut16[n], APSectionFactors[j]); //Q0*Q31=Q31 shifted 16 gives Q15
a <<= 1; // Q15 -> Q16
b = WebRtcSpl_AddSatW32(a, FilterState[j]); //Q16+Q16=Q16
// |a| in Q15 (Q0*Q31=Q31 shifted 16 gives Q15).
a = WEBRTC_SPL_MUL_16_32_RSFT16(b >> 16, -APSectionFactors[j]);
// FilterState[j]: Q15<<1 + Q0<<16 = Q16 + Q16 = Q16
FilterState[j] = WebRtcSpl_AddSatW32(a << 1, (uint32_t)InOut16[n] << 16);
InOut16[n] = (int16_t)(b >> 16); // Save as Q0.
}
}
}
void WebRtcIsacfix_DecimateAllpass32(const int16_t *in,
int32_t *state_in, /* array of size: 2*ALLPASSSECTIONS+1 */
int16_t N, /* number of input samples */
int16_t *out) /* array of size N/2 */
{
int n;
int16_t data_vec[PITCH_FRAME_LEN];
/* copy input */
memcpy(data_vec + 1, in, sizeof(int16_t) * (N - 1));
data_vec[0] = (int16_t)(state_in[2 * ALLPASSSECTIONS] >> 16); // z^-1 state.
state_in[2 * ALLPASSSECTIONS] = (uint32_t)in[N - 1] << 16;
AllpassFilterForDec32(data_vec+1, kApUpperQ15, N, state_in);
AllpassFilterForDec32(data_vec, kApLowerQ15, N, state_in+ALLPASSSECTIONS);
for (n=0;n<N/2;n++) {
out[n] = WebRtcSpl_AddSatW16(data_vec[2 * n], data_vec[2 * n + 1]);
}
}
|
320478.c | /****************************************************************************
* drivers/bch/bchdev_driver.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sched.h>
#include <errno.h>
#include <poll.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/fs/fs.h>
#include <nuttx/fs/ioctl.h>
#include <nuttx/drivers/drivers.h>
#include "bch.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
static int bch_open(FAR struct file *filep);
static int bch_close(FAR struct file *filep);
static off_t bch_seek(FAR struct file *filep, off_t offset, int whence);
static ssize_t bch_read(FAR struct file *filep, FAR char *buffer,
size_t buflen);
static ssize_t bch_write(FAR struct file *filep, FAR const char *buffer,
size_t buflen);
static int bch_ioctl(FAR struct file *filep, int cmd,
unsigned long arg);
static int bch_poll(FAR struct file *filep, FAR struct pollfd *fds,
bool setup);
#ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS
static int bch_unlink(FAR struct inode *inode);
#endif
/****************************************************************************
* Public Data
****************************************************************************/
const struct file_operations bch_fops =
{
bch_open, /* open */
bch_close, /* close */
bch_read, /* read */
bch_write, /* write */
bch_seek, /* seek */
bch_ioctl, /* ioctl */
bch_poll /* poll */
#ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS
, bch_unlink /* unlink */
#endif
};
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: bch_poll
****************************************************************************/
static int bch_poll(FAR struct file *filep, FAR struct pollfd *fds,
bool setup)
{
if (setup)
{
fds->revents |= (fds->events & (POLLIN | POLLOUT));
if (fds->revents != 0)
{
nxsem_post(fds->sem);
}
}
return OK;
}
/****************************************************************************
* Name: bch_open
*
* Description: Open the block device
*
****************************************************************************/
static int bch_open(FAR struct file *filep)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
int ret = OK;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
/* Increment the reference count */
ret = bchlib_semtake(bch);
if (ret < 0)
{
return ret;
}
if (bch->refs == MAX_OPENCNT)
{
ret = -EMFILE;
}
else
{
bch->refs++;
}
bchlib_semgive(bch);
return ret;
}
/****************************************************************************
* Name: bch_close
*
* Description: close the block device
*
****************************************************************************/
static int bch_close(FAR struct file *filep)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
int ret = OK;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
/* Get exclusive access */
ret = bchlib_semtake(bch);
if (ret < 0)
{
return ret;
}
/* Flush any dirty pages remaining in the cache */
bchlib_flushsector(bch);
/* Decrement the reference count (I don't use bchlib_decref() because I
* want the entire close operation to be atomic wrt other driver
* operations.
*/
if (bch->refs == 0)
{
ret = -EIO;
}
else
{
bch->refs--;
/* If the reference count decremented to zero AND if the character
* driver has been unlinked, then teardown the BCH device now.
*/
if (bch->refs == 0 && bch->unlinked)
{
/* Tear the driver down now. */
ret = bchlib_teardown((FAR void *)bch);
/* bchlib_teardown() would only fail if there are outstanding
* references on the device. Since we know that is not true, it
* should not fail at all.
*/
DEBUGASSERT(ret >= 0);
if (ret >= 0)
{
/* Return without releasing the stale semaphore */
return OK;
}
}
}
bchlib_semgive(bch);
return ret;
}
/****************************************************************************
* Name: bch_seek
****************************************************************************/
static off_t bch_seek(FAR struct file *filep, off_t offset, int whence)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
off_t newpos;
int ret;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
ret = bchlib_semtake(bch);
if (ret < 0)
{
return (off_t)ret;
}
/* Determine the new, requested file position */
switch (whence)
{
case SEEK_CUR:
newpos = filep->f_pos + offset;
break;
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = bch->sectsize * bch->nsectors + offset;
break;
default:
/* Return EINVAL if the whence argument is invalid */
bchlib_semgive(bch);
return -EINVAL;
}
/* Opengroup.org:
*
* "The lseek() function shall allow the file offset to be set beyond the
* end of the existing data in the file. If data is later written at this
* point, subsequent reads of data in the gap shall return bytes with the
* value 0 until data is actually written into the gap."
*
* We can conform to the first part, but not the second. But return EINVAL
* if:
*
* "...the resulting file offset would be negative for a regular file,
* block special file, or directory."
*/
if (newpos >= 0)
{
filep->f_pos = newpos;
ret = newpos;
}
else
{
ret = -EINVAL;
}
bchlib_semgive(bch);
return ret;
}
/****************************************************************************
* Name: bch_read
****************************************************************************/
static ssize_t bch_read(FAR struct file *filep, FAR char *buffer, size_t len)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
int ret;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
ret = bchlib_semtake(bch);
if (ret < 0)
{
return (ssize_t)ret;
}
ret = bchlib_read(bch, buffer, filep->f_pos, len);
if (ret > 0)
{
filep->f_pos += len;
}
bchlib_semgive(bch);
return ret;
}
/****************************************************************************
* Name: bch_write
****************************************************************************/
static ssize_t bch_write(FAR struct file *filep, FAR const char *buffer,
size_t len)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
int ret = -EACCES;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
if (!bch->readonly)
{
ret = bchlib_semtake(bch);
if (ret < 0)
{
return (ssize_t)ret;
}
ret = bchlib_write(bch, buffer, filep->f_pos, len);
if (ret > 0)
{
filep->f_pos += len;
}
bchlib_semgive(bch);
}
return ret;
}
/****************************************************************************
* Name: bch_ioctl
*
* Description:
* Handle IOCTL commands
*
****************************************************************************/
static int bch_ioctl(FAR struct file *filep, int cmd, unsigned long arg)
{
FAR struct inode *inode = filep->f_inode;
FAR struct bchlib_s *bch;
int ret = -ENOTTY;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
/* Process the call according to the command */
switch (cmd)
{
/* This isa request to get the private data structure */
case DIOC_GETPRIV:
{
FAR struct bchlib_s **bchr =
(FAR struct bchlib_s **)((uintptr_t)arg);
ret = bchlib_semtake(bch);
if (ret < 0)
{
return ret;
}
if (!bchr || bch->refs == MAX_OPENCNT)
{
ret = -EINVAL;
}
else
{
bch->refs++;
*bchr = bch;
ret = OK;
}
bchlib_semgive(bch);
}
break;
/* This is a required to return the geometry of the underlying block
* driver.
*/
case BIOC_GEOMETRY:
{
FAR struct geometry *geo = (FAR struct geometry *)((uintptr_t)arg);
DEBUGASSERT(geo != NULL && bch->inode && bch->inode->u.i_bops &&
bch->inode->u.i_bops->geometry);
ret = bch->inode->u.i_bops->geometry(bch->inode, geo);
if (ret < 0)
{
ferr("ERROR: geometry failed: %d\n", -ret);
}
else if (!geo->geo_available)
{
ferr("ERROR: geometry failed: %d\n", -ret);
ret = -ENODEV;
}
}
break;
#ifdef CONFIG_BCH_ENCRYPTION
/* This is a request to set the encryption key? */
case DIOC_SETKEY:
{
memcpy(bch->key, (FAR void *)arg, CONFIG_BCH_ENCRYPTION_KEY_SIZE);
ret = OK;
}
break;
#endif
/* Otherwise, pass the IOCTL command on to the contained block
* driver.
*/
default:
{
FAR struct inode *bchinode = bch->inode;
/* Does the block driver support the ioctl method? */
if (bchinode->u.i_bops->ioctl != NULL)
{
ret = bchinode->u.i_bops->ioctl(bchinode, cmd, arg);
}
}
break;
}
return ret;
}
/****************************************************************************
* Name: bch_unlink
*
* Handle unlinking of the BCH device
*
****************************************************************************/
#ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS
static int bch_unlink(FAR struct inode *inode)
{
FAR struct bchlib_s *bch;
int ret = OK;
DEBUGASSERT(inode && inode->i_private);
bch = (FAR struct bchlib_s *)inode->i_private;
/* Get exclusive access to the BCH device */
ret = bchlib_semtake(bch);
if (ret < 0)
{
return ret;
}
/* Indicate that the driver has been unlinked */
bch->unlinked = true;
/* If there are no open references to the driver then teardown the BCH
* device now.
*/
if (bch->refs == 0)
{
/* Tear the driver down now. */
ret = bchlib_teardown((FAR void *)bch);
/* bchlib_teardown() would only fail if there are outstanding
* references on the device. Since we know that is not true, it
* should not fail at all.
*/
DEBUGASSERT(ret >= 0);
if (ret >= 0)
{
/* Return without releasing the stale semaphore */
return OK;
}
}
bchlib_semgive(bch);
return ret;
}
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
|
408435.c | // Auto-generated file. Do not edit!
// Template: src/x32-transpose/sse2.c.in
// Generator: tools/xngen
//
// Copyright 2021 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 <immintrin.h>
#include <assert.h>
#include <xnnpack/common.h>
#include <xnnpack/math.h>
#include <xnnpack/transpose.h>
void xnn_x16_transpose_ukernel__8x8_reuse_dec_sse2(
const uint16_t* input,
uint16_t* output,
size_t input_stride,
size_t output_stride,
size_t block_width,
size_t block_height)
{
assert(output_stride >= block_height * sizeof(uint16_t));
assert(input_stride >= block_width * sizeof(uint16_t));
const size_t tile_height = 8;
const size_t tile_width = 8;
const size_t tile_hbytes = tile_height * sizeof(uint16_t);
const size_t tile_wbytes = tile_width * sizeof(uint16_t);
const size_t input_reset = tile_wbytes - round_down_po2(block_height, tile_height) * input_stride;
const size_t output_reset = tile_width * output_stride - round_down_po2(block_height, 2) * sizeof(uint16_t);
const uint16_t* i0 = input;
uint16_t* o = (uint16_t*) output;
do {
const size_t rem = min(block_width - 1, 7);
const size_t oN_stride = rem * output_stride;
size_t bh = block_height;
for (; bh >= 8; bh -= 8) {
const __m128i v3_0 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_1 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_2 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_3 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_4 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_5 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_6 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v3_7 = _mm_loadu_si128((const __m128i*) i0);
i0 = (uint16_t*) ((uintptr_t) i0 + input_stride);
const __m128i v2_0 = _mm_unpacklo_epi16(v3_0, v3_1);
const __m128i v2_1 = _mm_unpackhi_epi16(v3_0, v3_1);
const __m128i v2_2 = _mm_unpacklo_epi16(v3_2, v3_3);
const __m128i v2_3 = _mm_unpackhi_epi16(v3_2, v3_3);
const __m128i v2_4 = _mm_unpacklo_epi16(v3_4, v3_5);
const __m128i v2_5 = _mm_unpackhi_epi16(v3_4, v3_5);
const __m128i v2_6 = _mm_unpacklo_epi16(v3_6, v3_7);
const __m128i v2_7 = _mm_unpackhi_epi16(v3_6, v3_7);
const __m128i v1_0 = _mm_unpacklo_epi32(v2_0, v2_2);
const __m128i v1_1 = _mm_unpackhi_epi32(v2_0, v2_2);
const __m128i v1_2 = _mm_unpacklo_epi32(v2_1, v2_3);
const __m128i v1_3 = _mm_unpackhi_epi32(v2_1, v2_3);
const __m128i v1_4 = _mm_unpacklo_epi32(v2_4, v2_6);
const __m128i v1_5 = _mm_unpackhi_epi32(v2_4, v2_6);
const __m128i v1_6 = _mm_unpacklo_epi32(v2_5, v2_7);
const __m128i v1_7 = _mm_unpackhi_epi32(v2_5, v2_7);
const __m128i v0_0 = _mm_unpacklo_epi64(v1_0, v1_4);
const __m128i v0_1 = _mm_unpackhi_epi64(v1_0, v1_4);
const __m128i v0_2 = _mm_unpacklo_epi64(v1_1, v1_5);
const __m128i v0_3 = _mm_unpackhi_epi64(v1_1, v1_5);
const __m128i v0_4 = _mm_unpacklo_epi64(v1_2, v1_6);
const __m128i v0_5 = _mm_unpackhi_epi64(v1_2, v1_6);
const __m128i v0_6 = _mm_unpacklo_epi64(v1_3, v1_7);
const __m128i v0_7 = _mm_unpackhi_epi64(v1_3, v1_7);
uint16_t* o7 = (uint16_t*) ((uintptr_t) o + oN_stride);
_mm_storeu_si128((__m128i*) o7, v0_7);
uint16_t *o6 = (uint16_t*) ((uintptr_t) o7 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 7) {
o6 = o7;
}
_mm_storeu_si128((__m128i*) o6, v0_6);
uint16_t *o5 = (uint16_t*) ((uintptr_t) o6 - output_stride);
if XNN_UNPREDICTABLE(block_width < 7) {
o5 = o7;
}
_mm_storeu_si128((__m128i*) o5, v0_5);
uint16_t *o4 = (uint16_t*) ((uintptr_t) o5 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 5) {
o4 = o7;
}
_mm_storeu_si128((__m128i*) o4, v0_4);
uint16_t *o3 = (uint16_t*) ((uintptr_t) o4 - output_stride);
if XNN_UNPREDICTABLE(block_width < 5) {
o3 = o7;
}
_mm_storeu_si128((__m128i*) o3, v0_3);
uint16_t *o2 = (uint16_t*) ((uintptr_t) o3 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 3) {
o2 = o7;
}
_mm_storeu_si128((__m128i*) o2, v0_2);
uint16_t *o1 = (uint16_t*) ((uintptr_t) o2 - output_stride);
if XNN_UNPREDICTABLE(block_width < 3) {
o1 = o7;
}
_mm_storeu_si128((__m128i*) o1, v0_1);
_mm_storeu_si128((__m128i*) o, v0_0);
o = (uint16_t*) ((uintptr_t) o + tile_hbytes);
}
if (bh != 0) {
const __m128i v3_0 = _mm_loadu_si128((const __m128i*) i0);
const uint16_t *i1 = (const uint16_t*) ((uintptr_t) i0 + input_stride);
if XNN_UNPREDICTABLE(bh < 2) {
i1 = i0;
}
const __m128i v3_1 = _mm_loadu_si128((const __m128i*) i1);
const uint16_t *i2 = (const uint16_t*) ((uintptr_t) i1 + input_stride);
if XNN_UNPREDICTABLE(bh <= 2) {
i2 = i0;
}
const __m128i v3_2 = _mm_loadu_si128((const __m128i*) i2);
const uint16_t *i3 = (const uint16_t*) ((uintptr_t) i2 + input_stride);
if XNN_UNPREDICTABLE(bh < 4) {
i3 = i0;
}
const __m128i v3_3 = _mm_loadu_si128((const __m128i*) i3);
const uint16_t *i4 = (const uint16_t*) ((uintptr_t) i3 + input_stride);
if XNN_UNPREDICTABLE(bh <= 4) {
i4 = i0;
}
const __m128i v3_4 = _mm_loadu_si128((const __m128i*) i4);
const uint16_t *i5 = (const uint16_t*) ((uintptr_t) i4 + input_stride);
if XNN_UNPREDICTABLE(bh < 6) {
i5 = i0;
}
const __m128i v3_5 = _mm_loadu_si128((const __m128i*) i5);
const uint16_t *i6 = (const uint16_t*) ((uintptr_t) i5 + input_stride);
if XNN_UNPREDICTABLE(bh <= 6) {
i6 = i0;
}
const __m128i v3_6 = _mm_loadu_si128((const __m128i*) i6);
const __m128i v3_7 = _mm_undefined_si128();
const __m128i v2_0 = _mm_unpacklo_epi16(v3_0, v3_1);
const __m128i v2_1 = _mm_unpackhi_epi16(v3_0, v3_1);
const __m128i v2_2 = _mm_unpacklo_epi16(v3_2, v3_3);
const __m128i v2_3 = _mm_unpackhi_epi16(v3_2, v3_3);
const __m128i v2_4 = _mm_unpacklo_epi16(v3_4, v3_5);
const __m128i v2_5 = _mm_unpackhi_epi16(v3_4, v3_5);
const __m128i v2_6 = _mm_unpacklo_epi16(v3_6, v3_7);
const __m128i v2_7 = _mm_unpackhi_epi16(v3_6, v3_7);
const __m128i v1_0 = _mm_unpacklo_epi32(v2_0, v2_2);
const __m128i v1_1 = _mm_unpackhi_epi32(v2_0, v2_2);
const __m128i v1_2 = _mm_unpacklo_epi32(v2_1, v2_3);
const __m128i v1_3 = _mm_unpackhi_epi32(v2_1, v2_3);
const __m128i v1_4 = _mm_unpacklo_epi32(v2_4, v2_6);
const __m128i v1_5 = _mm_unpackhi_epi32(v2_4, v2_6);
const __m128i v1_6 = _mm_unpacklo_epi32(v2_5, v2_7);
const __m128i v1_7 = _mm_unpackhi_epi32(v2_5, v2_7);
__m128i v0_0 = _mm_unpacklo_epi64(v1_0, v1_4);
__m128i v0_1 = _mm_unpackhi_epi64(v1_0, v1_4);
__m128i v0_2 = _mm_unpacklo_epi64(v1_1, v1_5);
__m128i v0_3 = _mm_unpackhi_epi64(v1_1, v1_5);
__m128i v0_4 = _mm_unpacklo_epi64(v1_2, v1_6);
__m128i v0_5 = _mm_unpackhi_epi64(v1_2, v1_6);
__m128i v0_6 = _mm_unpacklo_epi64(v1_3, v1_7);
__m128i v0_7 = _mm_unpackhi_epi64(v1_3, v1_7);
if (bh & 4) {
uint16_t* o7 = (uint16_t*) ((uintptr_t) o + oN_stride);
_mm_storel_epi64((__m128i*) o7, v0_7);
uint16_t *o6 = (uint16_t*) ((uintptr_t) o7 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 7) {
o6 = o7;
}
_mm_storel_epi64((__m128i*) o6, v0_6);
uint16_t *o5 = (uint16_t*) ((uintptr_t) o6 - output_stride);
if XNN_UNPREDICTABLE(block_width < 7) {
o5 = o7;
}
_mm_storel_epi64((__m128i*) o5, v0_5);
uint16_t *o4 = (uint16_t*) ((uintptr_t) o5 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 5) {
o4 = o7;
}
_mm_storel_epi64((__m128i*) o4, v0_4);
uint16_t *o3 = (uint16_t*) ((uintptr_t) o4 - output_stride);
if XNN_UNPREDICTABLE(block_width < 5) {
o3 = o7;
}
_mm_storel_epi64((__m128i*) o3, v0_3);
uint16_t *o2 = (uint16_t*) ((uintptr_t) o3 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 3) {
o2 = o7;
}
_mm_storel_epi64((__m128i*) o2, v0_2);
uint16_t *o1 = (uint16_t*) ((uintptr_t) o2 - output_stride);
if XNN_UNPREDICTABLE(block_width < 3) {
o1 = o7;
}
_mm_storel_epi64((__m128i*) o1, v0_1);
_mm_storel_epi64((__m128i*) o, v0_0);
o += 4;
v0_0 = _mm_unpackhi_epi64(v0_0, v0_0);
v0_1 = _mm_unpackhi_epi64(v0_1, v0_1);
v0_2 = _mm_unpackhi_epi64(v0_2, v0_2);
v0_3 = _mm_unpackhi_epi64(v0_3, v0_3);
v0_4 = _mm_unpackhi_epi64(v0_4, v0_4);
v0_5 = _mm_unpackhi_epi64(v0_5, v0_5);
v0_6 = _mm_unpackhi_epi64(v0_6, v0_6);
v0_7 = _mm_unpackhi_epi64(v0_7, v0_7);
}
if (bh & 2) {
uint16_t* o7 = (uint16_t*) ((uintptr_t) o + oN_stride);
*((int*) o7) = _mm_cvtsi128_si32(v0_7);
uint16_t *o6 = (uint16_t*) ((uintptr_t) o7 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 7) {
o6 = o7;
}
*((int*) o6) = _mm_cvtsi128_si32(v0_6);
uint16_t *o5 = (uint16_t*) ((uintptr_t) o6 - output_stride);
if XNN_UNPREDICTABLE(block_width < 7) {
o5 = o7;
}
*((int*) o5) = _mm_cvtsi128_si32(v0_5);
uint16_t *o4 = (uint16_t*) ((uintptr_t) o5 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 5) {
o4 = o7;
}
*((int*) o4) = _mm_cvtsi128_si32(v0_4);
uint16_t *o3 = (uint16_t*) ((uintptr_t) o4 - output_stride);
if XNN_UNPREDICTABLE(block_width < 5) {
o3 = o7;
}
*((int*) o3) = _mm_cvtsi128_si32(v0_3);
uint16_t *o2 = (uint16_t*) ((uintptr_t) o3 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 3) {
o2 = o7;
}
*((int*) o2) = _mm_cvtsi128_si32(v0_2);
uint16_t *o1 = (uint16_t*) ((uintptr_t) o2 - output_stride);
if XNN_UNPREDICTABLE(block_width < 3) {
o1 = o7;
}
*((int*) o1) = _mm_cvtsi128_si32(v0_1);
*((int*) o) = _mm_cvtsi128_si32(v0_0);
o += 2;
v0_0 = _mm_srli_epi64(v0_0, 32);
v0_1 = _mm_srli_epi64(v0_1, 32);
v0_2 = _mm_srli_epi64(v0_2, 32);
v0_3 = _mm_srli_epi64(v0_3, 32);
v0_4 = _mm_srli_epi64(v0_4, 32);
v0_5 = _mm_srli_epi64(v0_5, 32);
v0_6 = _mm_srli_epi64(v0_6, 32);
v0_7 = _mm_srli_epi64(v0_7, 32);
}
if (bh & 1) {
uint16_t* o7 = (uint16_t*) ((uintptr_t) o + oN_stride);
*((uint16_t*) o7) = (uint16_t) _mm_cvtsi128_si32(v0_7);
uint16_t *o6 = (uint16_t*) ((uintptr_t) o7 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 7) {
o6 = o7;
}
*((uint16_t*) o6) = (uint16_t) _mm_cvtsi128_si32(v0_6);
uint16_t *o5 = (uint16_t*) ((uintptr_t) o6 - output_stride);
if XNN_UNPREDICTABLE(block_width < 7) {
o5 = o7;
}
*((uint16_t*) o5) = (uint16_t) _mm_cvtsi128_si32(v0_5);
uint16_t *o4 = (uint16_t*) ((uintptr_t) o5 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 5) {
o4 = o7;
}
*((uint16_t*) o4) = (uint16_t) _mm_cvtsi128_si32(v0_4);
uint16_t *o3 = (uint16_t*) ((uintptr_t) o4 - output_stride);
if XNN_UNPREDICTABLE(block_width < 5) {
o3 = o7;
}
*((uint16_t*) o3) = (uint16_t) _mm_cvtsi128_si32(v0_3);
uint16_t *o2 = (uint16_t*) ((uintptr_t) o3 - output_stride);
if XNN_UNPREDICTABLE(block_width <= 3) {
o2 = o7;
}
*((uint16_t*) o2) = (uint16_t) _mm_cvtsi128_si32(v0_2);
uint16_t *o1 = (uint16_t*) ((uintptr_t) o2 - output_stride);
if XNN_UNPREDICTABLE(block_width < 3) {
o1 = o7;
}
*((uint16_t*) o1) = (uint16_t) _mm_cvtsi128_si32(v0_1);
*((uint16_t*) o) = (uint16_t) _mm_cvtsi128_si32(v0_0);
}
}
i0 = (const uint16_t*) ((uintptr_t) i0 + input_reset);
o = (uint16_t*) ((uintptr_t) o + output_reset);
block_width = doz(block_width, tile_width);
} while (block_width != 0);
}
|
462324.c | /* Copyright 2021 Ramon Imbao
*
* 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 QMK_KEYBOARD_H
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT_all(
KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_BSPC, KC_INS, KC_HOME, KC_PGUP,
KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_DEL, KC_END, KC_PGDN,
KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_ENT,
KC_LSFT, KC_NO, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, MO(1), KC_UP,
KC_LCTL, KC_LGUI, KC_LALT, KC_NO, KC_SPC, KC_NO, KC_RALT, KC_RGUI, KC_MENU, KC_RCTL, KC_LEFT, KC_DOWN, KC_RGHT
),
[1] = LAYOUT_all(
RESET, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______
),
};
|
445462.c | // SPDX-License-Identifier: GPL-2.0+
/*
* AmLogic Meson-AXG Clock Controller Driver
*
* Copyright (c) 2016 Baylibre SAS.
* Author: Michael Turquette <[email protected]>
*
* Copyright (c) 2017 Amlogic, inc.
* Author: Qiufang Dai <[email protected]>
*/
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/init.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/mfd/syscon.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include "clkc.h"
#include "axg.h"
static DEFINE_SPINLOCK(meson_clk_lock);
static struct clk_regmap axg_fixed_pll = {
.data = &(struct meson_clk_pll_data){
.m = {
.reg_off = HHI_MPLL_CNTL,
.shift = 0,
.width = 9,
},
.n = {
.reg_off = HHI_MPLL_CNTL,
.shift = 9,
.width = 5,
},
.od = {
.reg_off = HHI_MPLL_CNTL,
.shift = 16,
.width = 2,
},
.frac = {
.reg_off = HHI_MPLL_CNTL2,
.shift = 0,
.width = 12,
},
.l = {
.reg_off = HHI_MPLL_CNTL,
.shift = 31,
.width = 1,
},
.rst = {
.reg_off = HHI_MPLL_CNTL,
.shift = 29,
.width = 1,
},
},
.hw.init = &(struct clk_init_data){
.name = "fixed_pll",
.ops = &meson_clk_pll_ro_ops,
.parent_names = (const char *[]){ "xtal" },
.num_parents = 1,
},
};
static struct clk_regmap axg_sys_pll = {
.data = &(struct meson_clk_pll_data){
.m = {
.reg_off = HHI_SYS_PLL_CNTL,
.shift = 0,
.width = 9,
},
.n = {
.reg_off = HHI_SYS_PLL_CNTL,
.shift = 9,
.width = 5,
},
.od = {
.reg_off = HHI_SYS_PLL_CNTL,
.shift = 16,
.width = 2,
},
.l = {
.reg_off = HHI_SYS_PLL_CNTL,
.shift = 31,
.width = 1,
},
.rst = {
.reg_off = HHI_SYS_PLL_CNTL,
.shift = 29,
.width = 1,
},
},
.hw.init = &(struct clk_init_data){
.name = "sys_pll",
.ops = &meson_clk_pll_ro_ops,
.parent_names = (const char *[]){ "xtal" },
.num_parents = 1,
.flags = CLK_GET_RATE_NOCACHE,
},
};
static const struct pll_rate_table axg_gp0_pll_rate_table[] = {
PLL_RATE(240000000, 40, 1, 2),
PLL_RATE(246000000, 41, 1, 2),
PLL_RATE(252000000, 42, 1, 2),
PLL_RATE(258000000, 43, 1, 2),
PLL_RATE(264000000, 44, 1, 2),
PLL_RATE(270000000, 45, 1, 2),
PLL_RATE(276000000, 46, 1, 2),
PLL_RATE(282000000, 47, 1, 2),
PLL_RATE(288000000, 48, 1, 2),
PLL_RATE(294000000, 49, 1, 2),
PLL_RATE(300000000, 50, 1, 2),
PLL_RATE(306000000, 51, 1, 2),
PLL_RATE(312000000, 52, 1, 2),
PLL_RATE(318000000, 53, 1, 2),
PLL_RATE(324000000, 54, 1, 2),
PLL_RATE(330000000, 55, 1, 2),
PLL_RATE(336000000, 56, 1, 2),
PLL_RATE(342000000, 57, 1, 2),
PLL_RATE(348000000, 58, 1, 2),
PLL_RATE(354000000, 59, 1, 2),
PLL_RATE(360000000, 60, 1, 2),
PLL_RATE(366000000, 61, 1, 2),
PLL_RATE(372000000, 62, 1, 2),
PLL_RATE(378000000, 63, 1, 2),
PLL_RATE(384000000, 64, 1, 2),
PLL_RATE(390000000, 65, 1, 3),
PLL_RATE(396000000, 66, 1, 3),
PLL_RATE(402000000, 67, 1, 3),
PLL_RATE(408000000, 68, 1, 3),
PLL_RATE(480000000, 40, 1, 1),
PLL_RATE(492000000, 41, 1, 1),
PLL_RATE(504000000, 42, 1, 1),
PLL_RATE(516000000, 43, 1, 1),
PLL_RATE(528000000, 44, 1, 1),
PLL_RATE(540000000, 45, 1, 1),
PLL_RATE(552000000, 46, 1, 1),
PLL_RATE(564000000, 47, 1, 1),
PLL_RATE(576000000, 48, 1, 1),
PLL_RATE(588000000, 49, 1, 1),
PLL_RATE(600000000, 50, 1, 1),
PLL_RATE(612000000, 51, 1, 1),
PLL_RATE(624000000, 52, 1, 1),
PLL_RATE(636000000, 53, 1, 1),
PLL_RATE(648000000, 54, 1, 1),
PLL_RATE(660000000, 55, 1, 1),
PLL_RATE(672000000, 56, 1, 1),
PLL_RATE(684000000, 57, 1, 1),
PLL_RATE(696000000, 58, 1, 1),
PLL_RATE(708000000, 59, 1, 1),
PLL_RATE(720000000, 60, 1, 1),
PLL_RATE(732000000, 61, 1, 1),
PLL_RATE(744000000, 62, 1, 1),
PLL_RATE(756000000, 63, 1, 1),
PLL_RATE(768000000, 64, 1, 1),
PLL_RATE(780000000, 65, 1, 1),
PLL_RATE(792000000, 66, 1, 1),
PLL_RATE(804000000, 67, 1, 1),
PLL_RATE(816000000, 68, 1, 1),
PLL_RATE(960000000, 40, 1, 0),
PLL_RATE(984000000, 41, 1, 0),
PLL_RATE(1008000000, 42, 1, 0),
PLL_RATE(1032000000, 43, 1, 0),
PLL_RATE(1056000000, 44, 1, 0),
PLL_RATE(1080000000, 45, 1, 0),
PLL_RATE(1104000000, 46, 1, 0),
PLL_RATE(1128000000, 47, 1, 0),
PLL_RATE(1152000000, 48, 1, 0),
PLL_RATE(1176000000, 49, 1, 0),
PLL_RATE(1200000000, 50, 1, 0),
PLL_RATE(1224000000, 51, 1, 0),
PLL_RATE(1248000000, 52, 1, 0),
PLL_RATE(1272000000, 53, 1, 0),
PLL_RATE(1296000000, 54, 1, 0),
PLL_RATE(1320000000, 55, 1, 0),
PLL_RATE(1344000000, 56, 1, 0),
PLL_RATE(1368000000, 57, 1, 0),
PLL_RATE(1392000000, 58, 1, 0),
PLL_RATE(1416000000, 59, 1, 0),
PLL_RATE(1440000000, 60, 1, 0),
PLL_RATE(1464000000, 61, 1, 0),
PLL_RATE(1488000000, 62, 1, 0),
PLL_RATE(1512000000, 63, 1, 0),
PLL_RATE(1536000000, 64, 1, 0),
PLL_RATE(1560000000, 65, 1, 0),
PLL_RATE(1584000000, 66, 1, 0),
PLL_RATE(1608000000, 67, 1, 0),
PLL_RATE(1632000000, 68, 1, 0),
{ /* sentinel */ },
};
static const struct reg_sequence axg_gp0_init_regs[] = {
{ .reg = HHI_GP0_PLL_CNTL1, .def = 0xc084b000 },
{ .reg = HHI_GP0_PLL_CNTL2, .def = 0xb75020be },
{ .reg = HHI_GP0_PLL_CNTL3, .def = 0x0a59a288 },
{ .reg = HHI_GP0_PLL_CNTL4, .def = 0xc000004d },
{ .reg = HHI_GP0_PLL_CNTL5, .def = 0x00078000 },
{ .reg = HHI_GP0_PLL_CNTL, .def = 0x40010250 },
};
static struct clk_regmap axg_gp0_pll = {
.data = &(struct meson_clk_pll_data){
.m = {
.reg_off = HHI_GP0_PLL_CNTL,
.shift = 0,
.width = 9,
},
.n = {
.reg_off = HHI_GP0_PLL_CNTL,
.shift = 9,
.width = 5,
},
.od = {
.reg_off = HHI_GP0_PLL_CNTL,
.shift = 16,
.width = 2,
},
.frac = {
.reg_off = HHI_GP0_PLL_CNTL1,
.shift = 0,
.width = 10,
},
.l = {
.reg_off = HHI_GP0_PLL_CNTL,
.shift = 31,
.width = 1,
},
.rst = {
.reg_off = HHI_GP0_PLL_CNTL,
.shift = 29,
.width = 1,
},
.table = axg_gp0_pll_rate_table,
.init_regs = axg_gp0_init_regs,
.init_count = ARRAY_SIZE(axg_gp0_init_regs),
},
.hw.init = &(struct clk_init_data){
.name = "gp0_pll",
.ops = &meson_clk_pll_ops,
.parent_names = (const char *[]){ "xtal" },
.num_parents = 1,
},
};
static const struct reg_sequence axg_hifi_init_regs[] = {
{ .reg = HHI_HIFI_PLL_CNTL1, .def = 0xc084b000 },
{ .reg = HHI_HIFI_PLL_CNTL2, .def = 0xb75020be },
{ .reg = HHI_HIFI_PLL_CNTL3, .def = 0x0a6a3a88 },
{ .reg = HHI_HIFI_PLL_CNTL4, .def = 0xc000004d },
{ .reg = HHI_HIFI_PLL_CNTL5, .def = 0x00058000 },
{ .reg = HHI_HIFI_PLL_CNTL, .def = 0x40010250 },
};
static struct clk_regmap axg_hifi_pll = {
.data = &(struct meson_clk_pll_data){
.m = {
.reg_off = HHI_HIFI_PLL_CNTL,
.shift = 0,
.width = 9,
},
.n = {
.reg_off = HHI_HIFI_PLL_CNTL,
.shift = 9,
.width = 5,
},
.od = {
.reg_off = HHI_HIFI_PLL_CNTL,
.shift = 16,
.width = 2,
},
.frac = {
.reg_off = HHI_HIFI_PLL_CNTL5,
.shift = 0,
.width = 13,
},
.l = {
.reg_off = HHI_HIFI_PLL_CNTL,
.shift = 31,
.width = 1,
},
.rst = {
.reg_off = HHI_HIFI_PLL_CNTL,
.shift = 29,
.width = 1,
},
.table = axg_gp0_pll_rate_table,
.init_regs = axg_hifi_init_regs,
.init_count = ARRAY_SIZE(axg_hifi_init_regs),
.flags = CLK_MESON_PLL_ROUND_CLOSEST,
},
.hw.init = &(struct clk_init_data){
.name = "hifi_pll",
.ops = &meson_clk_pll_ops,
.parent_names = (const char *[]){ "xtal" },
.num_parents = 1,
},
};
static struct clk_fixed_factor axg_fclk_div2_div = {
.mult = 1,
.div = 2,
.hw.init = &(struct clk_init_data){
.name = "fclk_div2_div",
.ops = &clk_fixed_factor_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_fclk_div2 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL6,
.bit_idx = 27,
},
.hw.init = &(struct clk_init_data){
.name = "fclk_div2",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "fclk_div2_div" },
.num_parents = 1,
},
};
static struct clk_fixed_factor axg_fclk_div3_div = {
.mult = 1,
.div = 3,
.hw.init = &(struct clk_init_data){
.name = "fclk_div3_div",
.ops = &clk_fixed_factor_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_fclk_div3 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL6,
.bit_idx = 28,
},
.hw.init = &(struct clk_init_data){
.name = "fclk_div3",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "fclk_div3_div" },
.num_parents = 1,
},
};
static struct clk_fixed_factor axg_fclk_div4_div = {
.mult = 1,
.div = 4,
.hw.init = &(struct clk_init_data){
.name = "fclk_div4_div",
.ops = &clk_fixed_factor_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_fclk_div4 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL6,
.bit_idx = 29,
},
.hw.init = &(struct clk_init_data){
.name = "fclk_div4",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "fclk_div4_div" },
.num_parents = 1,
},
};
static struct clk_fixed_factor axg_fclk_div5_div = {
.mult = 1,
.div = 5,
.hw.init = &(struct clk_init_data){
.name = "fclk_div5_div",
.ops = &clk_fixed_factor_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_fclk_div5 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL6,
.bit_idx = 30,
},
.hw.init = &(struct clk_init_data){
.name = "fclk_div5",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "fclk_div5_div" },
.num_parents = 1,
},
};
static struct clk_fixed_factor axg_fclk_div7_div = {
.mult = 1,
.div = 7,
.hw.init = &(struct clk_init_data){
.name = "fclk_div7_div",
.ops = &clk_fixed_factor_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_fclk_div7 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL6,
.bit_idx = 31,
},
.hw.init = &(struct clk_init_data){
.name = "fclk_div7",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "fclk_div7_div" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll_prediv = {
.data = &(struct clk_regmap_div_data){
.offset = HHI_MPLL_CNTL5,
.shift = 12,
.width = 1,
},
.hw.init = &(struct clk_init_data){
.name = "mpll_prediv",
.ops = &clk_regmap_divider_ro_ops,
.parent_names = (const char *[]){ "fixed_pll" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll0_div = {
.data = &(struct meson_clk_mpll_data){
.sdm = {
.reg_off = HHI_MPLL_CNTL7,
.shift = 0,
.width = 14,
},
.sdm_en = {
.reg_off = HHI_MPLL_CNTL7,
.shift = 15,
.width = 1,
},
.n2 = {
.reg_off = HHI_MPLL_CNTL7,
.shift = 16,
.width = 9,
},
.ssen = {
.reg_off = HHI_MPLL_CNTL,
.shift = 25,
.width = 1,
},
.misc = {
.reg_off = HHI_PLL_TOP_MISC,
.shift = 0,
.width = 1,
},
.lock = &meson_clk_lock,
},
.hw.init = &(struct clk_init_data){
.name = "mpll0_div",
.ops = &meson_clk_mpll_ops,
.parent_names = (const char *[]){ "mpll_prediv" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll0 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL7,
.bit_idx = 14,
},
.hw.init = &(struct clk_init_data){
.name = "mpll0",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "mpll0_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_mpll1_div = {
.data = &(struct meson_clk_mpll_data){
.sdm = {
.reg_off = HHI_MPLL_CNTL8,
.shift = 0,
.width = 14,
},
.sdm_en = {
.reg_off = HHI_MPLL_CNTL8,
.shift = 15,
.width = 1,
},
.n2 = {
.reg_off = HHI_MPLL_CNTL8,
.shift = 16,
.width = 9,
},
.misc = {
.reg_off = HHI_PLL_TOP_MISC,
.shift = 1,
.width = 1,
},
.lock = &meson_clk_lock,
},
.hw.init = &(struct clk_init_data){
.name = "mpll1_div",
.ops = &meson_clk_mpll_ops,
.parent_names = (const char *[]){ "mpll_prediv" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll1 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL8,
.bit_idx = 14,
},
.hw.init = &(struct clk_init_data){
.name = "mpll1",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "mpll1_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_mpll2_div = {
.data = &(struct meson_clk_mpll_data){
.sdm = {
.reg_off = HHI_MPLL_CNTL9,
.shift = 0,
.width = 14,
},
.sdm_en = {
.reg_off = HHI_MPLL_CNTL9,
.shift = 15,
.width = 1,
},
.n2 = {
.reg_off = HHI_MPLL_CNTL9,
.shift = 16,
.width = 9,
},
.misc = {
.reg_off = HHI_PLL_TOP_MISC,
.shift = 2,
.width = 1,
},
.lock = &meson_clk_lock,
},
.hw.init = &(struct clk_init_data){
.name = "mpll2_div",
.ops = &meson_clk_mpll_ops,
.parent_names = (const char *[]){ "mpll_prediv" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll2 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL_CNTL9,
.bit_idx = 14,
},
.hw.init = &(struct clk_init_data){
.name = "mpll2",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "mpll2_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_mpll3_div = {
.data = &(struct meson_clk_mpll_data){
.sdm = {
.reg_off = HHI_MPLL3_CNTL0,
.shift = 12,
.width = 14,
},
.sdm_en = {
.reg_off = HHI_MPLL3_CNTL0,
.shift = 11,
.width = 1,
},
.n2 = {
.reg_off = HHI_MPLL3_CNTL0,
.shift = 2,
.width = 9,
},
.misc = {
.reg_off = HHI_PLL_TOP_MISC,
.shift = 3,
.width = 1,
},
.lock = &meson_clk_lock,
},
.hw.init = &(struct clk_init_data){
.name = "mpll3_div",
.ops = &meson_clk_mpll_ops,
.parent_names = (const char *[]){ "mpll_prediv" },
.num_parents = 1,
},
};
static struct clk_regmap axg_mpll3 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPLL3_CNTL0,
.bit_idx = 0,
},
.hw.init = &(struct clk_init_data){
.name = "mpll3",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "mpll3_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static u32 mux_table_clk81[] = { 0, 2, 3, 4, 5, 6, 7 };
static const char * const clk81_parent_names[] = {
"xtal", "fclk_div7", "mpll1", "mpll2", "fclk_div4",
"fclk_div3", "fclk_div5"
};
static struct clk_regmap axg_mpeg_clk_sel = {
.data = &(struct clk_regmap_mux_data){
.offset = HHI_MPEG_CLK_CNTL,
.mask = 0x7,
.shift = 12,
.table = mux_table_clk81,
},
.hw.init = &(struct clk_init_data){
.name = "mpeg_clk_sel",
.ops = &clk_regmap_mux_ro_ops,
.parent_names = clk81_parent_names,
.num_parents = ARRAY_SIZE(clk81_parent_names),
},
};
static struct clk_regmap axg_mpeg_clk_div = {
.data = &(struct clk_regmap_div_data){
.offset = HHI_MPEG_CLK_CNTL,
.shift = 0,
.width = 7,
},
.hw.init = &(struct clk_init_data){
.name = "mpeg_clk_div",
.ops = &clk_regmap_divider_ops,
.parent_names = (const char *[]){ "mpeg_clk_sel" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_clk81 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_MPEG_CLK_CNTL,
.bit_idx = 7,
},
.hw.init = &(struct clk_init_data){
.name = "clk81",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "mpeg_clk_div" },
.num_parents = 1,
.flags = (CLK_SET_RATE_PARENT | CLK_IS_CRITICAL),
},
};
static const char * const axg_sd_emmc_clk0_parent_names[] = {
"xtal", "fclk_div2", "fclk_div3", "fclk_div5", "fclk_div7",
/*
* Following these parent clocks, we should also have had mpll2, mpll3
* and gp0_pll but these clocks are too precious to be used here. All
* the necessary rates for MMC and NAND operation can be acheived using
* xtal or fclk_div clocks
*/
};
/* SDcard clock */
static struct clk_regmap axg_sd_emmc_b_clk0_sel = {
.data = &(struct clk_regmap_mux_data){
.offset = HHI_SD_EMMC_CLK_CNTL,
.mask = 0x7,
.shift = 25,
},
.hw.init = &(struct clk_init_data) {
.name = "sd_emmc_b_clk0_sel",
.ops = &clk_regmap_mux_ops,
.parent_names = axg_sd_emmc_clk0_parent_names,
.num_parents = ARRAY_SIZE(axg_sd_emmc_clk0_parent_names),
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_sd_emmc_b_clk0_div = {
.data = &(struct clk_regmap_div_data){
.offset = HHI_SD_EMMC_CLK_CNTL,
.shift = 16,
.width = 7,
.flags = CLK_DIVIDER_ROUND_CLOSEST,
},
.hw.init = &(struct clk_init_data) {
.name = "sd_emmc_b_clk0_div",
.ops = &clk_regmap_divider_ops,
.parent_names = (const char *[]){ "sd_emmc_b_clk0_sel" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_sd_emmc_b_clk0 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_SD_EMMC_CLK_CNTL,
.bit_idx = 23,
},
.hw.init = &(struct clk_init_data){
.name = "sd_emmc_b_clk0",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "sd_emmc_b_clk0_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
/* EMMC/NAND clock */
static struct clk_regmap axg_sd_emmc_c_clk0_sel = {
.data = &(struct clk_regmap_mux_data){
.offset = HHI_NAND_CLK_CNTL,
.mask = 0x7,
.shift = 9,
},
.hw.init = &(struct clk_init_data) {
.name = "sd_emmc_c_clk0_sel",
.ops = &clk_regmap_mux_ops,
.parent_names = axg_sd_emmc_clk0_parent_names,
.num_parents = ARRAY_SIZE(axg_sd_emmc_clk0_parent_names),
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_sd_emmc_c_clk0_div = {
.data = &(struct clk_regmap_div_data){
.offset = HHI_NAND_CLK_CNTL,
.shift = 0,
.width = 7,
.flags = CLK_DIVIDER_ROUND_CLOSEST,
},
.hw.init = &(struct clk_init_data) {
.name = "sd_emmc_c_clk0_div",
.ops = &clk_regmap_divider_ops,
.parent_names = (const char *[]){ "sd_emmc_c_clk0_sel" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
static struct clk_regmap axg_sd_emmc_c_clk0 = {
.data = &(struct clk_regmap_gate_data){
.offset = HHI_NAND_CLK_CNTL,
.bit_idx = 7,
},
.hw.init = &(struct clk_init_data){
.name = "sd_emmc_c_clk0",
.ops = &clk_regmap_gate_ops,
.parent_names = (const char *[]){ "sd_emmc_c_clk0_div" },
.num_parents = 1,
.flags = CLK_SET_RATE_PARENT,
},
};
/* Everything Else (EE) domain gates */
static MESON_GATE(axg_ddr, HHI_GCLK_MPEG0, 0);
static MESON_GATE(axg_audio_locker, HHI_GCLK_MPEG0, 2);
static MESON_GATE(axg_mipi_dsi_host, HHI_GCLK_MPEG0, 3);
static MESON_GATE(axg_isa, HHI_GCLK_MPEG0, 5);
static MESON_GATE(axg_pl301, HHI_GCLK_MPEG0, 6);
static MESON_GATE(axg_periphs, HHI_GCLK_MPEG0, 7);
static MESON_GATE(axg_spicc_0, HHI_GCLK_MPEG0, 8);
static MESON_GATE(axg_i2c, HHI_GCLK_MPEG0, 9);
static MESON_GATE(axg_rng0, HHI_GCLK_MPEG0, 12);
static MESON_GATE(axg_uart0, HHI_GCLK_MPEG0, 13);
static MESON_GATE(axg_mipi_dsi_phy, HHI_GCLK_MPEG0, 14);
static MESON_GATE(axg_spicc_1, HHI_GCLK_MPEG0, 15);
static MESON_GATE(axg_pcie_a, HHI_GCLK_MPEG0, 16);
static MESON_GATE(axg_pcie_b, HHI_GCLK_MPEG0, 17);
static MESON_GATE(axg_hiu_reg, HHI_GCLK_MPEG0, 19);
static MESON_GATE(axg_assist_misc, HHI_GCLK_MPEG0, 23);
static MESON_GATE(axg_emmc_b, HHI_GCLK_MPEG0, 25);
static MESON_GATE(axg_emmc_c, HHI_GCLK_MPEG0, 26);
static MESON_GATE(axg_dma, HHI_GCLK_MPEG0, 27);
static MESON_GATE(axg_spi, HHI_GCLK_MPEG0, 30);
static MESON_GATE(axg_audio, HHI_GCLK_MPEG1, 0);
static MESON_GATE(axg_eth_core, HHI_GCLK_MPEG1, 3);
static MESON_GATE(axg_uart1, HHI_GCLK_MPEG1, 16);
static MESON_GATE(axg_g2d, HHI_GCLK_MPEG1, 20);
static MESON_GATE(axg_usb0, HHI_GCLK_MPEG1, 21);
static MESON_GATE(axg_usb1, HHI_GCLK_MPEG1, 22);
static MESON_GATE(axg_reset, HHI_GCLK_MPEG1, 23);
static MESON_GATE(axg_usb_general, HHI_GCLK_MPEG1, 26);
static MESON_GATE(axg_ahb_arb0, HHI_GCLK_MPEG1, 29);
static MESON_GATE(axg_efuse, HHI_GCLK_MPEG1, 30);
static MESON_GATE(axg_boot_rom, HHI_GCLK_MPEG1, 31);
static MESON_GATE(axg_ahb_data_bus, HHI_GCLK_MPEG2, 1);
static MESON_GATE(axg_ahb_ctrl_bus, HHI_GCLK_MPEG2, 2);
static MESON_GATE(axg_usb1_to_ddr, HHI_GCLK_MPEG2, 8);
static MESON_GATE(axg_usb0_to_ddr, HHI_GCLK_MPEG2, 9);
static MESON_GATE(axg_mmc_pclk, HHI_GCLK_MPEG2, 11);
static MESON_GATE(axg_vpu_intr, HHI_GCLK_MPEG2, 25);
static MESON_GATE(axg_sec_ahb_ahb3_bridge, HHI_GCLK_MPEG2, 26);
static MESON_GATE(axg_gic, HHI_GCLK_MPEG2, 30);
/* Always On (AO) domain gates */
static MESON_GATE(axg_ao_media_cpu, HHI_GCLK_AO, 0);
static MESON_GATE(axg_ao_ahb_sram, HHI_GCLK_AO, 1);
static MESON_GATE(axg_ao_ahb_bus, HHI_GCLK_AO, 2);
static MESON_GATE(axg_ao_iface, HHI_GCLK_AO, 3);
static MESON_GATE(axg_ao_i2c, HHI_GCLK_AO, 4);
/* Array of all clocks provided by this provider */
static struct clk_hw_onecell_data axg_hw_onecell_data = {
.hws = {
[CLKID_SYS_PLL] = &axg_sys_pll.hw,
[CLKID_FIXED_PLL] = &axg_fixed_pll.hw,
[CLKID_FCLK_DIV2] = &axg_fclk_div2.hw,
[CLKID_FCLK_DIV3] = &axg_fclk_div3.hw,
[CLKID_FCLK_DIV4] = &axg_fclk_div4.hw,
[CLKID_FCLK_DIV5] = &axg_fclk_div5.hw,
[CLKID_FCLK_DIV7] = &axg_fclk_div7.hw,
[CLKID_GP0_PLL] = &axg_gp0_pll.hw,
[CLKID_MPEG_SEL] = &axg_mpeg_clk_sel.hw,
[CLKID_MPEG_DIV] = &axg_mpeg_clk_div.hw,
[CLKID_CLK81] = &axg_clk81.hw,
[CLKID_MPLL0] = &axg_mpll0.hw,
[CLKID_MPLL1] = &axg_mpll1.hw,
[CLKID_MPLL2] = &axg_mpll2.hw,
[CLKID_MPLL3] = &axg_mpll3.hw,
[CLKID_DDR] = &axg_ddr.hw,
[CLKID_AUDIO_LOCKER] = &axg_audio_locker.hw,
[CLKID_MIPI_DSI_HOST] = &axg_mipi_dsi_host.hw,
[CLKID_ISA] = &axg_isa.hw,
[CLKID_PL301] = &axg_pl301.hw,
[CLKID_PERIPHS] = &axg_periphs.hw,
[CLKID_SPICC0] = &axg_spicc_0.hw,
[CLKID_I2C] = &axg_i2c.hw,
[CLKID_RNG0] = &axg_rng0.hw,
[CLKID_UART0] = &axg_uart0.hw,
[CLKID_MIPI_DSI_PHY] = &axg_mipi_dsi_phy.hw,
[CLKID_SPICC1] = &axg_spicc_1.hw,
[CLKID_PCIE_A] = &axg_pcie_a.hw,
[CLKID_PCIE_B] = &axg_pcie_b.hw,
[CLKID_HIU_IFACE] = &axg_hiu_reg.hw,
[CLKID_ASSIST_MISC] = &axg_assist_misc.hw,
[CLKID_SD_EMMC_B] = &axg_emmc_b.hw,
[CLKID_SD_EMMC_C] = &axg_emmc_c.hw,
[CLKID_DMA] = &axg_dma.hw,
[CLKID_SPI] = &axg_spi.hw,
[CLKID_AUDIO] = &axg_audio.hw,
[CLKID_ETH] = &axg_eth_core.hw,
[CLKID_UART1] = &axg_uart1.hw,
[CLKID_G2D] = &axg_g2d.hw,
[CLKID_USB0] = &axg_usb0.hw,
[CLKID_USB1] = &axg_usb1.hw,
[CLKID_RESET] = &axg_reset.hw,
[CLKID_USB] = &axg_usb_general.hw,
[CLKID_AHB_ARB0] = &axg_ahb_arb0.hw,
[CLKID_EFUSE] = &axg_efuse.hw,
[CLKID_BOOT_ROM] = &axg_boot_rom.hw,
[CLKID_AHB_DATA_BUS] = &axg_ahb_data_bus.hw,
[CLKID_AHB_CTRL_BUS] = &axg_ahb_ctrl_bus.hw,
[CLKID_USB1_DDR_BRIDGE] = &axg_usb1_to_ddr.hw,
[CLKID_USB0_DDR_BRIDGE] = &axg_usb0_to_ddr.hw,
[CLKID_MMC_PCLK] = &axg_mmc_pclk.hw,
[CLKID_VPU_INTR] = &axg_vpu_intr.hw,
[CLKID_SEC_AHB_AHB3_BRIDGE] = &axg_sec_ahb_ahb3_bridge.hw,
[CLKID_GIC] = &axg_gic.hw,
[CLKID_AO_MEDIA_CPU] = &axg_ao_media_cpu.hw,
[CLKID_AO_AHB_SRAM] = &axg_ao_ahb_sram.hw,
[CLKID_AO_AHB_BUS] = &axg_ao_ahb_bus.hw,
[CLKID_AO_IFACE] = &axg_ao_iface.hw,
[CLKID_AO_I2C] = &axg_ao_i2c.hw,
[CLKID_SD_EMMC_B_CLK0_SEL] = &axg_sd_emmc_b_clk0_sel.hw,
[CLKID_SD_EMMC_B_CLK0_DIV] = &axg_sd_emmc_b_clk0_div.hw,
[CLKID_SD_EMMC_B_CLK0] = &axg_sd_emmc_b_clk0.hw,
[CLKID_SD_EMMC_C_CLK0_SEL] = &axg_sd_emmc_c_clk0_sel.hw,
[CLKID_SD_EMMC_C_CLK0_DIV] = &axg_sd_emmc_c_clk0_div.hw,
[CLKID_SD_EMMC_C_CLK0] = &axg_sd_emmc_c_clk0.hw,
[CLKID_MPLL0_DIV] = &axg_mpll0_div.hw,
[CLKID_MPLL1_DIV] = &axg_mpll1_div.hw,
[CLKID_MPLL2_DIV] = &axg_mpll2_div.hw,
[CLKID_MPLL3_DIV] = &axg_mpll3_div.hw,
[CLKID_HIFI_PLL] = &axg_hifi_pll.hw,
[CLKID_MPLL_PREDIV] = &axg_mpll_prediv.hw,
[CLKID_FCLK_DIV2_DIV] = &axg_fclk_div2_div.hw,
[CLKID_FCLK_DIV3_DIV] = &axg_fclk_div3_div.hw,
[CLKID_FCLK_DIV4_DIV] = &axg_fclk_div4_div.hw,
[CLKID_FCLK_DIV5_DIV] = &axg_fclk_div5_div.hw,
[CLKID_FCLK_DIV7_DIV] = &axg_fclk_div7_div.hw,
[NR_CLKS] = NULL,
},
.num = NR_CLKS,
};
/* Convenience table to populate regmap in .probe */
static struct clk_regmap *const axg_clk_regmaps[] = {
&axg_clk81,
&axg_ddr,
&axg_audio_locker,
&axg_mipi_dsi_host,
&axg_isa,
&axg_pl301,
&axg_periphs,
&axg_spicc_0,
&axg_i2c,
&axg_rng0,
&axg_uart0,
&axg_mipi_dsi_phy,
&axg_spicc_1,
&axg_pcie_a,
&axg_pcie_b,
&axg_hiu_reg,
&axg_assist_misc,
&axg_emmc_b,
&axg_emmc_c,
&axg_dma,
&axg_spi,
&axg_audio,
&axg_eth_core,
&axg_uart1,
&axg_g2d,
&axg_usb0,
&axg_usb1,
&axg_reset,
&axg_usb_general,
&axg_ahb_arb0,
&axg_efuse,
&axg_boot_rom,
&axg_ahb_data_bus,
&axg_ahb_ctrl_bus,
&axg_usb1_to_ddr,
&axg_usb0_to_ddr,
&axg_mmc_pclk,
&axg_vpu_intr,
&axg_sec_ahb_ahb3_bridge,
&axg_gic,
&axg_ao_media_cpu,
&axg_ao_ahb_sram,
&axg_ao_ahb_bus,
&axg_ao_iface,
&axg_ao_i2c,
&axg_sd_emmc_b_clk0,
&axg_sd_emmc_c_clk0,
&axg_mpeg_clk_div,
&axg_sd_emmc_b_clk0_div,
&axg_sd_emmc_c_clk0_div,
&axg_mpeg_clk_sel,
&axg_sd_emmc_b_clk0_sel,
&axg_sd_emmc_c_clk0_sel,
&axg_mpll0,
&axg_mpll1,
&axg_mpll2,
&axg_mpll3,
&axg_mpll0_div,
&axg_mpll1_div,
&axg_mpll2_div,
&axg_mpll3_div,
&axg_fixed_pll,
&axg_sys_pll,
&axg_gp0_pll,
&axg_hifi_pll,
&axg_mpll_prediv,
&axg_fclk_div2,
&axg_fclk_div3,
&axg_fclk_div4,
&axg_fclk_div5,
&axg_fclk_div7,
};
static const struct of_device_id clkc_match_table[] = {
{ .compatible = "amlogic,axg-clkc" },
{}
};
static const struct regmap_config clkc_regmap_config = {
.reg_bits = 32,
.val_bits = 32,
.reg_stride = 4,
};
static int axg_clkc_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
void __iomem *clk_base = NULL;
struct regmap *map;
int ret, i;
/* Get the hhi system controller node if available */
map = syscon_node_to_regmap(of_get_parent(dev->of_node));
if (IS_ERR(map)) {
dev_err(dev,
"failed to get HHI regmap - Trying obsolete regs\n");
/*
* FIXME: HHI registers should be accessed through
* the appropriate system controller. This is required because
* there is more than just clocks in this register space
*
* This fallback method is only provided temporarily until
* all the platform DTs are properly using the syscon node
*/
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EINVAL;
clk_base = devm_ioremap(dev, res->start, resource_size(res));
if (!clk_base) {
dev_err(dev, "Unable to map clk base\n");
return -ENXIO;
}
map = devm_regmap_init_mmio(dev, clk_base,
&clkc_regmap_config);
if (IS_ERR(map))
return PTR_ERR(map);
}
/* Populate regmap for the regmap backed clocks */
for (i = 0; i < ARRAY_SIZE(axg_clk_regmaps); i++)
axg_clk_regmaps[i]->map = map;
for (i = 0; i < axg_hw_onecell_data.num; i++) {
/* array might be sparse */
if (!axg_hw_onecell_data.hws[i])
continue;
ret = devm_clk_hw_register(dev, axg_hw_onecell_data.hws[i]);
if (ret) {
dev_err(dev, "Clock registration failed\n");
return ret;
}
}
return devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get,
&axg_hw_onecell_data);
}
static struct platform_driver axg_driver = {
.probe = axg_clkc_probe,
.driver = {
.name = "axg-clkc",
.of_match_table = clkc_match_table,
},
};
builtin_platform_driver(axg_driver);
|
605630.c | /* how long does it take to memset() per-byte on different sizes? */
/* cc -O3 -o memwalk memwalk.c -std=c99 -Wall -Wextra */
/* Usage: ./memwalk 10 32 */
/* First parameter is the number of kilobytes to hit. */
/* Second parameter is the base-2 logarithm of how many times to hit them. */
/* "./memwalk 1 10" will walk 1024 times over 1kB. */
/* "./memwalk 1024 20" will walk 1048576 times over 1MB. */
/* "./memwalk 2048 16" will walk 65536 times over 2MB. */
#define _POSIX_C_SOURCE 199309L
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(int argc, char **argv)
{
struct timespec tbegin, tfinish;
size_t thismuch;
long long int thismany;
if (argc != 3) {
printf("I want two int parms.\n");
return 1;
}
long me = strtol(argv[1], NULL, 10);
if (me <= 0) {
printf("Noooo %ld isn't right.\n", me);
return 1;
}
thismuch = (size_t)me;
thismuch <<= 10;
thismany = strtoll(argv[2], NULL, 10);
if (thismany <= 0) {
printf("Noooo %lld isn't bigger than 0.\n", thismany);
return 1;
}
size_t longlong_bits = 8 * sizeof(long long);
if ((size_t)thismany >= longlong_bits - 1) {
printf("%lld is too many, I can't count to 1 << %zd.\n",
thismany, longlong_bits - 1);
return 1;
}
thismany = 1LL << thismany;
char *thesebytes = malloc(thismuch);
if (thesebytes == NULL) {
printf("No, can't allocate that %zu bytes.\n", thismuch);
}
printf("allocated %zd bytes at %p.\n", thismuch, (void *)thesebytes);
printf("will walk %lld times.\n", thismany);
memset(thesebytes, 0, thismuch);
clock_gettime(CLOCK_REALTIME, &tbegin);
for (long long l = 0; l < thismany; l++) {
memset(thesebytes, l & 0xFF, thismuch);
}
clock_gettime(CLOCK_REALTIME, &tfinish);
long diff_sec = (long)tfinish.tv_sec - (long)tbegin.tv_sec;
long diff_nsec = (long)tfinish.tv_nsec - (long)tbegin.tv_nsec;
double nanos = 1.0e9 * (double)diff_sec + (double)diff_nsec;
double ops = (double)thismuch * (double)thismany;
printf("%f ns/byte\n", nanos / ops);
free(thesebytes);
return 0;
}
|
916192.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* linux/drivers/mmc/core/sd.c
*
* Copyright (C) 2003-2004 Russell King, All Rights Reserved.
* SD support Copyright (C) 2004 Ian Molton, All Rights Reserved.
* Copyright (C) 2005-2007 Pierre Ossman, All Rights Reserved.
*/
#include <linux/err.h>
#include <linux/sizes.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/pm_runtime.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include "core.h"
#include "card.h"
#include "host.h"
#include "bus.h"
#include "mmc_ops.h"
#include "sd.h"
#include "sd_ops.h"
static const unsigned int tran_exp[] = {
10000, 100000, 1000000, 10000000,
0, 0, 0, 0
};
static const unsigned char tran_mant[] = {
0, 10, 12, 13, 15, 20, 25, 30,
35, 40, 45, 50, 55, 60, 70, 80,
};
static const unsigned int taac_exp[] = {
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
};
static const unsigned int taac_mant[] = {
0, 10, 12, 13, 15, 20, 25, 30,
35, 40, 45, 50, 55, 60, 70, 80,
};
static const unsigned int sd_au_size[] = {
0, SZ_16K / 512, SZ_32K / 512, SZ_64K / 512,
SZ_128K / 512, SZ_256K / 512, SZ_512K / 512, SZ_1M / 512,
SZ_2M / 512, SZ_4M / 512, SZ_8M / 512, (SZ_8M + SZ_4M) / 512,
SZ_16M / 512, (SZ_16M + SZ_8M) / 512, SZ_32M / 512, SZ_64M / 512,
};
#define UNSTUFF_BITS(resp,start,size) \
({ \
const int __size = size; \
const u32 __mask = (__size < 32 ? 1 << __size : 0) - 1; \
const int __off = 3 - ((start) / 32); \
const int __shft = (start) & 31; \
u32 __res; \
\
__res = resp[__off] >> __shft; \
if (__size + __shft > 32) \
__res |= resp[__off-1] << ((32 - __shft) % 32); \
__res & __mask; \
})
#define SD_POWEROFF_NOTIFY_TIMEOUT_MS 2000
#define SD_WRITE_EXTR_SINGLE_TIMEOUT_MS 1000
struct sd_busy_data {
struct mmc_card *card;
u8 *reg_buf;
};
/*
* Given the decoded CSD structure, decode the raw CID to our CID structure.
*/
void mmc_decode_cid(struct mmc_card *card)
{
u32 *resp = card->raw_cid;
/*
* SD doesn't currently have a version field so we will
* have to assume we can parse this.
*/
card->cid.manfid = UNSTUFF_BITS(resp, 120, 8);
card->cid.oemid = UNSTUFF_BITS(resp, 104, 16);
card->cid.prod_name[0] = UNSTUFF_BITS(resp, 96, 8);
card->cid.prod_name[1] = UNSTUFF_BITS(resp, 88, 8);
card->cid.prod_name[2] = UNSTUFF_BITS(resp, 80, 8);
card->cid.prod_name[3] = UNSTUFF_BITS(resp, 72, 8);
card->cid.prod_name[4] = UNSTUFF_BITS(resp, 64, 8);
card->cid.hwrev = UNSTUFF_BITS(resp, 60, 4);
card->cid.fwrev = UNSTUFF_BITS(resp, 56, 4);
card->cid.serial = UNSTUFF_BITS(resp, 24, 32);
card->cid.year = UNSTUFF_BITS(resp, 12, 8);
card->cid.month = UNSTUFF_BITS(resp, 8, 4);
card->cid.year += 2000; /* SD cards year offset */
}
/*
* Given a 128-bit response, decode to our card CSD structure.
*/
static int mmc_decode_csd(struct mmc_card *card)
{
struct mmc_csd *csd = &card->csd;
unsigned int e, m, csd_struct;
u32 *resp = card->raw_csd;
csd_struct = UNSTUFF_BITS(resp, 126, 2);
switch (csd_struct) {
case 0:
m = UNSTUFF_BITS(resp, 115, 4);
e = UNSTUFF_BITS(resp, 112, 3);
csd->taac_ns = (taac_exp[e] * taac_mant[m] + 9) / 10;
csd->taac_clks = UNSTUFF_BITS(resp, 104, 8) * 100;
m = UNSTUFF_BITS(resp, 99, 4);
e = UNSTUFF_BITS(resp, 96, 3);
csd->max_dtr = tran_exp[e] * tran_mant[m];
csd->cmdclass = UNSTUFF_BITS(resp, 84, 12);
e = UNSTUFF_BITS(resp, 47, 3);
m = UNSTUFF_BITS(resp, 62, 12);
csd->capacity = (1 + m) << (e + 2);
csd->read_blkbits = UNSTUFF_BITS(resp, 80, 4);
csd->read_partial = UNSTUFF_BITS(resp, 79, 1);
csd->write_misalign = UNSTUFF_BITS(resp, 78, 1);
csd->read_misalign = UNSTUFF_BITS(resp, 77, 1);
csd->dsr_imp = UNSTUFF_BITS(resp, 76, 1);
csd->r2w_factor = UNSTUFF_BITS(resp, 26, 3);
csd->write_blkbits = UNSTUFF_BITS(resp, 22, 4);
csd->write_partial = UNSTUFF_BITS(resp, 21, 1);
if (UNSTUFF_BITS(resp, 46, 1)) {
csd->erase_size = 1;
} else if (csd->write_blkbits >= 9) {
csd->erase_size = UNSTUFF_BITS(resp, 39, 7) + 1;
csd->erase_size <<= csd->write_blkbits - 9;
}
if (UNSTUFF_BITS(resp, 13, 1))
mmc_card_set_readonly(card);
break;
case 1:
/*
* This is a block-addressed SDHC or SDXC card. Most
* interesting fields are unused and have fixed
* values. To avoid getting tripped by buggy cards,
* we assume those fixed values ourselves.
*/
mmc_card_set_blockaddr(card);
csd->taac_ns = 0; /* Unused */
csd->taac_clks = 0; /* Unused */
m = UNSTUFF_BITS(resp, 99, 4);
e = UNSTUFF_BITS(resp, 96, 3);
csd->max_dtr = tran_exp[e] * tran_mant[m];
csd->cmdclass = UNSTUFF_BITS(resp, 84, 12);
csd->c_size = UNSTUFF_BITS(resp, 48, 22);
/* SDXC cards have a minimum C_SIZE of 0x00FFFF */
if (csd->c_size >= 0xFFFF)
mmc_card_set_ext_capacity(card);
m = UNSTUFF_BITS(resp, 48, 22);
csd->capacity = (1 + m) << 10;
csd->read_blkbits = 9;
csd->read_partial = 0;
csd->write_misalign = 0;
csd->read_misalign = 0;
csd->r2w_factor = 4; /* Unused */
csd->write_blkbits = 9;
csd->write_partial = 0;
csd->erase_size = 1;
if (UNSTUFF_BITS(resp, 13, 1))
mmc_card_set_readonly(card);
break;
default:
pr_err("%s: unrecognised CSD structure version %d\n",
mmc_hostname(card->host), csd_struct);
return -EINVAL;
}
card->erase_size = csd->erase_size;
return 0;
}
/*
* Given a 64-bit response, decode to our card SCR structure.
*/
static int mmc_decode_scr(struct mmc_card *card)
{
struct sd_scr *scr = &card->scr;
unsigned int scr_struct;
u32 resp[4];
resp[3] = card->raw_scr[1];
resp[2] = card->raw_scr[0];
scr_struct = UNSTUFF_BITS(resp, 60, 4);
if (scr_struct != 0) {
pr_err("%s: unrecognised SCR structure version %d\n",
mmc_hostname(card->host), scr_struct);
return -EINVAL;
}
scr->sda_vsn = UNSTUFF_BITS(resp, 56, 4);
scr->bus_widths = UNSTUFF_BITS(resp, 48, 4);
if (scr->sda_vsn == SCR_SPEC_VER_2)
/* Check if Physical Layer Spec v3.0 is supported */
scr->sda_spec3 = UNSTUFF_BITS(resp, 47, 1);
if (scr->sda_spec3) {
scr->sda_spec4 = UNSTUFF_BITS(resp, 42, 1);
scr->sda_specx = UNSTUFF_BITS(resp, 38, 4);
}
if (UNSTUFF_BITS(resp, 55, 1))
card->erased_byte = 0xFF;
else
card->erased_byte = 0x0;
if (scr->sda_spec4)
scr->cmds = UNSTUFF_BITS(resp, 32, 4);
else if (scr->sda_spec3)
scr->cmds = UNSTUFF_BITS(resp, 32, 2);
/* SD Spec says: any SD Card shall set at least bits 0 and 2 */
if (!(scr->bus_widths & SD_SCR_BUS_WIDTH_1) ||
!(scr->bus_widths & SD_SCR_BUS_WIDTH_4)) {
pr_err("%s: invalid bus width\n", mmc_hostname(card->host));
return -EINVAL;
}
return 0;
}
/*
* Fetch and process SD Status register.
*/
static int mmc_read_ssr(struct mmc_card *card)
{
unsigned int au, es, et, eo;
__be32 *raw_ssr;
u32 resp[4] = {};
u8 discard_support;
int i;
if (!(card->csd.cmdclass & CCC_APP_SPEC)) {
pr_warn("%s: card lacks mandatory SD Status function\n",
mmc_hostname(card->host));
return 0;
}
raw_ssr = kmalloc(sizeof(card->raw_ssr), GFP_KERNEL);
if (!raw_ssr)
return -ENOMEM;
if (mmc_app_sd_status(card, raw_ssr)) {
pr_warn("%s: problem reading SD Status register\n",
mmc_hostname(card->host));
kfree(raw_ssr);
return 0;
}
for (i = 0; i < 16; i++)
card->raw_ssr[i] = be32_to_cpu(raw_ssr[i]);
kfree(raw_ssr);
/*
* UNSTUFF_BITS only works with four u32s so we have to offset the
* bitfield positions accordingly.
*/
au = UNSTUFF_BITS(card->raw_ssr, 428 - 384, 4);
if (au) {
if (au <= 9 || card->scr.sda_spec3) {
card->ssr.au = sd_au_size[au];
es = UNSTUFF_BITS(card->raw_ssr, 408 - 384, 16);
et = UNSTUFF_BITS(card->raw_ssr, 402 - 384, 6);
if (es && et) {
eo = UNSTUFF_BITS(card->raw_ssr, 400 - 384, 2);
card->ssr.erase_timeout = (et * 1000) / es;
card->ssr.erase_offset = eo * 1000;
}
} else {
pr_warn("%s: SD Status: Invalid Allocation Unit size\n",
mmc_hostname(card->host));
}
}
/*
* starting SD5.1 discard is supported if DISCARD_SUPPORT (b313) is set
*/
resp[3] = card->raw_ssr[6];
discard_support = UNSTUFF_BITS(resp, 313 - 288, 1);
card->erase_arg = (card->scr.sda_specx && discard_support) ?
SD_DISCARD_ARG : SD_ERASE_ARG;
return 0;
}
/*
* Fetches and decodes switch information
*/
static int mmc_read_switch(struct mmc_card *card)
{
int err;
u8 *status;
if (card->scr.sda_vsn < SCR_SPEC_VER_1)
return 0;
if (!(card->csd.cmdclass & CCC_SWITCH)) {
pr_warn("%s: card lacks mandatory switch function, performance might suffer\n",
mmc_hostname(card->host));
return 0;
}
status = kmalloc(64, GFP_KERNEL);
if (!status)
return -ENOMEM;
/*
* Find out the card's support bits with a mode 0 operation.
* The argument does not matter, as the support bits do not
* change with the arguments.
*/
err = mmc_sd_switch(card, 0, 0, 0, status);
if (err) {
/*
* If the host or the card can't do the switch,
* fail more gracefully.
*/
if (err != -EINVAL && err != -ENOSYS && err != -EFAULT)
goto out;
pr_warn("%s: problem reading Bus Speed modes\n",
mmc_hostname(card->host));
err = 0;
goto out;
}
if (status[13] & SD_MODE_HIGH_SPEED)
card->sw_caps.hs_max_dtr = HIGH_SPEED_MAX_DTR;
if (card->scr.sda_spec3) {
card->sw_caps.sd3_bus_mode = status[13];
/* Driver Strengths supported by the card */
card->sw_caps.sd3_drv_type = status[9];
card->sw_caps.sd3_curr_limit = status[7] | status[6] << 8;
}
out:
kfree(status);
return err;
}
/*
* Test if the card supports high-speed mode and, if so, switch to it.
*/
int mmc_sd_switch_hs(struct mmc_card *card)
{
int err;
u8 *status;
if (card->scr.sda_vsn < SCR_SPEC_VER_1)
return 0;
if (!(card->csd.cmdclass & CCC_SWITCH))
return 0;
if (!(card->host->caps & MMC_CAP_SD_HIGHSPEED))
return 0;
if (card->sw_caps.hs_max_dtr == 0)
return 0;
status = kmalloc(64, GFP_KERNEL);
if (!status)
return -ENOMEM;
err = mmc_sd_switch(card, 1, 0, HIGH_SPEED_BUS_SPEED, status);
if (err)
goto out;
if ((status[16] & 0xF) != HIGH_SPEED_BUS_SPEED) {
pr_warn("%s: Problem switching card into high-speed mode!\n",
mmc_hostname(card->host));
err = 0;
} else {
err = 1;
}
out:
kfree(status);
return err;
}
static int sd_select_driver_type(struct mmc_card *card, u8 *status)
{
int card_drv_type, drive_strength, drv_type;
int err;
card->drive_strength = 0;
card_drv_type = card->sw_caps.sd3_drv_type | SD_DRIVER_TYPE_B;
drive_strength = mmc_select_drive_strength(card,
card->sw_caps.uhs_max_dtr,
card_drv_type, &drv_type);
if (drive_strength) {
err = mmc_sd_switch(card, 1, 2, drive_strength, status);
if (err)
return err;
if ((status[15] & 0xF) != drive_strength) {
pr_warn("%s: Problem setting drive strength!\n",
mmc_hostname(card->host));
return 0;
}
card->drive_strength = drive_strength;
}
if (drv_type)
mmc_set_driver_type(card->host, drv_type);
return 0;
}
static void sd_update_bus_speed_mode(struct mmc_card *card)
{
/*
* If the host doesn't support any of the UHS-I modes, fallback on
* default speed.
*/
if (!mmc_host_uhs(card->host)) {
card->sd_bus_speed = 0;
return;
}
if ((card->host->caps & MMC_CAP_UHS_SDR104) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR104)) {
card->sd_bus_speed = UHS_SDR104_BUS_SPEED;
} else if ((card->host->caps & MMC_CAP_UHS_DDR50) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_DDR50)) {
card->sd_bus_speed = UHS_DDR50_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50)) && (card->sw_caps.sd3_bus_mode &
SD_MODE_UHS_SDR50)) {
card->sd_bus_speed = UHS_SDR50_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR25)) &&
(card->sw_caps.sd3_bus_mode & SD_MODE_UHS_SDR25)) {
card->sd_bus_speed = UHS_SDR25_BUS_SPEED;
} else if ((card->host->caps & (MMC_CAP_UHS_SDR104 |
MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR25 |
MMC_CAP_UHS_SDR12)) && (card->sw_caps.sd3_bus_mode &
SD_MODE_UHS_SDR12)) {
card->sd_bus_speed = UHS_SDR12_BUS_SPEED;
}
}
static int sd_set_bus_speed_mode(struct mmc_card *card, u8 *status)
{
int err;
unsigned int timing = 0;
switch (card->sd_bus_speed) {
case UHS_SDR104_BUS_SPEED:
timing = MMC_TIMING_UHS_SDR104;
card->sw_caps.uhs_max_dtr = UHS_SDR104_MAX_DTR;
break;
case UHS_DDR50_BUS_SPEED:
timing = MMC_TIMING_UHS_DDR50;
card->sw_caps.uhs_max_dtr = UHS_DDR50_MAX_DTR;
break;
case UHS_SDR50_BUS_SPEED:
timing = MMC_TIMING_UHS_SDR50;
card->sw_caps.uhs_max_dtr = UHS_SDR50_MAX_DTR;
break;
case UHS_SDR25_BUS_SPEED:
timing = MMC_TIMING_UHS_SDR25;
card->sw_caps.uhs_max_dtr = UHS_SDR25_MAX_DTR;
break;
case UHS_SDR12_BUS_SPEED:
timing = MMC_TIMING_UHS_SDR12;
card->sw_caps.uhs_max_dtr = UHS_SDR12_MAX_DTR;
break;
default:
return 0;
}
err = mmc_sd_switch(card, 1, 0, card->sd_bus_speed, status);
if (err)
return err;
if ((status[16] & 0xF) != card->sd_bus_speed)
pr_warn("%s: Problem setting bus speed mode!\n",
mmc_hostname(card->host));
else {
mmc_set_timing(card->host, timing);
mmc_set_clock(card->host, card->sw_caps.uhs_max_dtr);
}
return 0;
}
/* Get host's max current setting at its current voltage */
static u32 sd_get_host_max_current(struct mmc_host *host)
{
u32 voltage, max_current;
voltage = 1 << host->ios.vdd;
switch (voltage) {
case MMC_VDD_165_195:
max_current = host->max_current_180;
break;
case MMC_VDD_29_30:
case MMC_VDD_30_31:
max_current = host->max_current_300;
break;
case MMC_VDD_32_33:
case MMC_VDD_33_34:
max_current = host->max_current_330;
break;
default:
max_current = 0;
}
return max_current;
}
static int sd_set_current_limit(struct mmc_card *card, u8 *status)
{
int current_limit = SD_SET_CURRENT_NO_CHANGE;
int err;
u32 max_current;
/*
* Current limit switch is only defined for SDR50, SDR104, and DDR50
* bus speed modes. For other bus speed modes, we do not change the
* current limit.
*/
if ((card->sd_bus_speed != UHS_SDR50_BUS_SPEED) &&
(card->sd_bus_speed != UHS_SDR104_BUS_SPEED) &&
(card->sd_bus_speed != UHS_DDR50_BUS_SPEED))
return 0;
/*
* Host has different current capabilities when operating at
* different voltages, so find out its max current first.
*/
max_current = sd_get_host_max_current(card->host);
/*
* We only check host's capability here, if we set a limit that is
* higher than the card's maximum current, the card will be using its
* maximum current, e.g. if the card's maximum current is 300ma, and
* when we set current limit to 200ma, the card will draw 200ma, and
* when we set current limit to 400/600/800ma, the card will draw its
* maximum 300ma from the host.
*
* The above is incorrect: if we try to set a current limit that is
* not supported by the card, the card can rightfully error out the
* attempt, and remain at the default current limit. This results
* in a 300mA card being limited to 200mA even though the host
* supports 800mA. Failures seen with SanDisk 8GB UHS cards with
* an iMX6 host. --rmk
*/
if (max_current >= 800 &&
card->sw_caps.sd3_curr_limit & SD_MAX_CURRENT_800)
current_limit = SD_SET_CURRENT_LIMIT_800;
else if (max_current >= 600 &&
card->sw_caps.sd3_curr_limit & SD_MAX_CURRENT_600)
current_limit = SD_SET_CURRENT_LIMIT_600;
else if (max_current >= 400 &&
card->sw_caps.sd3_curr_limit & SD_MAX_CURRENT_400)
current_limit = SD_SET_CURRENT_LIMIT_400;
else if (max_current >= 200 &&
card->sw_caps.sd3_curr_limit & SD_MAX_CURRENT_200)
current_limit = SD_SET_CURRENT_LIMIT_200;
if (current_limit != SD_SET_CURRENT_NO_CHANGE) {
err = mmc_sd_switch(card, 1, 3, current_limit, status);
if (err)
return err;
if (((status[15] >> 4) & 0x0F) != current_limit)
pr_warn("%s: Problem setting current limit!\n",
mmc_hostname(card->host));
}
return 0;
}
/*
* UHS-I specific initialization procedure
*/
static int mmc_sd_init_uhs_card(struct mmc_card *card)
{
int err;
u8 *status;
if (!(card->csd.cmdclass & CCC_SWITCH))
return 0;
status = kmalloc(64, GFP_KERNEL);
if (!status)
return -ENOMEM;
/* Set 4-bit bus width */
err = mmc_app_set_bus_width(card, MMC_BUS_WIDTH_4);
if (err)
goto out;
mmc_set_bus_width(card->host, MMC_BUS_WIDTH_4);
/*
* Select the bus speed mode depending on host
* and card capability.
*/
sd_update_bus_speed_mode(card);
/* Set the driver strength for the card */
err = sd_select_driver_type(card, status);
if (err)
goto out;
/* Set current limit for the card */
err = sd_set_current_limit(card, status);
if (err)
goto out;
/* Set bus speed mode of the card */
err = sd_set_bus_speed_mode(card, status);
if (err)
goto out;
/*
* SPI mode doesn't define CMD19 and tuning is only valid for SDR50 and
* SDR104 mode SD-cards. Note that tuning is mandatory for SDR104.
*/
if (!mmc_host_is_spi(card->host) &&
(card->host->ios.timing == MMC_TIMING_UHS_SDR50 ||
card->host->ios.timing == MMC_TIMING_UHS_DDR50 ||
card->host->ios.timing == MMC_TIMING_UHS_SDR104)) {
err = mmc_execute_tuning(card);
/*
* As SD Specifications Part1 Physical Layer Specification
* Version 3.01 says, CMD19 tuning is available for unlocked
* cards in transfer state of 1.8V signaling mode. The small
* difference between v3.00 and 3.01 spec means that CMD19
* tuning is also available for DDR50 mode.
*/
if (err && card->host->ios.timing == MMC_TIMING_UHS_DDR50) {
pr_warn("%s: ddr50 tuning failed\n",
mmc_hostname(card->host));
err = 0;
}
}
out:
kfree(status);
return err;
}
MMC_DEV_ATTR(cid, "%08x%08x%08x%08x\n", card->raw_cid[0], card->raw_cid[1],
card->raw_cid[2], card->raw_cid[3]);
MMC_DEV_ATTR(csd, "%08x%08x%08x%08x\n", card->raw_csd[0], card->raw_csd[1],
card->raw_csd[2], card->raw_csd[3]);
MMC_DEV_ATTR(scr, "%08x%08x\n", card->raw_scr[0], card->raw_scr[1]);
MMC_DEV_ATTR(ssr,
"%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n",
card->raw_ssr[0], card->raw_ssr[1], card->raw_ssr[2],
card->raw_ssr[3], card->raw_ssr[4], card->raw_ssr[5],
card->raw_ssr[6], card->raw_ssr[7], card->raw_ssr[8],
card->raw_ssr[9], card->raw_ssr[10], card->raw_ssr[11],
card->raw_ssr[12], card->raw_ssr[13], card->raw_ssr[14],
card->raw_ssr[15]);
MMC_DEV_ATTR(date, "%02d/%04d\n", card->cid.month, card->cid.year);
MMC_DEV_ATTR(erase_size, "%u\n", card->erase_size << 9);
MMC_DEV_ATTR(preferred_erase_size, "%u\n", card->pref_erase << 9);
MMC_DEV_ATTR(fwrev, "0x%x\n", card->cid.fwrev);
MMC_DEV_ATTR(hwrev, "0x%x\n", card->cid.hwrev);
MMC_DEV_ATTR(manfid, "0x%06x\n", card->cid.manfid);
MMC_DEV_ATTR(name, "%s\n", card->cid.prod_name);
MMC_DEV_ATTR(oemid, "0x%04x\n", card->cid.oemid);
MMC_DEV_ATTR(serial, "0x%08x\n", card->cid.serial);
MMC_DEV_ATTR(ocr, "0x%08x\n", card->ocr);
MMC_DEV_ATTR(rca, "0x%04x\n", card->rca);
static ssize_t mmc_dsr_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct mmc_card *card = mmc_dev_to_card(dev);
struct mmc_host *host = card->host;
if (card->csd.dsr_imp && host->dsr_req)
return sprintf(buf, "0x%x\n", host->dsr);
else
/* return default DSR value */
return sprintf(buf, "0x%x\n", 0x404);
}
static DEVICE_ATTR(dsr, S_IRUGO, mmc_dsr_show, NULL);
MMC_DEV_ATTR(vendor, "0x%04x\n", card->cis.vendor);
MMC_DEV_ATTR(device, "0x%04x\n", card->cis.device);
MMC_DEV_ATTR(revision, "%u.%u\n", card->major_rev, card->minor_rev);
#define sdio_info_attr(num) \
static ssize_t info##num##_show(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
struct mmc_card *card = mmc_dev_to_card(dev); \
\
if (num > card->num_info) \
return -ENODATA; \
if (!card->info[num-1][0]) \
return 0; \
return sprintf(buf, "%s\n", card->info[num-1]); \
} \
static DEVICE_ATTR_RO(info##num)
sdio_info_attr(1);
sdio_info_attr(2);
sdio_info_attr(3);
sdio_info_attr(4);
static struct attribute *sd_std_attrs[] = {
&dev_attr_vendor.attr,
&dev_attr_device.attr,
&dev_attr_revision.attr,
&dev_attr_info1.attr,
&dev_attr_info2.attr,
&dev_attr_info3.attr,
&dev_attr_info4.attr,
&dev_attr_cid.attr,
&dev_attr_csd.attr,
&dev_attr_scr.attr,
&dev_attr_ssr.attr,
&dev_attr_date.attr,
&dev_attr_erase_size.attr,
&dev_attr_preferred_erase_size.attr,
&dev_attr_fwrev.attr,
&dev_attr_hwrev.attr,
&dev_attr_manfid.attr,
&dev_attr_name.attr,
&dev_attr_oemid.attr,
&dev_attr_serial.attr,
&dev_attr_ocr.attr,
&dev_attr_rca.attr,
&dev_attr_dsr.attr,
NULL,
};
static umode_t sd_std_is_visible(struct kobject *kobj, struct attribute *attr,
int index)
{
struct device *dev = kobj_to_dev(kobj);
struct mmc_card *card = mmc_dev_to_card(dev);
/* CIS vendor and device ids, revision and info string are available only for Combo cards */
if ((attr == &dev_attr_vendor.attr ||
attr == &dev_attr_device.attr ||
attr == &dev_attr_revision.attr ||
attr == &dev_attr_info1.attr ||
attr == &dev_attr_info2.attr ||
attr == &dev_attr_info3.attr ||
attr == &dev_attr_info4.attr
) && card->type != MMC_TYPE_SD_COMBO)
return 0;
return attr->mode;
}
static const struct attribute_group sd_std_group = {
.attrs = sd_std_attrs,
.is_visible = sd_std_is_visible,
};
__ATTRIBUTE_GROUPS(sd_std);
struct device_type sd_type = {
.groups = sd_std_groups,
};
/*
* Fetch CID from card.
*/
int mmc_sd_get_cid(struct mmc_host *host, u32 ocr, u32 *cid, u32 *rocr)
{
int err;
u32 max_current;
int retries = 10;
u32 pocr = ocr;
try_again:
if (!retries) {
ocr &= ~SD_OCR_S18R;
pr_warn("%s: Skipping voltage switch\n", mmc_hostname(host));
}
/*
* Since we're changing the OCR value, we seem to
* need to tell some cards to go back to the idle
* state. We wait 1ms to give cards time to
* respond.
*/
mmc_go_idle(host);
/*
* If SD_SEND_IF_COND indicates an SD 2.0
* compliant card and we should set bit 30
* of the ocr to indicate that we can handle
* block-addressed SDHC cards.
*/
err = mmc_send_if_cond(host, ocr);
if (!err)
ocr |= SD_OCR_CCS;
/*
* If the host supports one of UHS-I modes, request the card
* to switch to 1.8V signaling level. If the card has failed
* repeatedly to switch however, skip this.
*/
if (retries && mmc_host_uhs(host))
ocr |= SD_OCR_S18R;
/*
* If the host can supply more than 150mA at current voltage,
* XPC should be set to 1.
*/
max_current = sd_get_host_max_current(host);
if (max_current > 150)
ocr |= SD_OCR_XPC;
err = mmc_send_app_op_cond(host, ocr, rocr);
if (err)
return err;
/*
* In case the S18A bit is set in the response, let's start the signal
* voltage switch procedure. SPI mode doesn't support CMD11.
* Note that, according to the spec, the S18A bit is not valid unless
* the CCS bit is set as well. We deliberately deviate from the spec in
* regards to this, which allows UHS-I to be supported for SDSC cards.
*/
if (!mmc_host_is_spi(host) && rocr && (*rocr & 0x01000000)) {
err = mmc_set_uhs_voltage(host, pocr);
if (err == -EAGAIN) {
retries--;
goto try_again;
} else if (err) {
retries = 0;
goto try_again;
}
}
err = mmc_send_cid(host, cid);
return err;
}
int mmc_sd_get_csd(struct mmc_card *card)
{
int err;
/*
* Fetch CSD from card.
*/
err = mmc_send_csd(card, card->raw_csd);
if (err)
return err;
err = mmc_decode_csd(card);
if (err)
return err;
return 0;
}
static int mmc_sd_get_ro(struct mmc_host *host)
{
int ro;
/*
* Some systems don't feature a write-protect pin and don't need one.
* E.g. because they only have micro-SD card slot. For those systems
* assume that the SD card is always read-write.
*/
if (host->caps2 & MMC_CAP2_NO_WRITE_PROTECT)
return 0;
if (!host->ops->get_ro)
return -1;
ro = host->ops->get_ro(host);
return ro;
}
int mmc_sd_setup_card(struct mmc_host *host, struct mmc_card *card,
bool reinit)
{
int err;
if (!reinit) {
/*
* Fetch SCR from card.
*/
err = mmc_app_send_scr(card);
if (err)
return err;
err = mmc_decode_scr(card);
if (err)
return err;
/*
* Fetch and process SD Status register.
*/
err = mmc_read_ssr(card);
if (err)
return err;
/* Erase init depends on CSD and SSR */
mmc_init_erase(card);
/*
* Fetch switch information from card.
*/
err = mmc_read_switch(card);
if (err)
return err;
}
/*
* For SPI, enable CRC as appropriate.
* This CRC enable is located AFTER the reading of the
* card registers because some SDHC cards are not able
* to provide valid CRCs for non-512-byte blocks.
*/
if (mmc_host_is_spi(host)) {
err = mmc_spi_set_crc(host, use_spi_crc);
if (err)
return err;
}
/*
* Check if read-only switch is active.
*/
if (!reinit) {
int ro = mmc_sd_get_ro(host);
if (ro < 0) {
pr_warn("%s: host does not support reading read-only switch, assuming write-enable\n",
mmc_hostname(host));
} else if (ro > 0) {
mmc_card_set_readonly(card);
}
}
return 0;
}
unsigned mmc_sd_get_max_clock(struct mmc_card *card)
{
unsigned max_dtr = (unsigned int)-1;
if (mmc_card_hs(card)) {
if (max_dtr > card->sw_caps.hs_max_dtr)
max_dtr = card->sw_caps.hs_max_dtr;
} else if (max_dtr > card->csd.max_dtr) {
max_dtr = card->csd.max_dtr;
}
return max_dtr;
}
static bool mmc_sd_card_using_v18(struct mmc_card *card)
{
/*
* According to the SD spec., the Bus Speed Mode (function group 1) bits
* 2 to 4 are zero if the card is initialized at 3.3V signal level. Thus
* they can be used to determine if the card has already switched to
* 1.8V signaling.
*/
return card->sw_caps.sd3_bus_mode &
(SD_MODE_UHS_SDR50 | SD_MODE_UHS_SDR104 | SD_MODE_UHS_DDR50);
}
static int sd_write_ext_reg(struct mmc_card *card, u8 fno, u8 page, u16 offset,
u8 reg_data)
{
struct mmc_host *host = card->host;
struct mmc_request mrq = {};
struct mmc_command cmd = {};
struct mmc_data data = {};
struct scatterlist sg;
u8 *reg_buf;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
mrq.cmd = &cmd;
mrq.data = &data;
/*
* Arguments of CMD49:
* [31:31] MIO (0 = memory).
* [30:27] FNO (function number).
* [26:26] MW - mask write mode (0 = disable).
* [25:18] page number.
* [17:9] offset address.
* [8:0] length (0 = 1 byte).
*/
cmd.arg = fno << 27 | page << 18 | offset << 9;
/* The first byte in the buffer is the data to be written. */
reg_buf[0] = reg_data;
data.flags = MMC_DATA_WRITE;
data.blksz = 512;
data.blocks = 1;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, reg_buf, 512);
cmd.opcode = SD_WRITE_EXTR_SINGLE;
cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
mmc_set_data_timeout(&data, card);
mmc_wait_for_req(host, &mrq);
kfree(reg_buf);
/*
* Note that, the SD card is allowed to signal busy on DAT0 up to 1s
* after the CMD49. Although, let's leave this to be managed by the
* caller.
*/
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
return 0;
}
static int sd_read_ext_reg(struct mmc_card *card, u8 fno, u8 page,
u16 offset, u16 len, u8 *reg_buf)
{
u32 cmd_args;
/*
* Command arguments of CMD48:
* [31:31] MIO (0 = memory).
* [30:27] FNO (function number).
* [26:26] reserved (0).
* [25:18] page number.
* [17:9] offset address.
* [8:0] length (0 = 1 byte, 1ff = 512 bytes).
*/
cmd_args = fno << 27 | page << 18 | offset << 9 | (len -1);
return mmc_send_adtc_data(card, card->host, SD_READ_EXTR_SINGLE,
cmd_args, reg_buf, 512);
}
static int sd_parse_ext_reg_power(struct mmc_card *card, u8 fno, u8 page,
u16 offset)
{
int err;
u8 *reg_buf;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
/* Read the extension register for power management function. */
err = sd_read_ext_reg(card, fno, page, offset, 512, reg_buf);
if (err) {
pr_warn("%s: error %d reading PM func of ext reg\n",
mmc_hostname(card->host), err);
goto out;
}
/* PM revision consists of 4 bits. */
card->ext_power.rev = reg_buf[0] & 0xf;
/* Power Off Notification support at bit 4. */
if (reg_buf[1] & BIT(4))
card->ext_power.feature_support |= SD_EXT_POWER_OFF_NOTIFY;
/* Power Sustenance support at bit 5. */
if (reg_buf[1] & BIT(5))
card->ext_power.feature_support |= SD_EXT_POWER_SUSTENANCE;
/* Power Down Mode support at bit 6. */
if (reg_buf[1] & BIT(6))
card->ext_power.feature_support |= SD_EXT_POWER_DOWN_MODE;
card->ext_power.fno = fno;
card->ext_power.page = page;
card->ext_power.offset = offset;
out:
kfree(reg_buf);
return err;
}
static int sd_parse_ext_reg_perf(struct mmc_card *card, u8 fno, u8 page,
u16 offset)
{
int err;
u8 *reg_buf;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
err = sd_read_ext_reg(card, fno, page, offset, 512, reg_buf);
if (err) {
pr_warn("%s: error %d reading PERF func of ext reg\n",
mmc_hostname(card->host), err);
goto out;
}
/* PERF revision. */
card->ext_perf.rev = reg_buf[0];
/* FX_EVENT support at bit 0. */
if (reg_buf[1] & BIT(0))
card->ext_perf.feature_support |= SD_EXT_PERF_FX_EVENT;
/* Card initiated self-maintenance support at bit 0. */
if (reg_buf[2] & BIT(0))
card->ext_perf.feature_support |= SD_EXT_PERF_CARD_MAINT;
/* Host initiated self-maintenance support at bit 1. */
if (reg_buf[2] & BIT(1))
card->ext_perf.feature_support |= SD_EXT_PERF_HOST_MAINT;
/* Cache support at bit 0. */
if (reg_buf[4] & BIT(0))
card->ext_perf.feature_support |= SD_EXT_PERF_CACHE;
/* Command queue support indicated via queue depth bits (0 to 4). */
if (reg_buf[6] & 0x1f)
card->ext_perf.feature_support |= SD_EXT_PERF_CMD_QUEUE;
card->ext_perf.fno = fno;
card->ext_perf.page = page;
card->ext_perf.offset = offset;
out:
kfree(reg_buf);
return err;
}
static int sd_parse_ext_reg(struct mmc_card *card, u8 *gen_info_buf,
u16 *next_ext_addr)
{
u8 num_regs, fno, page;
u16 sfc, offset, ext = *next_ext_addr;
u32 reg_addr;
/*
* Parse only one register set per extension, as that is sufficient to
* support the standard functions. This means another 48 bytes in the
* buffer must be available.
*/
if (ext + 48 > 512)
return -EFAULT;
/* Standard Function Code */
memcpy(&sfc, &gen_info_buf[ext], 2);
/* Address to the next extension. */
memcpy(next_ext_addr, &gen_info_buf[ext + 40], 2);
/* Number of registers for this extension. */
num_regs = gen_info_buf[ext + 42];
/* We support only one register per extension. */
if (num_regs != 1)
return 0;
/* Extension register address. */
memcpy(®_addr, &gen_info_buf[ext + 44], 4);
/* 9 bits (0 to 8) contains the offset address. */
offset = reg_addr & 0x1ff;
/* 8 bits (9 to 16) contains the page number. */
page = reg_addr >> 9 & 0xff ;
/* 4 bits (18 to 21) contains the function number. */
fno = reg_addr >> 18 & 0xf;
/* Standard Function Code for power management. */
if (sfc == 0x1)
return sd_parse_ext_reg_power(card, fno, page, offset);
/* Standard Function Code for performance enhancement. */
if (sfc == 0x2)
return sd_parse_ext_reg_perf(card, fno, page, offset);
return 0;
}
static int sd_read_ext_regs(struct mmc_card *card)
{
int err, i;
u8 num_ext, *gen_info_buf;
u16 rev, len, next_ext_addr;
if (mmc_host_is_spi(card->host))
return 0;
if (!(card->scr.cmds & SD_SCR_CMD48_SUPPORT))
return 0;
gen_info_buf = kzalloc(512, GFP_KERNEL);
if (!gen_info_buf)
return -ENOMEM;
/*
* Read 512 bytes of general info, which is found at function number 0,
* at page 0 and with no offset.
*/
err = sd_read_ext_reg(card, 0, 0, 0, 512, gen_info_buf);
if (err) {
pr_warn("%s: error %d reading general info of SD ext reg\n",
mmc_hostname(card->host), err);
goto out;
}
/* General info structure revision. */
memcpy(&rev, &gen_info_buf[0], 2);
/* Length of general info in bytes. */
memcpy(&len, &gen_info_buf[2], 2);
/* Number of extensions to be find. */
num_ext = gen_info_buf[4];
/* We support revision 0, but limit it to 512 bytes for simplicity. */
if (rev != 0 || len > 512) {
pr_warn("%s: non-supported SD ext reg layout\n",
mmc_hostname(card->host));
goto out;
}
/*
* Parse the extension registers. The first extension should start
* immediately after the general info header (16 bytes).
*/
next_ext_addr = 16;
for (i = 0; i < num_ext; i++) {
err = sd_parse_ext_reg(card, gen_info_buf, &next_ext_addr);
if (err) {
pr_warn("%s: error %d parsing SD ext reg\n",
mmc_hostname(card->host), err);
goto out;
}
}
out:
kfree(gen_info_buf);
return err;
}
static bool sd_cache_enabled(struct mmc_host *host)
{
return host->card->ext_perf.feature_enabled & SD_EXT_PERF_CACHE;
}
static int sd_flush_cache(struct mmc_host *host)
{
struct mmc_card *card = host->card;
u8 *reg_buf, fno, page;
u16 offset;
int err;
if (!sd_cache_enabled(host))
return 0;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
/*
* Set Flush Cache at bit 0 in the performance enhancement register at
* 261 bytes offset.
*/
fno = card->ext_perf.fno;
page = card->ext_perf.page;
offset = card->ext_perf.offset + 261;
err = sd_write_ext_reg(card, fno, page, offset, BIT(0));
if (err) {
pr_warn("%s: error %d writing Cache Flush bit\n",
mmc_hostname(host), err);
goto out;
}
err = mmc_poll_for_busy(card, SD_WRITE_EXTR_SINGLE_TIMEOUT_MS, false,
MMC_BUSY_EXTR_SINGLE);
if (err)
goto out;
/*
* Read the Flush Cache bit. The card shall reset it, to confirm that
* it's has completed the flushing of the cache.
*/
err = sd_read_ext_reg(card, fno, page, offset, 1, reg_buf);
if (err) {
pr_warn("%s: error %d reading Cache Flush bit\n",
mmc_hostname(host), err);
goto out;
}
if (reg_buf[0] & BIT(0))
err = -ETIMEDOUT;
out:
kfree(reg_buf);
return err;
}
static int sd_enable_cache(struct mmc_card *card)
{
u8 *reg_buf;
int err;
card->ext_perf.feature_enabled &= ~SD_EXT_PERF_CACHE;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
/*
* Set Cache Enable at bit 0 in the performance enhancement register at
* 260 bytes offset.
*/
err = sd_write_ext_reg(card, card->ext_perf.fno, card->ext_perf.page,
card->ext_perf.offset + 260, BIT(0));
if (err) {
pr_warn("%s: error %d writing Cache Enable bit\n",
mmc_hostname(card->host), err);
goto out;
}
err = mmc_poll_for_busy(card, SD_WRITE_EXTR_SINGLE_TIMEOUT_MS, false,
MMC_BUSY_EXTR_SINGLE);
if (!err)
card->ext_perf.feature_enabled |= SD_EXT_PERF_CACHE;
out:
kfree(reg_buf);
return err;
}
/*
* Handle the detection and initialisation of a card.
*
* In the case of a resume, "oldcard" will contain the card
* we're trying to reinitialise.
*/
static int mmc_sd_init_card(struct mmc_host *host, u32 ocr,
struct mmc_card *oldcard)
{
struct mmc_card *card;
int err;
u32 cid[4];
u32 rocr = 0;
bool v18_fixup_failed = false;
WARN_ON(!host->claimed);
retry:
err = mmc_sd_get_cid(host, ocr, cid, &rocr);
if (err)
return err;
if (oldcard) {
if (memcmp(cid, oldcard->raw_cid, sizeof(cid)) != 0) {
pr_debug("%s: Perhaps the card was replaced\n",
mmc_hostname(host));
return -ENOENT;
}
card = oldcard;
} else {
/*
* Allocate card structure.
*/
card = mmc_alloc_card(host, &sd_type);
if (IS_ERR(card))
return PTR_ERR(card);
card->ocr = ocr;
card->type = MMC_TYPE_SD;
memcpy(card->raw_cid, cid, sizeof(card->raw_cid));
}
/*
* Call the optional HC's init_card function to handle quirks.
*/
if (host->ops->init_card)
host->ops->init_card(host, card);
/*
* For native busses: get card RCA and quit open drain mode.
*/
if (!mmc_host_is_spi(host)) {
err = mmc_send_relative_addr(host, &card->rca);
if (err)
goto free_card;
}
if (!oldcard) {
err = mmc_sd_get_csd(card);
if (err)
goto free_card;
mmc_decode_cid(card);
}
/*
* handling only for cards supporting DSR and hosts requesting
* DSR configuration
*/
if (card->csd.dsr_imp && host->dsr_req)
mmc_set_dsr(host);
/*
* Select card, as all following commands rely on that.
*/
if (!mmc_host_is_spi(host)) {
err = mmc_select_card(card);
if (err)
goto free_card;
}
err = mmc_sd_setup_card(host, card, oldcard != NULL);
if (err)
goto free_card;
/*
* If the card has not been power cycled, it may still be using 1.8V
* signaling. Detect that situation and try to initialize a UHS-I (1.8V)
* transfer mode.
*/
if (!v18_fixup_failed && !mmc_host_is_spi(host) && mmc_host_uhs(host) &&
mmc_sd_card_using_v18(card) &&
host->ios.signal_voltage != MMC_SIGNAL_VOLTAGE_180) {
/*
* Re-read switch information in case it has changed since
* oldcard was initialized.
*/
if (oldcard) {
err = mmc_read_switch(card);
if (err)
goto free_card;
}
if (mmc_sd_card_using_v18(card)) {
if (mmc_host_set_uhs_voltage(host) ||
mmc_sd_init_uhs_card(card)) {
v18_fixup_failed = true;
mmc_power_cycle(host, ocr);
if (!oldcard)
mmc_remove_card(card);
goto retry;
}
goto done;
}
}
/* Initialization sequence for UHS-I cards */
if (rocr & SD_ROCR_S18A && mmc_host_uhs(host)) {
err = mmc_sd_init_uhs_card(card);
if (err)
goto free_card;
} else {
/*
* Attempt to change to high-speed (if supported)
*/
err = mmc_sd_switch_hs(card);
if (err > 0)
mmc_set_timing(card->host, MMC_TIMING_SD_HS);
else if (err)
goto free_card;
/*
* Set bus speed.
*/
mmc_set_clock(host, mmc_sd_get_max_clock(card));
/*
* Switch to wider bus (if supported).
*/
if ((host->caps & MMC_CAP_4_BIT_DATA) &&
(card->scr.bus_widths & SD_SCR_BUS_WIDTH_4)) {
err = mmc_app_set_bus_width(card, MMC_BUS_WIDTH_4);
if (err)
goto free_card;
mmc_set_bus_width(host, MMC_BUS_WIDTH_4);
}
}
if (!oldcard) {
/* Read/parse the extension registers. */
err = sd_read_ext_regs(card);
if (err)
goto free_card;
}
/* Enable internal SD cache if supported. */
if (card->ext_perf.feature_support & SD_EXT_PERF_CACHE) {
err = sd_enable_cache(card);
if (err)
goto free_card;
}
if (host->cqe_ops && !host->cqe_enabled) {
err = host->cqe_ops->cqe_enable(host, card);
if (!err) {
host->cqe_enabled = true;
host->hsq_enabled = true;
pr_info("%s: Host Software Queue enabled\n",
mmc_hostname(host));
}
}
if (host->caps2 & MMC_CAP2_AVOID_3_3V &&
host->ios.signal_voltage == MMC_SIGNAL_VOLTAGE_330) {
pr_err("%s: Host failed to negotiate down from 3.3V\n",
mmc_hostname(host));
err = -EINVAL;
goto free_card;
}
done:
host->card = card;
return 0;
free_card:
if (!oldcard)
mmc_remove_card(card);
return err;
}
/*
* Host is being removed. Free up the current card.
*/
static void mmc_sd_remove(struct mmc_host *host)
{
mmc_remove_card(host->card);
host->card = NULL;
}
/*
* Card detection - card is alive.
*/
static int mmc_sd_alive(struct mmc_host *host)
{
return mmc_send_status(host->card, NULL);
}
/*
* Card detection callback from host.
*/
static void mmc_sd_detect(struct mmc_host *host)
{
int err;
mmc_get_card(host->card, NULL);
/*
* Just check if our card has been removed.
*/
err = _mmc_detect_card_removed(host);
mmc_put_card(host->card, NULL);
if (err) {
mmc_sd_remove(host);
mmc_claim_host(host);
mmc_detach_bus(host);
mmc_power_off(host);
mmc_release_host(host);
}
}
static int sd_can_poweroff_notify(struct mmc_card *card)
{
return card->ext_power.feature_support & SD_EXT_POWER_OFF_NOTIFY;
}
static int sd_busy_poweroff_notify_cb(void *cb_data, bool *busy)
{
struct sd_busy_data *data = cb_data;
struct mmc_card *card = data->card;
int err;
/*
* Read the status register for the power management function. It's at
* one byte offset and is one byte long. The Power Off Notification
* Ready is bit 0.
*/
err = sd_read_ext_reg(card, card->ext_power.fno, card->ext_power.page,
card->ext_power.offset + 1, 1, data->reg_buf);
if (err) {
pr_warn("%s: error %d reading status reg of PM func\n",
mmc_hostname(card->host), err);
return err;
}
*busy = !(data->reg_buf[0] & BIT(0));
return 0;
}
static int sd_poweroff_notify(struct mmc_card *card)
{
struct sd_busy_data cb_data;
u8 *reg_buf;
int err;
reg_buf = kzalloc(512, GFP_KERNEL);
if (!reg_buf)
return -ENOMEM;
/*
* Set the Power Off Notification bit in the power management settings
* register at 2 bytes offset.
*/
err = sd_write_ext_reg(card, card->ext_power.fno, card->ext_power.page,
card->ext_power.offset + 2, BIT(0));
if (err) {
pr_warn("%s: error %d writing Power Off Notify bit\n",
mmc_hostname(card->host), err);
goto out;
}
cb_data.card = card;
cb_data.reg_buf = reg_buf;
err = __mmc_poll_for_busy(card, SD_POWEROFF_NOTIFY_TIMEOUT_MS,
&sd_busy_poweroff_notify_cb, &cb_data);
out:
kfree(reg_buf);
return err;
}
static int _mmc_sd_suspend(struct mmc_host *host)
{
struct mmc_card *card = host->card;
int err = 0;
mmc_claim_host(host);
if (mmc_card_suspended(card))
goto out;
if (sd_can_poweroff_notify(card))
err = sd_poweroff_notify(card);
else if (!mmc_host_is_spi(host))
err = mmc_deselect_cards(host);
if (!err) {
mmc_power_off(host);
mmc_card_set_suspended(card);
}
out:
mmc_release_host(host);
return err;
}
/*
* Callback for suspend
*/
static int mmc_sd_suspend(struct mmc_host *host)
{
int err;
err = _mmc_sd_suspend(host);
if (!err) {
pm_runtime_disable(&host->card->dev);
pm_runtime_set_suspended(&host->card->dev);
}
return err;
}
/*
* This function tries to determine if the same card is still present
* and, if so, restore all state to it.
*/
static int _mmc_sd_resume(struct mmc_host *host)
{
int err = 0;
mmc_claim_host(host);
if (!mmc_card_suspended(host->card))
goto out;
mmc_power_up(host, host->card->ocr);
err = mmc_sd_init_card(host, host->card->ocr, host->card);
mmc_card_clr_suspended(host->card);
out:
mmc_release_host(host);
return err;
}
/*
* Callback for resume
*/
static int mmc_sd_resume(struct mmc_host *host)
{
pm_runtime_enable(&host->card->dev);
return 0;
}
/*
* Callback for runtime_suspend.
*/
static int mmc_sd_runtime_suspend(struct mmc_host *host)
{
int err;
if (!(host->caps & MMC_CAP_AGGRESSIVE_PM))
return 0;
err = _mmc_sd_suspend(host);
if (err)
pr_err("%s: error %d doing aggressive suspend\n",
mmc_hostname(host), err);
return err;
}
/*
* Callback for runtime_resume.
*/
static int mmc_sd_runtime_resume(struct mmc_host *host)
{
int err;
err = _mmc_sd_resume(host);
if (err && err != -ENOMEDIUM)
pr_err("%s: error %d doing runtime resume\n",
mmc_hostname(host), err);
return 0;
}
static int mmc_sd_hw_reset(struct mmc_host *host)
{
mmc_power_cycle(host, host->card->ocr);
return mmc_sd_init_card(host, host->card->ocr, host->card);
}
static const struct mmc_bus_ops mmc_sd_ops = {
.remove = mmc_sd_remove,
.detect = mmc_sd_detect,
.runtime_suspend = mmc_sd_runtime_suspend,
.runtime_resume = mmc_sd_runtime_resume,
.suspend = mmc_sd_suspend,
.resume = mmc_sd_resume,
.alive = mmc_sd_alive,
.shutdown = mmc_sd_suspend,
.hw_reset = mmc_sd_hw_reset,
.cache_enabled = sd_cache_enabled,
.flush_cache = sd_flush_cache,
};
/*
* Starting point for SD card init.
*/
int mmc_attach_sd(struct mmc_host *host)
{
int err;
u32 ocr, rocr;
WARN_ON(!host->claimed);
err = mmc_send_app_op_cond(host, 0, &ocr);
if (err)
return err;
mmc_attach_bus(host, &mmc_sd_ops);
if (host->ocr_avail_sd)
host->ocr_avail = host->ocr_avail_sd;
/*
* We need to get OCR a different way for SPI.
*/
if (mmc_host_is_spi(host)) {
mmc_go_idle(host);
err = mmc_spi_read_ocr(host, 0, &ocr);
if (err)
goto err;
}
/*
* Some SD cards claims an out of spec VDD voltage range. Let's treat
* these bits as being in-valid and especially also bit7.
*/
ocr &= ~0x7FFF;
rocr = mmc_select_voltage(host, ocr);
/*
* Can we support the voltage(s) of the card(s)?
*/
if (!rocr) {
err = -EINVAL;
goto err;
}
/*
* Detect and init the card.
*/
err = mmc_sd_init_card(host, rocr, NULL);
if (err)
goto err;
mmc_release_host(host);
err = mmc_add_card(host->card);
if (err)
goto remove_card;
mmc_claim_host(host);
return 0;
remove_card:
mmc_remove_card(host->card);
host->card = NULL;
mmc_claim_host(host);
err:
mmc_detach_bus(host);
pr_err("%s: error %d whilst initialising SD card\n",
mmc_hostname(host), err);
return err;
}
|
622176.c | /* Copyright (c) 2014 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.
*
*/
/** @file
* @defgroup uart_example_main main.c
* @{
* @ingroup uart_example
* @brief UART Example Application main file.
*
* This file contains the source code for a sample application using UART.
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "app_uart.h"
#include "app_error.h"
#include "nrf_delay.h"
#include "nrf.h"
#include "bsp.h"
//#define ENABLE_LOOPBACK_TEST /**< if defined, then this example will be a loopback test, which means that TX should be connected to RX to get data loopback. */
#define MAX_TEST_DATA_BYTES (15U) /**< max number of test bytes to be used for tx and rx. */
#define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 1 /**< UART RX buffer size. */
void uart_error_handle(app_uart_evt_t * p_event)
{
if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_communication);
}
else if (p_event->evt_type == APP_UART_FIFO_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_code);
}
}
#ifdef ENABLE_LOOPBACK_TEST
/** @brief Function for setting the @ref ERROR_PIN high, and then enter an infinite loop.
*/
static void show_error(void)
{
LEDS_ON(LEDS_MASK);
while(true)
{
// Do nothing.
}
}
/** @brief Function for testing UART loop back.
* @details Transmitts one character at a time to check if the data received from the loopback is same as the transmitted data.
* @note @ref TX_PIN_NUMBER must be connected to @ref RX_PIN_NUMBER)
*/
static void uart_loopback_test()
{
uint8_t * tx_data = (uint8_t *)("\n\rLOOPBACK_TEST\n\r");
uint8_t rx_data;
// Start sending one byte and see if you get the same
for (uint32_t i = 0; i < MAX_TEST_DATA_BYTES; i++)
{
uint32_t err_code;
while(app_uart_put(tx_data[i]) != NRF_SUCCESS);
nrf_delay_ms(10);
err_code = app_uart_get(&rx_data);
if ((rx_data != tx_data[i]) || (err_code != NRF_SUCCESS))
{
show_error();
}
}
return;
}
#endif
/**
* @brief Function for main application entry.
*/
int main(void)
{
LEDS_CONFIGURE(LEDS_MASK);
LEDS_OFF(LEDS_MASK);
uint32_t err_code;
const app_uart_comm_params_t comm_params =
{
RX_PIN_NUMBER,
TX_PIN_NUMBER,
RTS_PIN_NUMBER,
CTS_PIN_NUMBER,
APP_UART_FLOW_CONTROL_ENABLED,
false,
UART_BAUDRATE_BAUDRATE_Baud115200
};
APP_UART_FIFO_INIT(&comm_params,
UART_RX_BUF_SIZE,
UART_TX_BUF_SIZE,
uart_error_handle,
APP_IRQ_PRIORITY_LOW,
err_code);
APP_ERROR_CHECK(err_code);
#ifndef ENABLE_LOOPBACK_TEST
printf("\n\rStart: \n\r");
while (true)
{
uint8_t cr;
while(app_uart_get(&cr) != NRF_SUCCESS);
while(app_uart_put(cr) != NRF_SUCCESS);
if (cr == 'q' || cr == 'Q')
{
printf(" \n\rExit!\n\r");
while (true)
{
// Do nothing.
}
}
}
#else
// This part of the example is just for testing the loopback .
while (true)
{
uart_loopback_test();
}
#endif
}
/** @} */
|
784941.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "dsp/core/c1331.h"
#include "dsp/core/c161.h"
#include "dsp/core/core.h"
#include "dsp/scale/scale.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/limits.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.h"
#include "libc/math.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/bsr.h"
#include "libc/rand/rand.h"
#include "libc/runtime/gc.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/testlib/testlib.h"
#include "libc/x/x.h"
#include "third_party/gdtoa/gdtoa.h"
#include "third_party/getopt/getopt.h"
#include "third_party/stb/stb_image.h"
#include "tool/viz/lib/bilinearscale.h"
#include "tool/viz/lib/graphic.h"
#define LONG long
#define CHAR char
#define CLAMP(X) MIN(255, MAX(0, X))
#define C13(A, B) (((A) + 3 * (B) + 2) >> 2)
#define LERP(X, Y, P) ((X) + (((P) * ((Y) - (X))) >> 8))
static double r_;
static unsigned char ChessBoard(unsigned y, unsigned x, unsigned char a,
unsigned char b) {
return !((y ^ x) & (1u << 2)) ? a : b;
}
static unsigned char AlphaBackground(unsigned y, unsigned x) {
return ChessBoard(y, x, 255, 200);
}
static unsigned char OutOfBoundsBackground(unsigned y, unsigned x) {
return ChessBoard(y, x, 40, 80);
}
static unsigned char Opacify(CHAR w, const unsigned char P[1u << w][1u << w],
const unsigned char A[1u << w][1u << w], LONG yn,
LONG xn, long y, long x) {
if ((0 <= y && y < yn) && (0 <= x && x < xn)) {
return LERP(AlphaBackground(y, x), P[y][x], A[y][x]);
} else {
return OutOfBoundsBackground(y, x);
}
}
static void PrintImage(CHAR w, unsigned char R[1u << w][1u << w],
unsigned char G[1u << w][1u << w],
unsigned char B[1u << w][1u << w],
unsigned char A[1u << w][1u << w], LONG yn, LONG xn) {
bool didhalfy;
long y, x;
didhalfy = false;
for (y = 0; y < yn; y += 2) {
if (y) printf("\e[0m\n");
for (x = 0; x < xn; ++x) {
printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄",
Opacify(w, R, A, yn, xn, y + 0, x),
Opacify(w, G, A, yn, xn, y + 0, x),
Opacify(w, B, A, yn, xn, y + 0, x),
Opacify(w, R, A, yn, xn, y + 1, x),
Opacify(w, G, A, yn, xn, y + 1, x),
Opacify(w, B, A, yn, xn, y + 1, x));
}
if (y == 0) {
printf("\e[0m‾0");
} else if (yn / 2 <= y && y <= yn / 2 + 1 && !didhalfy) {
printf("\e[0m‾%s%s", "yn/2", y % 2 ? "+1" : "");
didhalfy = true;
} else if (y + 1 == yn / 2 && !didhalfy) {
printf("\e[0m⎯yn/2");
didhalfy = true;
} else if (y + 1 == yn) {
printf("\e[0m⎯yn");
} else if (y + 2 == yn) {
printf("\e[0m_yn");
} else if (!(y % 10)) {
printf("\e[0m‾%,u", y);
}
}
printf("\e[0m\n");
}
static void DeblinterlaceRgba(CHAR w, unsigned char R[1u << w][1u << w],
unsigned char G[1u << w][1u << w],
unsigned char B[1u << w][1u << w],
unsigned char A[1u << w][1u << w], LONG yn,
LONG xn, const unsigned char src[yn][xn][4]) {
long y, x;
for (y = 0; y < yn; ++y) {
for (x = 0; x < xn; ++x) {
R[y][x] = src[y][x][0];
G[y][x] = src[y][x][1];
B[y][x] = src[y][x][2];
A[y][x] = src[y][x][3];
}
}
}
static void SharpenX(CHAR w, unsigned char dst[1u << w][1u << w],
const unsigned char src[1u << w][1u << w], char yw,
char xw) {
int y, x;
for (y = 0; y < (1u << yw); ++y) {
for (x = 0; x < (1u << xw); ++x) {
dst[y][x] = C161(src[y][MAX(0, x - 1)], src[y][x],
src[y][MIN((1u << xw) - 1, x + 1)]);
}
}
}
static void SharpenY(CHAR w, unsigned char dst[1u << w][1u << w],
const unsigned char src[1u << w][1u << w], char yw,
char xw) {
int y, x;
for (y = 0; y < (1u << yw); ++y) {
for (x = 0; x < (1u << xw); ++x) {
dst[y][x] = C161(src[MAX(0, y - 1)][x], src[y][x],
src[MIN((1u << yw) - 1, y + 1)][x]);
}
}
}
static void UpscaleX(CHAR w, unsigned char img[1u << w][1u << w], char yw,
char xw) {
long y, x;
for (y = (1u << yw); y--;) {
for (x = (1u << xw); --x;) {
img[y][x] =
C13(img[y][MIN(((1u << xw) >> 1) - 1, (x >> 1) - 1 + (x & 1) * 2)],
img[y][x >> 1]);
}
}
}
static void UpscaleY(CHAR w, unsigned char img[1u << w][1u << w], char yw,
char xw) {
long y, x;
for (y = (1u << yw); --y;) {
for (x = (1u << xw); x--;) {
img[y][x] =
C13(img[MIN(((1u << yw) >> 1) - 1, (y >> 1) - 1 + (y & 1) * 2)][x],
img[y >> 1][x]);
}
}
}
static void Upscale(CHAR w, unsigned char img[1u << w][1u << w],
unsigned char tmp[1u << w][1u << w], char yw, char xw) {
UpscaleY(w, img, yw, xw - 1);
SharpenY(w, tmp, img, yw, xw - 1);
UpscaleX(w, tmp, yw, xw);
SharpenX(w, img, tmp, yw, xw);
}
#if 0
static void *MagikarpY(CHAR w, unsigned char p[1u << w][1u << w], char yw,
char xw) {
long y, x, yn, xn, ym;
unsigned char(*t)[(1u << w) + 2][1u << w];
t = memalign(64, ((1u << w) + 2) * (1u << w));
memset(t, 0, ((1u << w) + 2) * (1u << w));
yn = 1u << yw;
xn = 1u << xw;
ym = yn >> 1;
for (y = 0; y < ym; ++y) {
for (x = 0; x < xn; ++x) {
(*t)[y + 1][x] =
C1331(y ? p[(y << 1) - 1][x] : 0, p[y << 1][x], p[(y << 1) + 1][x],
p[MIN(yn - 1, (y << 1) + 2)][x]);
}
}
for (y = 0; y < ym; ++y) {
for (x = 0; x < xn; ++x) {
p[y][x] =
C161((*t)[y + 1 - 1][x], (*t)[y + 1 + 0][x], (*t)[y + 1 + 1][x]);
}
}
free(t);
return p;
}
static void *MagikarpX(CHAR w, unsigned char p[1u << w][1u << w], char yw,
char xw) {
int y, x;
LONG yn, xn, xm;
yn = 1u << yw;
xn = 1u << xw;
xm = xn >> 1;
for (x = 0; x < xm; ++x) {
for (y = 0; y < yn; ++y) {
p[y][(xn - xm - 1) + (xm - x - 1)] =
C1331(p[y][MAX(00 + 0, xn - (x << 1) - 1 + (xn & 1) - 1)],
p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 0)],
p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 1)],
p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 2)]);
}
}
for (x = 0; x < xm; ++x) {
for (y = 0; y < yn; ++y) {
p[y][x] = C161(p[y][MAX(xn - 1 - xm, xn - xm - 1 + x - 1)],
p[y][MIN(xn - 1 - 00, xn - xm - 1 + x + 0)],
p[y][MIN(xn - 1 - 00, xn - xm - 1 + x + 1)]);
}
}
return p;
}
static void ProcessImageVerbatim(LONG yn, LONG xn,
unsigned char img[yn][xn][4]) {
CHAR w;
void *R, *G, *B, *A;
w = roundup2log(MAX(yn, xn));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn, xn, img);
PrintImage(w, R, G, B, A, yn, xn);
free(R);
free(G);
free(B);
free(A);
}
static void ProcessImageDouble(LONG yn, LONG xn, unsigned char img[yn][xn][4]) {
CHAR w;
void *t, *R, *G, *B, *A;
w = roundup2log(MAX(yn, xn)) + 1;
t = xvalloc((1u << w) * (1u << w));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn, xn, img);
Upscale(w, R, t, w, w);
Upscale(w, G, t, w, w);
Upscale(w, B, t, w, w);
Upscale(w, A, t, w, w);
free(t);
PrintImage(w, R, G, B, A, yn * 2, xn * 2);
free(R);
free(G);
free(B);
free(A);
}
static void ProcessImageHalf(LONG yn, LONG xn, unsigned char img[yn][xn][4]) {
CHAR w;
void *R, *G, *B, *A;
w = roundup2log(MAX(yn, xn));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn, xn, img);
MagikarpY(w, R, w, w);
MagikarpY(w, G, w, w);
MagikarpY(w, B, w, w);
MagikarpY(w, A, w, w);
MagikarpX(w, R, w - 1, w);
MagikarpX(w, G, w - 1, w);
MagikarpX(w, B, w - 1, w);
MagikarpX(w, A, w - 1, w);
PrintImage(w, R, G, B, A, yn >> 1, xn >> 1);
free(R);
free(G);
free(B);
free(A);
}
static void ProcessImageHalfY(LONG yn, LONG xn, unsigned char img[yn][xn][4]) {
CHAR w;
void *R, *G, *B, *A;
w = roundup2log(MAX(yn, xn));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn, xn, img);
MagikarpY(w, R, w, w);
MagikarpY(w, G, w, w);
MagikarpY(w, B, w, w);
MagikarpY(w, A, w, w);
PrintImage(w, R, G, B, A, yn >> 1, xn);
free(R);
free(G);
free(B);
free(A);
}
static void ProcessImageHalfLanczos(LONG yn, LONG xn,
unsigned char img[yn][xn][4]) {
CHAR w;
void *t, *R, *G, *B, *A;
t = xvalloc((yn >> 1) * (xn >> 1) * 4);
lanczos1b(yn >> 1, xn >> 1, t, yn, xn, &img[0][0][0]);
w = roundup2log(MAX(yn >> 1, xn >> 1));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn >> 1, xn >> 1, img);
free(t);
PrintImage(w, R, G, B, A, yn >> 1, xn >> 1);
free(R);
free(G);
free(B);
free(A);
}
static void ProcessImageWash(LONG yn, LONG xn, unsigned char img[yn][xn][4]) {
long w;
void *R, *G, *B, *A, *t;
w = roundup2log(MAX(yn, xn)) + 1;
t = xvalloc((1u << w) * (1u << w));
R = xvalloc((1u << w) * (1u << w));
G = xvalloc((1u << w) * (1u << w));
B = xvalloc((1u << w) * (1u << w));
A = xvalloc((1u << w) * (1u << w));
DeblinterlaceRgba(w, R, G, B, A, yn, xn, img);
Upscale(w, R, t, w, w);
Upscale(w, G, t, w, w);
Upscale(w, B, t, w, w);
Upscale(w, A, t, w, w);
MagikarpY(w, R, w, w);
MagikarpY(w, G, w, w);
MagikarpY(w, B, w, w);
MagikarpY(w, A, w, w);
MagikarpX(w, R, w - 1, w);
MagikarpX(w, G, w - 1, w);
MagikarpX(w, B, w - 1, w);
MagikarpX(w, A, w - 1, w);
free(t);
PrintImage(w, R, G, B, A, yn, xn);
free(R);
free(G);
free(B);
free(A);
}
#endif
#if 0
static void *MagikarpY(size_t ys, size_t xs, unsigned char p[ys][xs], size_t yn,
size_t xn) {
int y, x, h, b;
b = yn % 2;
h = yn / 2;
if (b && yn < ys) yn++;
for (y = b; y < h + b; ++y) {
for (x = 0; x < xn; ++x) {
p[(yn - h - 1) + (h - y - 1)][x] =
C1331(p[MAX(00 + 0, yn - y * 2 - 1 - 1)][x],
p[MIN(yn - 1, yn - y * 2 - 1 + 0)][x],
p[MIN(yn - 1, yn - y * 2 - 1 + 1)][x],
p[MIN(yn - 1, yn - y * 2 - 1 + 2)][x]);
}
}
for (y = b; y < h + b; ++y) {
for (x = 0; x < xn; ++x) {
p[y][x] = C161(p[MAX(yn - 1 - h, yn - h - 1 + y - 1)][x],
p[MIN(yn - 1 - 0, yn - h - 1 + y + 0)][x],
p[MIN(yn - 1 - 0, yn - h - 1 + y + 1)][x]);
}
}
return p;
}
#endif
#if 0
static void *MagikarpX(size_t ys, size_t xs, unsigned char p[ys][xs], size_t yn,
size_t xn) {
int y, x, w, b;
b = xn % 2;
w = xn / 2;
if (b && xn < xs) xn++;
for (x = 0; x < w; ++x) {
for (y = b; y < yn + b; ++y) {
p[y][(xn - w - 1) + (w - x - 1)] =
C1331(p[y][MAX(00 + 0, xn - x * 2 - 1 - 1)],
p[y][MIN(xn - 1, xn - x * 2 - 1 + 0)],
p[y][MIN(xn - 1, xn - x * 2 - 1 + 1)],
p[y][MIN(xn - 1, xn - x * 2 - 1 + 2)]);
}
}
for (x = 0; x < w; ++x) {
for (y = b; y < yn + b; ++y) {
p[y][x] = C161(p[y][MAX(xn - 1 - w, xn - w - 1 + x - 1)],
p[y][MIN(xn - 1 - 0, xn - w - 1 + x + 0)],
p[y][MIN(xn - 1 - 0, xn - w - 1 + x + 1)]);
}
}
return p;
}
#endif
#if 0
static void ProcessImageMagikarpImpl(CHAR sw,
unsigned char src[5][1u << sw][1u << sw],
LONG syn, LONG sxn,
const unsigned char img[syn][sxn][4],
LONG dyn, LONG dxn) {
DeblinterlaceRgba2(sw, src, syn, sxn, img);
MagikarpY(sw, src[0], sw, sw);
MagikarpX(sw, src[0], sw - 1, sw);
MagikarpY(sw, src[1], sw, sw);
MagikarpX(sw, src[1], sw - 1, sw);
MagikarpY(sw, src[2], sw, sw);
MagikarpX(sw, src[2], sw - 1, sw);
BilinearScale(sw, src[4], sw, src[3], dyn, dxn, syn, sxn);
memcpy(src[3], src[4], syn * sxn);
PrintImage2(sw, src, dyn, dxn);
}
static void ProcessImageMagikarp(LONG syn, LONG sxn,
unsigned char img[syn][sxn][4]) {
CHAR sw;
LONG dyn, dxn;
dyn = syn >> 1;
dxn = sxn >> 1;
sw = roundup2log(MAX(syn, sxn));
ProcessImageMagikarpImpl(sw, gc(xvalloc((1u << sw) * (1u << sw) * 5)), syn,
sxn, img, dyn, dxn);
}
#endif
/*
********************************************************************************
*/
static unsigned char Opacify2(unsigned yw, unsigned xw,
const unsigned char P[yw][xw],
const unsigned char A[yw][xw], unsigned yn,
unsigned xn, unsigned y, unsigned x) {
if ((0 <= y && y < yn) && (0 <= x && x < xn)) {
return LERP(AlphaBackground(y, x), P[y][x], A[y][x]);
} else {
return OutOfBoundsBackground(y, x);
}
}
static noinline void PrintImage2(unsigned yw, unsigned xw,
unsigned char img[4][yw][xw], unsigned yn,
unsigned xn) {
bool didhalfy;
unsigned y, x;
didhalfy = false;
for (y = 0; y < yn; y += 2) {
if (y) printf("\e[0m\n");
for (x = 0; x < xn; ++x) {
printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄",
Opacify2(yw, xw, img[0], img[3], yn, xn, y + 0, x),
Opacify2(yw, xw, img[1], img[3], yn, xn, y + 0, x),
Opacify2(yw, xw, img[2], img[3], yn, xn, y + 0, x),
Opacify2(yw, xw, img[0], img[3], yn, xn, y + 1, x),
Opacify2(yw, xw, img[1], img[3], yn, xn, y + 1, x),
Opacify2(yw, xw, img[2], img[3], yn, xn, y + 1, x));
}
if (y == 0) {
printf("\e[0m‾0");
} else if (yn / 2 <= y && y <= yn / 2 + 1 && !didhalfy) {
printf("\e[0m‾%s%s", "yn/2", y % 2 ? "+1" : "");
didhalfy = true;
} else if (y + 1 == yn / 2 && !didhalfy) {
printf("\e[0m⎯yn/2");
didhalfy = true;
} else if (y + 1 == yn) {
printf("\e[0m⎯yn");
} else if (y + 2 == yn) {
printf("\e[0m_yn");
} else if (!(y % 10)) {
printf("\e[0m‾%,u", y);
}
}
printf("\e[0m\n");
}
static noinline void *DeblinterlaceRgba2(unsigned yn, unsigned xn,
unsigned char D[4][yn][xn],
const unsigned char S[yn][xn][4]) {
unsigned y, x;
for (y = 0; y < yn; ++y) {
for (x = 0; x < xn; ++x) {
D[0][y][x] = S[y][x][0];
D[1][y][x] = S[y][x][1];
D[2][y][x] = S[y][x][2];
D[3][y][x] = S[y][x][3];
}
}
return D;
}
void ProcessImageBilinearImpl(unsigned dyn, unsigned dxn,
unsigned char dst[4][dyn][dxn], unsigned syn,
unsigned sxn, unsigned char src[4][syn][sxn],
unsigned char img[syn][sxn][4]) {
DeblinterlaceRgba2(syn, sxn, src, img);
BilinearScale(4, dyn, dxn, dst, 4, syn, sxn, src, 0, 4, dyn, dxn, syn, sxn,
r_, r_, 0, 0);
PrintImage2(dyn, dxn, dst, dyn, dxn);
}
void ProcessImageBilinear(unsigned yn, unsigned xn,
unsigned char img[yn][xn][4]) {
unsigned dyn, dxn;
dyn = lround(yn / r_);
dxn = lround(xn / r_);
ProcessImageBilinearImpl(dyn, dxn, gc(xmalloc(dyn * dxn * 4)), yn, xn,
gc(xmalloc(yn * xn * 4)), img);
}
static void *b2f(long n, float dst[n], const unsigned char src[n]) {
long i;
float f;
for (i = 0; i < n; ++i) {
f = src[i];
f *= 1 / 255.;
dst[i] = f;
}
return dst;
}
static void *f2b(long n, unsigned char dst[n], const float src[n]) {
int x;
long i;
for (i = 0; i < n; ++i) {
x = lroundf(src[i] * 255);
dst[i] = MIN(255, MAX(0, x));
}
return dst;
}
void ProcessImageGyarados(unsigned yn, unsigned xn,
unsigned char img[yn][xn][4]) {
unsigned dyn, dxn;
dyn = lround(yn / r_);
dxn = lround(xn / r_);
PrintImage2(
dyn, dxn,
EzGyarados(4, dyn, dxn, gc(xmalloc(dyn * dxn * 4)), 4, yn, xn,
DeblinterlaceRgba2(yn, xn, gc(xmalloc(yn * xn * 4)), img), 0,
4, dyn, dxn, yn, xn, r_, r_, 0, 0),
dyn, dxn);
}
void MagikarpDecimate(int yw, int xw, unsigned char img[4][yw][xw], int yn,
int xn, int n) {
int c;
if (n <= 1) {
PrintImage2(yw, xw, img, yn, xn);
} else {
for (c = 0; c < 4; ++c) Magikarp2xY(yw, xw, img[c], yn, xn);
for (c = 0; c < 4; ++c) Magikarp2xX(yw, xw, img[c], (yn + 1) / 2, xn);
MagikarpDecimate(yw, xw, img, (yn + 1) / 2, (xn + 1) / 2, (n + 1) / 2);
}
}
void ProcessImageMagikarp(unsigned yn, unsigned xn,
unsigned char img[yn][xn][4]) {
MagikarpDecimate(yn, xn,
DeblinterlaceRgba2(yn, xn, gc(xmalloc(yn * xn * 4)), img),
yn, xn, lround(r_));
}
noinline void WithImageFile(const char *path,
void fn(unsigned yn, unsigned xn,
unsigned char img[yn][xn][4])) {
struct stat st;
int fd, yn, xn;
void *map, *data;
CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path);
CHECK_NE(-1, fstat(fd, &st));
CHECK_GT(st.st_size, 0);
CHECK_LE(st.st_size, INT_MAX);
fadvise(fd, 0, 0, MADV_WILLNEED | MADV_SEQUENTIAL);
CHECK_NE(MAP_FAILED,
(map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)));
CHECK_NOTNULL(
(data = stbi_load_from_memory(map, st.st_size, &xn, &yn, NULL, 4)), "%s",
path);
CHECK_NE(-1, munmap(map, st.st_size));
CHECK_NE(-1, close(fd));
fn(yn, xn, data);
free(data);
}
int main(int argc, char *argv[]) {
int i, opt;
bool bilinear;
void (*scaler)(unsigned yn, unsigned xn, unsigned char[yn][xn][4]) =
ProcessImageMagikarp;
r_ = 2;
while ((opt = getopt(argc, argv, "mlsSybr:")) != -1) {
switch (opt) {
case 'r':
r_ = strtod(optarg, NULL);
break;
case 'm':
scaler = ProcessImageMagikarp;
break;
case 's':
case 'S':
scaler = ProcessImageGyarados;
break;
case 'b':
scaler = ProcessImageBilinear;
break;
default:
break;
}
}
showcrashreports();
for (i = optind; i < argc; ++i) {
WithImageFile(argv[i], scaler);
}
return 0;
}
|
285294.c | /* hexedit.c - Hexadecimal file editor
*
* Copyright 2015 Rob Landley <[email protected]>
*
* No standard
USE_HEXEDIT(NEWTOY(hexedit, "<1>1r", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LOCALE))
config HEXEDIT
bool "hexedit"
default y
help
usage: hexedit FILENAME
Hexadecimal file editor.
-r Read only (display but don't edit)
*/
#define FOR_hexedit
#include "toys.h"
GLOBALS(
char *data;
long long len, base;
int numlen, undo, undolen;
unsigned height;
)
#define UNDO_LEN (sizeof(toybuf)/(sizeof(long long)+1))
// Render all characters printable, using color to distinguish.
static void draw_char(char broiled)
{
if (broiled<32 || broiled>=127) {
if (broiled>127) {
tty_esc("2m");
broiled &= 127;
}
if (broiled<32 || broiled==127) {
tty_esc("7m");
if (broiled==127) broiled = 32;
else broiled += 64;
}
printf("%c", broiled);
tty_esc("0m");
} else printf("%c", broiled);
}
static void draw_tail(void)
{
int i = 0, width = 0, w, len;
char *start = *toys.optargs, *end;
tty_jump(0, TT.height);
tty_esc("K");
// First time, make sure we fit in 71 chars (advancing start as necessary).
// Second time, print from start to end, escaping nonprintable chars.
for (i=0; i<2; i++) {
for (end = start; *end;) {
wchar_t wc;
len = mbrtowc(&wc, end, 99, 0);
if (len<0 || wc<32 || (w = wcwidth(wc))<0) {
len = w = 1;
if (i) draw_char(*end);
} else if (i) fwrite(end, len, 1, stdout);
end += len;
if (!i) {
width += w;
while (width > 71) {
len = mbrtowc(&wc, start, 99, 0);
if (len<0 || wc<32 || (w = wcwidth(wc))<0) len = w = 1;
width -= w;
start += len;
}
}
}
}
}
static void draw_line(long long yy)
{
int x, xx = 16;
yy = (TT.base+yy)*16;
if (yy+xx>=TT.len) xx = TT.len-yy;
if (yy<TT.len) {
printf("\r%0*llX ", TT.numlen, yy);
for (x=0; x<xx; x++) printf(" %02X", TT.data[yy+x]);
printf("%*s", 2+3*(16-xx), "");
for (x=0; x<xx; x++) draw_char(TT.data[yy+x]);
printf("%*s", 16-xx, "");
}
tty_esc("K");
}
static void draw_page(void)
{
int y;
tty_jump(0, 0);
for (y = 0; y<TT.height; y++) {
if (y) printf("\r\n");
draw_line(y);
}
draw_tail();
}
// side: 0 = editing left, 1 = editing right, 2 = clear, 3 = read only
static void highlight(int xx, int yy, int side)
{
char cc = TT.data[16*(TT.base+yy)+xx];
int i;
// Display cursor
tty_jump(2+TT.numlen+3*xx, yy);
tty_esc("0m");
if (side!=2) tty_esc("7m");
if (side>1) printf("%02X", cc);
else for (i=0; i<2;) {
if (side==i) tty_esc("32m");
printf("%X", (cc>>(4*(1&++i)))&15);
}
tty_esc("0m");
tty_jump(TT.numlen+17*3+xx, yy);
draw_char(cc);
}
void hexedit_main(void)
{
long long pos = 0, y;
int x, i, side = 0, key, ro = toys.optflags&FLAG_r,
fd = xopen(*toys.optargs, ro ? O_RDONLY : O_RDWR);
char keybuf[16];
// Terminal setup
TT.height = 25;
terminal_size(0, &TT.height);
if (TT.height) TT.height--;
sigatexit(tty_sigreset);
tty_esc("0m");
tty_esc("?25l");
fflush(0);
set_terminal(1, 1, 0);
if ((TT.len = fdlength(fd))<0) error_exit("bad length");
if (sizeof(long)==32 && TT.len>SIZE_MAX) TT.len = SIZE_MAX;
// count file length hex in digits, rounded up to multiple of 4
for (pos = TT.len, TT.numlen = 0; pos; pos >>= 4, TT.numlen++);
TT.numlen += (4-TT.numlen)&3;
TT.data = mmap(0, TT.len, PROT_READ|(PROT_WRITE*!ro), MAP_SHARED, fd, 0);
draw_page();
for (;;) {
// Scroll display if necessary
if (pos<0) pos = 0;
if (pos>TT.len) pos = TT.len-1;
x = pos&15;
y = pos/16;
i = 0;
while (y<TT.base) {
if (TT.base-y>(TT.height/2)) {
TT.base = y;
draw_page();
} else {
TT.base--;
i++;
tty_esc("1T");
tty_jump(0, 0);
draw_line(0);
}
}
while (y>=TT.base+TT.height) {
if (y-(TT.base+TT.height)>(TT.height/2)) {
TT.base = y-TT.height-1;
draw_page();
} else {
TT.base++;
i++;
tty_esc("1S");
tty_jump(0, TT.height-1);
draw_line(TT.height-1);
}
}
if (i) draw_tail();
y -= TT.base;
// Display cursor and flush output
highlight(x, y, ro ? 3 : side);
xprintf("");
// Wait for next key
key = scan_key(keybuf, 1);
// Exit for q, ctrl-c, ctrl-d, escape, or EOF
if (key==-1 || key==3 || key==4 || key==27 || key=='q') break;
highlight(x, y, 2);
// Hex digit?
if (key>='a' && key<='f') key-=32;
if (!ro && ((key>='0' && key<='9') || (key>='A' && key<='F'))) {
if (!side) {
long long *ll = (long long *)toybuf;
ll[TT.undo] = pos;
toybuf[(sizeof(long long)*UNDO_LEN)+TT.undo++] = TT.data[pos];
if (TT.undolen < UNDO_LEN) TT.undolen++;
TT.undo %= UNDO_LEN;
}
i = key - '0';
if (i>9) i -= 7;
TT.data[pos] &= 15<<(4*side);
TT.data[pos] |= i<<(4*!side);
if (++side==2) {
highlight(x, y, side);
side = 0;
++pos;
}
} else side = 0;
if (key=='u') {
if (TT.undolen) {
long long *ll = (long long *)toybuf;
TT.undolen--;
if (!TT.undo) TT.undo = UNDO_LEN;
pos = ll[--TT.undo];
TT.data[pos] = toybuf[sizeof(long long)*UNDO_LEN+TT.undo];
}
} else if (key==KEY_UP) pos -= 16;
else if (key==KEY_DOWN) pos += 16;
else if (key==KEY_RIGHT) {
if (x<15) pos++;
} else if (key==KEY_LEFT) {
if (x) pos--;
} else if (key==KEY_PGUP) pos -= 16*TT.height;
else if (key==KEY_PGDN) pos += 16*TT.height;
else if (key==KEY_HOME) pos = 0;
else if (key==KEY_END) pos = TT.len-1;
}
munmap(TT.data, TT.len);
close(fd);
tty_reset();
}
|
482662.c | /*
* linux/arch/arm/mm/alignment.c
*
* Copyright (C) 1995 Linus Torvalds
* Modifications for ARM processor (c) 1995-2001 Russell King
* Thumb alignment fault fixups (c) 2004 MontaVista Software, Inc.
* - Adapted from gdb/sim/arm/thumbemu.c -- Thumb instruction emulation.
* Copyright (C) 1996, Cygnus Software Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/moduleparam.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/sched/debug.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/sched/signal.h>
#include <linux/uaccess.h>
#include <asm/cp15.h>
#include <asm/system_info.h>
#include <asm/unaligned.h>
#include <asm/opcodes.h>
#include "fault.h"
#include "mm.h"
/*
* 32-bit misaligned trap handler (c) 1998 San Mehat (CCC) -July 1998
* /proc/sys/debug/alignment, modified and integrated into
* Linux 2.1 by Russell King
*
* Speed optimisations and better fault handling by Russell King.
*
* *** NOTE ***
* This code is not portable to processors with late data abort handling.
*/
#define CODING_BITS(i) (i & 0x0e000000)
#define COND_BITS(i) (i & 0xf0000000)
#define LDST_I_BIT(i) (i & (1 << 26)) /* Immediate constant */
#define LDST_P_BIT(i) (i & (1 << 24)) /* Preindex */
#define LDST_U_BIT(i) (i & (1 << 23)) /* Add offset */
#define LDST_W_BIT(i) (i & (1 << 21)) /* Writeback */
#define LDST_L_BIT(i) (i & (1 << 20)) /* Load */
#define LDST_P_EQ_U(i) ((((i) ^ ((i) >> 1)) & (1 << 23)) == 0)
#define LDSTHD_I_BIT(i) (i & (1 << 22)) /* double/half-word immed */
#define LDM_S_BIT(i) (i & (1 << 22)) /* write CPSR from SPSR */
#define RN_BITS(i) ((i >> 16) & 15) /* Rn */
#define RD_BITS(i) ((i >> 12) & 15) /* Rd */
#define RM_BITS(i) (i & 15) /* Rm */
#define REGMASK_BITS(i) (i & 0xffff)
#define OFFSET_BITS(i) (i & 0x0fff)
#define IS_SHIFT(i) (i & 0x0ff0)
#define SHIFT_BITS(i) ((i >> 7) & 0x1f)
#define SHIFT_TYPE(i) (i & 0x60)
#define SHIFT_LSL 0x00
#define SHIFT_LSR 0x20
#define SHIFT_ASR 0x40
#define SHIFT_RORRRX 0x60
#define BAD_INSTR 0xdeadc0de
/* Thumb-2 32 bit format per ARMv7 DDI0406A A6.3, either f800h,e800h,f800h */
#define IS_T32(hi16) \
(((hi16) & 0xe000) == 0xe000 && ((hi16) & 0x1800))
static unsigned long ai_user;
static unsigned long ai_sys;
static void *ai_sys_last_pc;
static unsigned long ai_skipped;
static unsigned long ai_half;
static unsigned long ai_word;
static unsigned long ai_dword;
static unsigned long ai_multi;
static int ai_usermode;
static unsigned long cr_no_alignment;
core_param(alignment, ai_usermode, int, 0600);
#define UM_WARN (1 << 0)
#define UM_FIXUP (1 << 1)
#define UM_SIGNAL (1 << 2)
/* Return true if and only if the ARMv6 unaligned access model is in use. */
static bool cpu_is_v6_unaligned(void)
{
return cpu_architecture() >= CPU_ARCH_ARMv6 && get_cr() & CR_U;
}
static int safe_usermode(int new_usermode, bool warn)
{
/*
* ARMv6 and later CPUs can perform unaligned accesses for
* most single load and store instructions up to word size.
* LDM, STM, LDRD and STRD still need to be handled.
*
* Ignoring the alignment fault is not an option on these
* CPUs since we spin re-faulting the instruction without
* making any progress.
*/
if (cpu_is_v6_unaligned() && !(new_usermode & (UM_FIXUP | UM_SIGNAL))) {
new_usermode |= UM_FIXUP;
if (warn)
pr_warn("alignment: ignoring faults is unsafe on this CPU. Defaulting to fixup mode.\n");
}
return new_usermode;
}
#ifdef CONFIG_PROC_FS
static const char *usermode_action[] = {
"ignored",
"warn",
"fixup",
"fixup+warn",
"signal",
"signal+warn"
};
static int alignment_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "User:\t\t%lu\n", ai_user);
seq_printf(m, "System:\t\t%lu (%pF)\n", ai_sys, ai_sys_last_pc);
seq_printf(m, "Skipped:\t%lu\n", ai_skipped);
seq_printf(m, "Half:\t\t%lu\n", ai_half);
seq_printf(m, "Word:\t\t%lu\n", ai_word);
if (cpu_architecture() >= CPU_ARCH_ARMv5TE)
seq_printf(m, "DWord:\t\t%lu\n", ai_dword);
seq_printf(m, "Multi:\t\t%lu\n", ai_multi);
seq_printf(m, "User faults:\t%i (%s)\n", ai_usermode,
usermode_action[ai_usermode]);
return 0;
}
static int alignment_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, alignment_proc_show, NULL);
}
static ssize_t alignment_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *pos)
{
char mode;
if (count > 0) {
if (get_user(mode, buffer))
return -EFAULT;
if (mode >= '0' && mode <= '5')
ai_usermode = safe_usermode(mode - '0', true);
}
return count;
}
static const struct file_operations alignment_proc_fops = {
.open = alignment_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = alignment_proc_write,
};
#endif /* CONFIG_PROC_FS */
union offset_union {
unsigned long un;
signed long sn;
};
#define TYPE_ERROR 0
#define TYPE_FAULT 1
#define TYPE_LDST 2
#define TYPE_DONE 3
#ifdef __ARMEB__
#define BE 1
#define FIRST_BYTE_16 "mov %1, %1, ror #8\n"
#define FIRST_BYTE_32 "mov %1, %1, ror #24\n"
#define NEXT_BYTE "ror #24"
#else
#define BE 0
#define FIRST_BYTE_16
#define FIRST_BYTE_32
#define NEXT_BYTE "lsr #8"
#endif
#define __get8_unaligned_check(ins,val,addr,err) \
__asm__( \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
"2:\n" \
" .pushsection .text.fixup,\"ax\"\n" \
" .align 2\n" \
"3: mov %0, #1\n" \
" b 2b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 3b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (val), "=r" (addr) \
: "0" (err), "2" (addr))
#define __get16_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v, a = addr; \
__get8_unaligned_check(ins,v,a,err); \
val = v << ((BE) ? 8 : 0); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 0 : 8); \
if (err) \
goto fault; \
} while (0)
#define get16_unaligned_check(val,addr) \
__get16_unaligned_check("ldrb",val,addr)
#define get16t_unaligned_check(val,addr) \
__get16_unaligned_check("ldrbt",val,addr)
#define __get32_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v, a = addr; \
__get8_unaligned_check(ins,v,a,err); \
val = v << ((BE) ? 24 : 0); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 16 : 8); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 8 : 16); \
__get8_unaligned_check(ins,v,a,err); \
val |= v << ((BE) ? 0 : 24); \
if (err) \
goto fault; \
} while (0)
#define get32_unaligned_check(val,addr) \
__get32_unaligned_check("ldrb",val,addr)
#define get32t_unaligned_check(val,addr) \
__get32_unaligned_check("ldrbt",val,addr)
#define __put16_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( FIRST_BYTE_16 \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
"2: "ins" %1, [%2]\n" \
"3:\n" \
" .pushsection .text.fixup,\"ax\"\n" \
" .align 2\n" \
"4: mov %0, #1\n" \
" b 3b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 4b\n" \
" .long 2b, 4b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define put16_unaligned_check(val,addr) \
__put16_unaligned_check("strb",val,addr)
#define put16t_unaligned_check(val,addr) \
__put16_unaligned_check("strbt",val,addr)
#define __put32_unaligned_check(ins,val,addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( FIRST_BYTE_32 \
ARM( "1: "ins" %1, [%2], #1\n" ) \
THUMB( "1: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
ARM( "2: "ins" %1, [%2], #1\n" ) \
THUMB( "2: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
ARM( "3: "ins" %1, [%2], #1\n" ) \
THUMB( "3: "ins" %1, [%2]\n" ) \
THUMB( " add %2, %2, #1\n" ) \
" mov %1, %1, "NEXT_BYTE"\n" \
"4: "ins" %1, [%2]\n" \
"5:\n" \
" .pushsection .text.fixup,\"ax\"\n" \
" .align 2\n" \
"6: mov %0, #1\n" \
" b 5b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 6b\n" \
" .long 2b, 6b\n" \
" .long 3b, 6b\n" \
" .long 4b, 6b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define put32_unaligned_check(val,addr) \
__put32_unaligned_check("strb", val, addr)
#define put32t_unaligned_check(val,addr) \
__put32_unaligned_check("strbt", val, addr)
static void
do_alignment_finish_ldst(unsigned long addr, unsigned long instr, struct pt_regs *regs, union offset_union offset)
{
if (!LDST_U_BIT(instr))
offset.un = -offset.un;
if (!LDST_P_BIT(instr))
addr += offset.un;
if (!LDST_P_BIT(instr) || LDST_W_BIT(instr))
regs->uregs[RN_BITS(instr)] = addr;
}
static int
do_alignment_ldrhstrh(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
ai_half += 1;
if (user_mode(regs))
goto user;
if (LDST_L_BIT(instr)) {
unsigned long val;
get16_unaligned_check(val, addr);
/* signed half-word? */
if (instr & 0x40)
val = (signed long)((signed short) val);
regs->uregs[rd] = val;
} else
put16_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
user:
if (LDST_L_BIT(instr)) {
unsigned long val;
unsigned int __ua_flags = uaccess_save_and_enable();
get16t_unaligned_check(val, addr);
uaccess_restore(__ua_flags);
/* signed half-word? */
if (instr & 0x40)
val = (signed long)((signed short) val);
regs->uregs[rd] = val;
} else {
unsigned int __ua_flags = uaccess_save_and_enable();
put16t_unaligned_check(regs->uregs[rd], addr);
uaccess_restore(__ua_flags);
}
return TYPE_LDST;
fault:
return TYPE_FAULT;
}
static int
do_alignment_ldrdstrd(unsigned long addr, unsigned long instr,
struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
unsigned int rd2;
int load;
if ((instr & 0xfe000000) == 0xe8000000) {
/* ARMv7 Thumb-2 32-bit LDRD/STRD */
rd2 = (instr >> 8) & 0xf;
load = !!(LDST_L_BIT(instr));
} else if (((rd & 1) == 1) || (rd == 14))
goto bad;
else {
load = ((instr & 0xf0) == 0xd0);
rd2 = rd + 1;
}
ai_dword += 1;
if (user_mode(regs))
goto user;
if (load) {
unsigned long val;
get32_unaligned_check(val, addr);
regs->uregs[rd] = val;
get32_unaligned_check(val, addr + 4);
regs->uregs[rd2] = val;
} else {
put32_unaligned_check(regs->uregs[rd], addr);
put32_unaligned_check(regs->uregs[rd2], addr + 4);
}
return TYPE_LDST;
user:
if (load) {
unsigned long val, val2;
unsigned int __ua_flags = uaccess_save_and_enable();
get32t_unaligned_check(val, addr);
get32t_unaligned_check(val2, addr + 4);
uaccess_restore(__ua_flags);
regs->uregs[rd] = val;
regs->uregs[rd2] = val2;
} else {
unsigned int __ua_flags = uaccess_save_and_enable();
put32t_unaligned_check(regs->uregs[rd], addr);
put32t_unaligned_check(regs->uregs[rd2], addr + 4);
uaccess_restore(__ua_flags);
}
return TYPE_LDST;
bad:
return TYPE_ERROR;
fault:
return TYPE_FAULT;
}
static int
do_alignment_ldrstr(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
ai_word += 1;
if ((!LDST_P_BIT(instr) && LDST_W_BIT(instr)) || user_mode(regs))
goto trans;
if (LDST_L_BIT(instr)) {
unsigned int val;
get32_unaligned_check(val, addr);
regs->uregs[rd] = val;
} else
put32_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
trans:
if (LDST_L_BIT(instr)) {
unsigned int val;
unsigned int __ua_flags = uaccess_save_and_enable();
get32t_unaligned_check(val, addr);
uaccess_restore(__ua_flags);
regs->uregs[rd] = val;
} else {
unsigned int __ua_flags = uaccess_save_and_enable();
put32t_unaligned_check(regs->uregs[rd], addr);
uaccess_restore(__ua_flags);
}
return TYPE_LDST;
fault:
return TYPE_FAULT;
}
/*
* LDM/STM alignment handler.
*
* There are 4 variants of this instruction:
*
* B = rn pointer before instruction, A = rn pointer after instruction
* ------ increasing address ----->
* | | r0 | r1 | ... | rx | |
* PU = 01 B A
* PU = 11 B A
* PU = 00 A B
* PU = 10 A B
*/
static int
do_alignment_ldmstm(unsigned long addr, unsigned long instr, struct pt_regs *regs)
{
unsigned int rd, rn, correction, nr_regs, regbits;
unsigned long eaddr, newaddr;
if (LDM_S_BIT(instr))
goto bad;
correction = 4; /* processor implementation defined */
regs->ARM_pc += correction;
ai_multi += 1;
/* count the number of registers in the mask to be transferred */
nr_regs = hweight16(REGMASK_BITS(instr)) * 4;
rn = RN_BITS(instr);
newaddr = eaddr = regs->uregs[rn];
if (!LDST_U_BIT(instr))
nr_regs = -nr_regs;
newaddr += nr_regs;
if (!LDST_U_BIT(instr))
eaddr = newaddr;
if (LDST_P_EQ_U(instr)) /* U = P */
eaddr += 4;
/*
* For alignment faults on the ARM922T/ARM920T the MMU makes
* the FSR (and hence addr) equal to the updated base address
* of the multiple access rather than the restored value.
* Switch this message off if we've got a ARM92[02], otherwise
* [ls]dm alignment faults are noisy!
*/
#if !(defined CONFIG_CPU_ARM922T) && !(defined CONFIG_CPU_ARM920T)
/*
* This is a "hint" - we already have eaddr worked out by the
* processor for us.
*/
if (addr != eaddr) {
pr_err("LDMSTM: PC = %08lx, instr = %08lx, "
"addr = %08lx, eaddr = %08lx\n",
instruction_pointer(regs), instr, addr, eaddr);
show_regs(regs);
}
#endif
if (user_mode(regs)) {
unsigned int __ua_flags = uaccess_save_and_enable();
for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
regbits >>= 1, rd += 1)
if (regbits & 1) {
if (LDST_L_BIT(instr)) {
unsigned int val;
get32t_unaligned_check(val, eaddr);
regs->uregs[rd] = val;
} else
put32t_unaligned_check(regs->uregs[rd], eaddr);
eaddr += 4;
}
uaccess_restore(__ua_flags);
} else {
for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
regbits >>= 1, rd += 1)
if (regbits & 1) {
if (LDST_L_BIT(instr)) {
unsigned int val;
get32_unaligned_check(val, eaddr);
regs->uregs[rd] = val;
} else
put32_unaligned_check(regs->uregs[rd], eaddr);
eaddr += 4;
}
}
if (LDST_W_BIT(instr))
regs->uregs[rn] = newaddr;
if (!LDST_L_BIT(instr) || !(REGMASK_BITS(instr) & (1 << 15)))
regs->ARM_pc -= correction;
return TYPE_DONE;
fault:
regs->ARM_pc -= correction;
return TYPE_FAULT;
bad:
pr_err("Alignment trap: not handling ldm with s-bit set\n");
return TYPE_ERROR;
}
/*
* Convert Thumb ld/st instruction forms to equivalent ARM instructions so
* we can reuse ARM userland alignment fault fixups for Thumb.
*
* This implementation was initially based on the algorithm found in
* gdb/sim/arm/thumbemu.c. It is basically just a code reduction of same
* to convert only Thumb ld/st instruction forms to equivalent ARM forms.
*
* NOTES:
* 1. Comments below refer to ARM ARM DDI0100E Thumb Instruction sections.
* 2. If for some reason we're passed an non-ld/st Thumb instruction to
* decode, we return 0xdeadc0de. This should never happen under normal
* circumstances but if it does, we've got other problems to deal with
* elsewhere and we obviously can't fix those problems here.
*/
static unsigned long
thumb2arm(u16 tinstr)
{
u32 L = (tinstr & (1<<11)) >> 11;
switch ((tinstr & 0xf800) >> 11) {
/* 6.5.1 Format 1: */
case 0x6000 >> 11: /* 7.1.52 STR(1) */
case 0x6800 >> 11: /* 7.1.26 LDR(1) */
case 0x7000 >> 11: /* 7.1.55 STRB(1) */
case 0x7800 >> 11: /* 7.1.30 LDRB(1) */
return 0xe5800000 |
((tinstr & (1<<12)) << (22-12)) | /* fixup */
(L<<20) | /* L==1? */
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (31<<6)) >> /* immed_5 */
(6 - ((tinstr & (1<<12)) ? 0 : 2)));
case 0x8000 >> 11: /* 7.1.57 STRH(1) */
case 0x8800 >> 11: /* 7.1.32 LDRH(1) */
return 0xe1c000b0 |
(L<<20) | /* L==1? */
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (7<<6)) >> (6-1)) | /* immed_5[2:0] */
((tinstr & (3<<9)) >> (9-8)); /* immed_5[4:3] */
/* 6.5.1 Format 2: */
case 0x5000 >> 11:
case 0x5800 >> 11:
{
static const u32 subset[8] = {
0xe7800000, /* 7.1.53 STR(2) */
0xe18000b0, /* 7.1.58 STRH(2) */
0xe7c00000, /* 7.1.56 STRB(2) */
0xe19000d0, /* 7.1.34 LDRSB */
0xe7900000, /* 7.1.27 LDR(2) */
0xe19000b0, /* 7.1.33 LDRH(2) */
0xe7d00000, /* 7.1.31 LDRB(2) */
0xe19000f0 /* 7.1.35 LDRSH */
};
return subset[(tinstr & (7<<9)) >> 9] |
((tinstr & (7<<0)) << (12-0)) | /* Rd */
((tinstr & (7<<3)) << (16-3)) | /* Rn */
((tinstr & (7<<6)) >> (6-0)); /* Rm */
}
/* 6.5.1 Format 3: */
case 0x4800 >> 11: /* 7.1.28 LDR(3) */
/* NOTE: This case is not technically possible. We're
* loading 32-bit memory data via PC relative
* addressing mode. So we can and should eliminate
* this case. But I'll leave it here for now.
*/
return 0xe59f0000 |
((tinstr & (7<<8)) << (12-8)) | /* Rd */
((tinstr & 255) << (2-0)); /* immed_8 */
/* 6.5.1 Format 4: */
case 0x9000 >> 11: /* 7.1.54 STR(3) */
case 0x9800 >> 11: /* 7.1.29 LDR(4) */
return 0xe58d0000 |
(L<<20) | /* L==1? */
((tinstr & (7<<8)) << (12-8)) | /* Rd */
((tinstr & 255) << 2); /* immed_8 */
/* 6.6.1 Format 1: */
case 0xc000 >> 11: /* 7.1.51 STMIA */
case 0xc800 >> 11: /* 7.1.25 LDMIA */
{
u32 Rn = (tinstr & (7<<8)) >> 8;
u32 W = ((L<<Rn) & (tinstr&255)) ? 0 : 1<<21;
return 0xe8800000 | W | (L<<20) | (Rn<<16) |
(tinstr&255);
}
/* 6.6.1 Format 2: */
case 0xb000 >> 11: /* 7.1.48 PUSH */
case 0xb800 >> 11: /* 7.1.47 POP */
if ((tinstr & (3 << 9)) == 0x0400) {
static const u32 subset[4] = {
0xe92d0000, /* STMDB sp!,{registers} */
0xe92d4000, /* STMDB sp!,{registers,lr} */
0xe8bd0000, /* LDMIA sp!,{registers} */
0xe8bd8000 /* LDMIA sp!,{registers,pc} */
};
return subset[(L<<1) | ((tinstr & (1<<8)) >> 8)] |
(tinstr & 255); /* register_list */
}
/* Else fall through for illegal instruction case */
default:
return BAD_INSTR;
}
}
/*
* Convert Thumb-2 32 bit LDM, STM, LDRD, STRD to equivalent instruction
* handlable by ARM alignment handler, also find the corresponding handler,
* so that we can reuse ARM userland alignment fault fixups for Thumb.
*
* @pinstr: original Thumb-2 instruction; returns new handlable instruction
* @regs: register context.
* @poffset: return offset from faulted addr for later writeback
*
* NOTES:
* 1. Comments below refer to ARMv7 DDI0406A Thumb Instruction sections.
* 2. Register name Rt from ARMv7 is same as Rd from ARMv6 (Rd is Rt)
*/
static void *
do_alignment_t32_to_handler(unsigned long *pinstr, struct pt_regs *regs,
union offset_union *poffset)
{
unsigned long instr = *pinstr;
u16 tinst1 = (instr >> 16) & 0xffff;
u16 tinst2 = instr & 0xffff;
switch (tinst1 & 0xffe0) {
/* A6.3.5 Load/Store multiple */
case 0xe880: /* STM/STMIA/STMEA,LDM/LDMIA, PUSH/POP T2 */
case 0xe8a0: /* ...above writeback version */
case 0xe900: /* STMDB/STMFD, LDMDB/LDMEA */
case 0xe920: /* ...above writeback version */
/* no need offset decision since handler calculates it */
return do_alignment_ldmstm;
case 0xf840: /* POP/PUSH T3 (single register) */
if (RN_BITS(instr) == 13 && (tinst2 & 0x09ff) == 0x0904) {
u32 L = !!(LDST_L_BIT(instr));
const u32 subset[2] = {
0xe92d0000, /* STMDB sp!,{registers} */
0xe8bd0000, /* LDMIA sp!,{registers} */
};
*pinstr = subset[L] | (1<<RD_BITS(instr));
return do_alignment_ldmstm;
}
/* Else fall through for illegal instruction case */
break;
/* A6.3.6 Load/store double, STRD/LDRD(immed, lit, reg) */
case 0xe860:
case 0xe960:
case 0xe8e0:
case 0xe9e0:
poffset->un = (tinst2 & 0xff) << 2;
case 0xe940:
case 0xe9c0:
return do_alignment_ldrdstrd;
/*
* No need to handle load/store instructions up to word size
* since ARMv6 and later CPUs can perform unaligned accesses.
*/
default:
break;
}
return NULL;
}
static int
do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
union offset_union uninitialized_var(offset);
unsigned long instr = 0, instrptr;
int (*handler)(unsigned long addr, unsigned long instr, struct pt_regs *regs);
unsigned int type;
unsigned int fault;
u16 tinstr = 0;
int isize = 4;
int thumb2_32b = 0;
if (interrupts_enabled(regs))
local_irq_enable();
instrptr = instruction_pointer(regs);
if (thumb_mode(regs)) {
u16 *ptr = (u16 *)(instrptr & ~1);
fault = probe_kernel_address(ptr, tinstr);
tinstr = __mem_to_opcode_thumb16(tinstr);
if (!fault) {
if (cpu_architecture() >= CPU_ARCH_ARMv7 &&
IS_T32(tinstr)) {
/* Thumb-2 32-bit */
u16 tinst2 = 0;
fault = probe_kernel_address(ptr + 1, tinst2);
tinst2 = __mem_to_opcode_thumb16(tinst2);
instr = __opcode_thumb32_compose(tinstr, tinst2);
thumb2_32b = 1;
} else {
isize = 2;
instr = thumb2arm(tinstr);
}
}
} else {
fault = probe_kernel_address((void *)instrptr, instr);
instr = __mem_to_opcode_arm(instr);
}
if (fault) {
type = TYPE_FAULT;
goto bad_or_fault;
}
if (user_mode(regs))
goto user;
ai_sys += 1;
ai_sys_last_pc = (void *)instruction_pointer(regs);
fixup:
regs->ARM_pc += isize;
switch (CODING_BITS(instr)) {
case 0x00000000: /* 3.13.4 load/store instruction extensions */
if (LDSTHD_I_BIT(instr))
offset.un = (instr & 0xf00) >> 4 | (instr & 15);
else
offset.un = regs->uregs[RM_BITS(instr)];
if ((instr & 0x000000f0) == 0x000000b0 || /* LDRH, STRH */
(instr & 0x001000f0) == 0x001000f0) /* LDRSH */
handler = do_alignment_ldrhstrh;
else if ((instr & 0x001000f0) == 0x000000d0 || /* LDRD */
(instr & 0x001000f0) == 0x000000f0) /* STRD */
handler = do_alignment_ldrdstrd;
else if ((instr & 0x01f00ff0) == 0x01000090) /* SWP */
goto swp;
else
goto bad;
break;
case 0x04000000: /* ldr or str immediate */
if (COND_BITS(instr) == 0xf0000000) /* NEON VLDn, VSTn */
goto bad;
offset.un = OFFSET_BITS(instr);
handler = do_alignment_ldrstr;
break;
case 0x06000000: /* ldr or str register */
offset.un = regs->uregs[RM_BITS(instr)];
if (IS_SHIFT(instr)) {
unsigned int shiftval = SHIFT_BITS(instr);
switch(SHIFT_TYPE(instr)) {
case SHIFT_LSL:
offset.un <<= shiftval;
break;
case SHIFT_LSR:
offset.un >>= shiftval;
break;
case SHIFT_ASR:
offset.sn >>= shiftval;
break;
case SHIFT_RORRRX:
if (shiftval == 0) {
offset.un >>= 1;
if (regs->ARM_cpsr & PSR_C_BIT)
offset.un |= 1 << 31;
} else
offset.un = offset.un >> shiftval |
offset.un << (32 - shiftval);
break;
}
}
handler = do_alignment_ldrstr;
break;
case 0x08000000: /* ldm or stm, or thumb-2 32bit instruction */
if (thumb2_32b) {
offset.un = 0;
handler = do_alignment_t32_to_handler(&instr, regs, &offset);
} else {
offset.un = 0;
handler = do_alignment_ldmstm;
}
break;
default:
goto bad;
}
if (!handler)
goto bad;
type = handler(addr, instr, regs);
if (type == TYPE_ERROR || type == TYPE_FAULT) {
regs->ARM_pc -= isize;
goto bad_or_fault;
}
if (type == TYPE_LDST)
do_alignment_finish_ldst(addr, instr, regs, offset);
return 0;
bad_or_fault:
if (type == TYPE_ERROR)
goto bad;
/*
* We got a fault - fix it up, or die.
*/
do_bad_area(addr, fsr, regs);
return 0;
swp:
pr_err("Alignment trap: not handling swp instruction\n");
bad:
/*
* Oops, we didn't handle the instruction.
*/
pr_err("Alignment trap: not handling instruction "
"%0*lx at [<%08lx>]\n",
isize << 1,
isize == 2 ? tinstr : instr, instrptr);
ai_skipped += 1;
return 1;
user:
ai_user += 1;
if (ai_usermode & UM_WARN)
printk("Alignment trap: %s (%d) PC=0x%08lx Instr=0x%0*lx "
"Address=0x%08lx FSR 0x%03x\n", current->comm,
task_pid_nr(current), instrptr,
isize << 1,
isize == 2 ? tinstr : instr,
addr, fsr);
if (ai_usermode & UM_FIXUP)
goto fixup;
if (ai_usermode & UM_SIGNAL) {
siginfo_t si;
si.si_signo = SIGBUS;
si.si_errno = 0;
si.si_code = BUS_ADRALN;
si.si_addr = (void __user *)addr;
force_sig_info(si.si_signo, &si, current);
} else {
/*
* We're about to disable the alignment trap and return to
* user space. But if an interrupt occurs before actually
* reaching user space, then the IRQ vector entry code will
* notice that we were still in kernel space and therefore
* the alignment trap won't be re-enabled in that case as it
* is presumed to be always on from kernel space.
* Let's prevent that race by disabling interrupts here (they
* are disabled on the way back to user space anyway in
* entry-common.S) and disable the alignment trap only if
* there is no work pending for this thread.
*/
raw_local_irq_disable();
if (!(current_thread_info()->flags & _TIF_WORK_MASK))
set_cr(cr_no_alignment);
}
return 0;
}
static int __init noalign_setup(char *__unused)
{
set_cr(__clear_cr(CR_A));
return 1;
}
__setup("noalign", noalign_setup);
/*
* This needs to be done after sysctl_init, otherwise sys/ will be
* overwritten. Actually, this shouldn't be in sys/ at all since
* it isn't a sysctl, and it doesn't contain sysctl information.
* We now locate it in /proc/cpu/alignment instead.
*/
static int __init alignment_init(void)
{
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *res;
res = proc_create("cpu/alignment", S_IWUSR | S_IRUGO, NULL,
&alignment_proc_fops);
if (!res)
return -ENOMEM;
#endif
if (cpu_is_v6_unaligned()) {
set_cr(__clear_cr(CR_A));
ai_usermode = safe_usermode(ai_usermode, false);
}
cr_no_alignment = get_cr() & ~CR_A;
hook_fault_code(FAULT_CODE_ALIGNMENT, do_alignment, SIGBUS, BUS_ADRALN,
"alignment exception");
/*
* ARMv6K and ARMv7 use fault status 3 (0b00011) as Access Flag section
* fault, not as alignment error.
*
* TODO: handle ARMv6K properly. Runtime check for 'K' extension is
* needed.
*/
if (cpu_architecture() <= CPU_ARCH_ARMv6) {
hook_fault_code(3, do_alignment, SIGBUS, BUS_ADRALN,
"alignment exception");
}
return 0;
}
fs_initcall(alignment_init);
|
242094.c |
#include "f2c-bridge.h"
#include "blas_enum.h"
void BLAS_cge_sum_mv_s_c_x(enum blas_order_type order, int m, int n,
const void *alpha, const float *a, int lda,
const void *x, int incx,
const void *beta, const float *b, int ldb,
void *y, int incy, enum blas_prec_type prec);
extern void FC_FUNC_(blas_cge_sum_mv_s_c_x, BLAS_CGE_SUM_MV_S_C_X)
(int *m, int *n, const void *alpha, const float *a, int *lda, const void *x, int *incx, const void *beta, const float *b, int *ldb, void *y, int *incy, int *prec)
{
BLAS_cge_sum_mv_s_c_x(blas_colmajor, *m, *n,
alpha, a, *lda,
x, *incx,
beta, b, *ldb,
y, *incy, (enum blas_prec_type)*prec);
}
|
839529.c | #include "vint.h"
#include "vtype.h"
PG_FUNCTION_INFO_V1(vint8inc_any);
PG_FUNCTION_INFO_V1(vint4_sum);
PG_FUNCTION_INFO_V1(vint8inc);
Datum vint8inc_any(PG_FUNCTION_ARGS)
{
int64 result;
int64 arg;
int i;
char **entries;
vtype *batch;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
arg = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
result = arg;
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result++;
}
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
arg = DatumGetInt64(*transVal);
result = arg + 1;
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
Datum
vint4_sum(PG_FUNCTION_ARGS)
{
char **entries;
vtype *batch;
int i;
int64 result;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
#if 0
if (PG_ARGISNULL(0))
{
/* No non-null input seen so far... */
if (PG_ARGISNULL(1))
PG_RETURN_NULL(); /* still no non-null */
/* This is the first non-null input. */
newval = (int64) PG_GETARG_INT32(1);
PG_RETURN_INT64(newval);
}
#endif
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
result = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result += DatumGetInt32(batch->values[i]);
}
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
result = DatumGetInt64(*transVal);
result += DatumGetInt32(batch->values[i]);
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
Datum vint8inc(PG_FUNCTION_ARGS)
{
int64 result;
int64 arg;
int i;
char **entries;
vtype *batch;
Datum *transVal;
int32 groupOffset = PG_GETARG_INT32(1);
if (groupOffset < 0)
{
/* Not called as an aggregate, so just do it the dumb way */
result = arg = PG_GETARG_INT64(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
result++;
}
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
PG_RETURN_INT64(result);
}
entries = (char **)PG_GETARG_POINTER(0);
batch = (vtype *) PG_GETARG_POINTER(2);
for (i = 0; i < BATCHSIZE; i++)
{
if (batch->skipref[i])
continue;
transVal = (Datum *)(entries[i] + groupOffset);
arg = DatumGetInt64(*transVal);
result = arg + 1;
/* Overflow check */
if (result < 0 && arg > 0)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range")));
*transVal = Int64GetDatum(result);
}
PG_RETURN_INT64(0);
}
|
503913.c | #include <azureiot/iothub_device_client_ll.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <azureiot/iothub_client_core_common.h>
#include <azureiot/iothub_client_options.h>
#include <azureiot/iothubtransportmqtt.h>
#include <azureiot/iothub.h>
#include <applibs/log.h>
#include "azure_iot_utilities.h"
#include "build_options.h"
#include "connection_strings.h"
// Refer to https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-device-sdk-c-intro for more
// information on Azure IoT SDK for C
//
// String containing Hostname, Device Id & Device Key in the format:
// "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
// see information on iothub-explorer at http://aka.ms/iothubgetstartedVSCS
//
#include "connection_strings.h"
static const char connectionString[] = MY_CONNECTION_STRING;
/// <summary>
/// Maximum amount of time to attempt reconnection when the connection to the IoT Hub drops.
/// </summary>
/// <remarks>Time expressed in seconds. A value of 0 means to retry forever.</remarks>
static const size_t retryTimeoutSeconds = 0;
/// <summary>
/// Function invoked to provide the result of the Device Twin reported properties
/// delivery.
/// </summary>
static DeviceTwinDeliveryConfirmationFnType deviceTwinConfirmationCb = 0;
/// <summary>
/// Function invoked whenever a Direct Method call is received from the IoT Hub.
/// </summary>
static DirectMethodCallFnType directMethodCallCb = 0;
/// <summary>
/// Function invoked whenever a Device Twin update is received from the IoT Hub.
/// </summary>
static TwinUpdateFnType twinUpdateCb = 0;
/// <summary>
/// Function invoked whenever the connection status to the IoT Hub changes.
/// </summary>
static ConnectionStatusFnType hubConnectionStatusCb = 0;
/// <summary>
/// Function invoked whenever a message is received from the IoT Hub.
/// </summary>
static MessageReceivedFnType messageReceivedCb = 0;
/// <summary>
/// Function invoked to report the delivery confirmation of a message sent to the IoT
/// Hub.
/// </summary>
static MessageDeliveryConfirmationFnType messageDeliveryConfirmationCb = 0;
/// <summary>
/// The handle to the IoT Hub client used for communication with the hub.
/// </summary>
IOTHUB_DEVICE_CLIENT_LL_HANDLE iothubClientHandle = NULL;
/// <summary>
/// Used to set the keepalive period over MQTT to 20 seconds.
/// </summary>
static int keepalivePeriodSeconds = 20;
/// <summary>
/// Set of bundle of root certificate authorities.
/// </summary>
static const char azureIoTCertificatesX[] =
/* DigiCert Baltimore Root */
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\r\n"
"RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\r\n"
"VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\r\n"
"DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\r\n"
"ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\r\n"
"VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\r\n"
"mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\r\n"
"IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\r\n"
"mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\r\n"
"XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\r\n"
"dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\r\n"
"jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\r\n"
"BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\r\n"
"DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\r\n"
"9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\r\n"
"jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\r\n"
"Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\r\n"
"ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\r\n"
"R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\r\n"
"-----END CERTIFICATE-----\r\n"
/* DigiCert Global Root CA */
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\r\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\r\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\r\n"
"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\r\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\r\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\r\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\r\n"
"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\r\n"
"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\r\n"
"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\r\n"
"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\r\n"
"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\r\n"
"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\r\n"
"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\r\n"
"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\r\n"
"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\r\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\r\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\r\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\r\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\r\n"
"-----END CERTIFICATE-----\r\n"
/* D-TRUST Root Class 3 CA 2 2009 */
"-----BEGIN CERTIFICATE-----\r\n"
"MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF\r\n"
"MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD\r\n"
"bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha\r\n"
"ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM\r\n"
"HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB\r\n"
"BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03\r\n"
"UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42\r\n"
"tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R\r\n"
"ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM\r\n"
"lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp\r\n"
"/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G\r\n"
"A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G\r\n"
"A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj\r\n"
"dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy\r\n"
"MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl\r\n"
"cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js\r\n"
"L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL\r\n"
"BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni\r\n"
"acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0\r\n"
"o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K\r\n"
"zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8\r\n"
"PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y\r\n"
"Johw1+qRzT65ysCQblrGXnRl11z+o+I=\r\n"
"-----END CERTIFICATE-----\r\n";
// Forward declarations.
static void sendMessageCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *context);
static IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback(IOTHUB_MESSAGE_HANDLE message,
void *context);
static void twinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad,
size_t size, void *userContextCallback);
static int directMethodCallback(const char *methodName, const unsigned char *payload, size_t size,
unsigned char **response, size_t *response_size,
void *userContextCallback);
static void hubConnectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS result,
IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason,
void *userContextCallback);
#if (defined(IOT_CENTRAL_APPLICATION) || defined(IOT_HUB_APPLICATION))
#define MAXS_SIZE 512
// Verify that the connection string is not too long
_Static_assert(sizeof(connectionString) <= MAXS_SIZE, "Connection string too long");
// Verify tthat the connection string is defined
_Static_assert(sizeof(connectionString) > 1, "Connection string not defined! Define MY_CONNECTION_STRING in connection_strings.h");
#endif
/// <summary>
/// Converts the IoT Hub connection status reason to a string.
/// </summary>
static const char *getReasonString(IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason)
{
static char *reasonString = "unknown reason";
switch (reason) {
case IOTHUB_CLIENT_CONNECTION_EXPIRED_SAS_TOKEN:
reasonString = "IOTHUB_CLIENT_CONNECTION_EXPIRED_SAS_TOKEN";
break;
case IOTHUB_CLIENT_CONNECTION_DEVICE_DISABLED:
reasonString = "IOTHUB_CLIENT_CONNECTION_DEVICE_DISABLED";
break;
case IOTHUB_CLIENT_CONNECTION_BAD_CREDENTIAL:
reasonString = "IOTHUB_CLIENT_CONNECTION_BAD_CREDENTIAL";
break;
case IOTHUB_CLIENT_CONNECTION_RETRY_EXPIRED:
reasonString = "IOTHUB_CLIENT_CONNECTION_RETRY_EXPIRED";
break;
case IOTHUB_CLIENT_CONNECTION_NO_NETWORK:
reasonString = "IOTHUB_CLIENT_CONNECTION_NO_NETWORK";
break;
case IOTHUB_CLIENT_CONNECTION_COMMUNICATION_ERROR:
reasonString = "IOTHUB_CLIENT_CONNECTION_COMMUNICATION_ERROR";
break;
case IOTHUB_CLIENT_CONNECTION_OK:
reasonString = "IOTHUB_CLIENT_CONNECTION_OK";
break;
}
return reasonString;
}
/// <summary>
/// Log a message related to the Azure IoT Hub client with
/// prefix [Azure IoT Hub client]:"
/// </summary>
/// <param name="message">The format string containing the error to output along with
/// placeholders</param>
/// <param name="...">The list of arguments to populate the format string placeholders</param>
void LogMessage(char *message, ...)
{
va_list args;
va_start(args, message);
Log_Debug("[Azure IoT Hub client] ");
Log_DebugVarArgs(message, args);
va_end(args);
}
/// <summary>
/// Sets up the client in order to establish the communication channel to Azure IoT Hub.
///
/// The client is created by using the IoT Hub connection string that is provisioned
/// on the device or hardcoded into the source. The client is setup with the following
/// options:
/// - IOTHUB_CLIENT_RETRY_INTERVAL retry policy which, when the network connection
/// to the IoT Hub drops, attempts a reconnection each 5 seconds for a period of time
/// of 5000 seconds before giving up;
/// - MQTT procotol 'keepalive' value of 20 seconds; when no PINGRESP is received after
/// 20 seconds, the connection is believed to be down and the retry policy kicks in;
/// </summary>
/// <returns>'true' if the client has been properly set up. 'false' when a fatal error occurred
/// while setting up the client.</returns>
/// <remarks>This function is a no-op when the client has already been set up, i.e. this
/// function has already completed successfully.</remarks>
bool AzureIoT_SetupClient(void)
{
if (iothubClientHandle != NULL) {
return true;
}
iothubClientHandle =
IoTHubDeviceClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
if (iothubClientHandle == NULL) {
return false;
}
if (IoTHubDeviceClient_LL_SetOption(iothubClientHandle, "TrustedCerts",
azureIoTCertificatesX) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failure to set option \"TrustedCerts\"\n");
return false;
}
if (IoTHubDeviceClient_LL_SetOption(iothubClientHandle, OPTION_KEEP_ALIVE,
&keepalivePeriodSeconds) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failure setting option \"%s\"\n", OPTION_KEEP_ALIVE);
return false;
}
// Set callbacks for Message, MethodCall and Device Twin features.
IoTHubDeviceClient_LL_SetMessageCallback(iothubClientHandle, receiveMessageCallback, NULL);
IoTHubDeviceClient_LL_SetDeviceMethodCallback(iothubClientHandle, directMethodCallback, NULL);
IoTHubDeviceClient_LL_SetDeviceTwinCallback(iothubClientHandle, twinCallback, NULL);
// Set callbacks for connection status related events.
if (IoTHubDeviceClient_LL_SetConnectionStatusCallback(
iothubClientHandle, hubConnectionStatusCallback, NULL) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failure setting callback\n");
return false;
}
// Set retry policy for the connection to the IoT Hub.
if (IoTHubDeviceClient_LL_SetRetryPolicy(iothubClientHandle, IOTHUB_CLIENT_RETRY_INTERVAL,
retryTimeoutSeconds) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failure setting retry policy\n");
return false;
}
return true;
}
/// <summary>
/// Destroys the Azure IoT Hub client.
/// </summary>
void AzureIoT_DestroyClient(void)
{
if (iothubClientHandle != NULL) {
IoTHubDeviceClient_LL_Destroy(iothubClientHandle);
iothubClientHandle = NULL;
}
}
/// <summary>
/// Periodically outputs a provided format string with a variable number of arguments.
/// </summary>
/// <param name="lastInvokedTime">Pointer where to store the 'last time this function has been
/// invoked' information</param>
/// <param name="periodInSeconds">The desired period of the output</param>
/// <param name="format">The format string</param>
static void PeriodicLogVarArgs(time_t *lastInvokedTime, time_t periodInSeconds, const char *format,
...)
{
struct timespec ts;
int timeOk = timespec_get(&ts, TIME_UTC);
if (!timeOk) {
return;
}
if (ts.tv_sec > *lastInvokedTime + periodInSeconds) {
va_list args;
va_start(args, format);
Log_Debug("[Azure IoT Hub client] ");
Log_DebugVarArgs(format, args);
va_end(args);
*lastInvokedTime = ts.tv_sec;
}
}
/// <summary>
/// Keeps IoT Hub Client alive by exchanging data with the Azure IoT Hub.
/// </summary>
/// <remarks>
/// This function must to be invoked periodically so that the Azure IoT Hub
/// SDK can accomplish its work (e.g. sending messages, invocation of callbacks, reconnection
/// attempts, and so forth).
/// </remarks>
void AzureIoT_DoPeriodicTasks(void)
{
static time_t lastTimeLogged = 0;
PeriodicLogVarArgs(&lastTimeLogged, 5, "INFO: %s calls in progress...\n", __func__);
// DoWork - send some of the buffered events to the IoT Hub, and receive some of the buffered
// events from the IoT Hub.
IoTHubDeviceClient_LL_DoWork(iothubClientHandle);
}
/// <summary>
/// Creates and enqueues a message to be delivered the IoT Hub. The message is not actually sent
/// immediately, but it is sent on the next invocation of AzureIoT_DoPeriodicTasks().
/// </summary>
/// <param name="messagePayload">The payload of the message to send.</param>
void AzureIoT_SendMessage(const char *messagePayload)
{
if (iothubClientHandle == NULL) {
LogMessage("WARNING: IoT Hub client not initialized\n");
return;
}
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromString(messagePayload);
if (messageHandle == 0) {
LogMessage("WARNING: unable to create a new IoTHubMessage\n");
return;
}
if (IoTHubDeviceClient_LL_SendEventAsync(iothubClientHandle, messageHandle, sendMessageCallback,
/*&callback_param*/ 0) != IOTHUB_CLIENT_OK) {
LogMessage("WARNING: failed to hand over the message to IoTHubClient\n");
} else {
LogMessage("INFO: IoTHubClient accepted the message for delivery\n");
}
IoTHubMessage_Destroy(messageHandle);
}
/// <summary>
/// Sets the function to be invoked whenever the Device Twin properties have been delivered to
/// the IoT Hub.
/// </summary>
/// <param name="callback">The function pointer to the callback function.</param>
void AzureIoT_SetDeviceTwinDeliveryConfirmationCallback(
DeviceTwinDeliveryConfirmationFnType callback)
{
deviceTwinConfirmationCb = callback;
}
/// <summary>
/// Callback invoked when the Device Twin reported properties are accepted by IoT Hub.
/// </summary>
static void reportStatusCallback(int result, void *context)
{
LogMessage("INFO: Device Twin reported properties update result: HTTP status code %d\n",
result);
if (deviceTwinConfirmationCb)
deviceTwinConfirmationCb(result);
}
/// <summary>
/// Creates and enqueues a report containing the name and value pair of a Device Twin reported
/// property.
/// The report is not actually sent immediately, but it is sent on the next invocation of
/// AzureIoT_DoPeriodicTasks().
/// </summary>
void AzureIoT_TwinReportState(const char *propertyName, size_t propertyValue)
{
if (iothubClientHandle == NULL) {
LogMessage("ERROR: client not initialized\n");
return;
}
char *reportedPropertiesString = NULL;
JSON_Value *reportedPropertiesRootJson = json_value_init_object();
if (reportedPropertiesRootJson == NULL) {
LogMessage("ERROR: could not create the JSON_Value for Device Twin reporting.\n");
return;
}
JSON_Object *reportedPropertiesJson = json_value_get_object(reportedPropertiesRootJson);
if (reportedPropertiesJson == NULL) {
LogMessage("ERROR: could not get the JSON_Object for Device Twin reporting.\n");
goto cleanup;
}
if (JSONSuccess !=
json_object_set_number(reportedPropertiesJson, propertyName, propertyValue)) {
LogMessage("ERROR: could not set the property value for Device Twin reporting.\n");
goto cleanup;
}
reportedPropertiesString = json_serialize_to_string(reportedPropertiesRootJson);
if (reportedPropertiesString == NULL) {
LogMessage(
"ERROR: could not serialize the JSON payload to string for Device "
"Twin reporting.\n");
goto cleanup;
}
if (IoTHubDeviceClient_LL_SendReportedState(
iothubClientHandle, (unsigned char *)reportedPropertiesString,
strlen(reportedPropertiesString), reportStatusCallback, 0) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failed to set reported property '%s'.\n", propertyName);
} else {
LogMessage("INFO: Set reported property '%s' to value %d.\n", propertyName, propertyValue);
}
cleanup:
if (reportedPropertiesRootJson != NULL) {
json_value_free(reportedPropertiesRootJson);
}
if (reportedPropertiesString != NULL) {
json_free_serialized_string(reportedPropertiesString);
}
}
/// <summary>
/// Sets a callback function invoked whenever a message is received from IoT Hub.
/// </summary>
/// <param name="callback">The callback function invoked when a message is received</param>
void AzureIoT_SetMessageReceivedCallback(MessageReceivedFnType callback)
{
messageReceivedCb = callback;
}
/// <summary>
/// Sets the function to be invoked whenever the message to the Iot Hub has been delivered.
/// </summary>
/// <param name="callback">The function pointer to the callback function.</param>
void AzureIoT_SetMessageConfirmationCallback(MessageDeliveryConfirmationFnType callback)
{
messageDeliveryConfirmationCb = callback;
}
/// <summary>
/// Function invoked when the message delivery confirmation is being reported.
/// </summary>
/// <param name="result">Message delivery status</param>
/// <param name="context">User specified context</param>
static void sendMessageCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *context)
{
LogMessage("INFO: Message received by IoT Hub. Result is: %d\n", result);
if (messageDeliveryConfirmationCb) {
messageDeliveryConfirmationCb(result == IOTHUB_CLIENT_CONFIRMATION_OK);
}
}
/// <summary>
/// Callback function invoked when a message is received from IoT Hub.
/// </summary>
/// <param name="message">The handle of the received message</param>
/// <param name="context">The user context specified at IoTHubDeviceClient_LL_SetMessageCallback()
/// invocation time</param>
/// <returns>Return value to indicates the message procession status (i.e. accepted, rejected,
/// abandoned)</returns>
static IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback(IOTHUB_MESSAGE_HANDLE message,
void *context)
{
const unsigned char *buffer = NULL;
size_t size = 0;
if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) {
LogMessage("WARNING: failure performing IoTHubMessage_GetByteArray\n");
return IOTHUBMESSAGE_REJECTED;
}
// 'buffer' is not zero terminated.
unsigned char *str_msg = (unsigned char *)malloc(size + 1);
if (str_msg == NULL) {
LogMessage("ERROR: could not allocate buffer for incoming message\n");
abort();
}
memcpy(str_msg, buffer, size);
str_msg[size] = '\0';
if (messageReceivedCb != 0) {
messageReceivedCb(str_msg);
} else {
LogMessage("WARNING: no user callback set up for event 'message received from IoT Hub'\n");
}
LogMessage("INFO: Received message '%s' from IoT Hub\n", str_msg);
free(str_msg);
return IOTHUBMESSAGE_ACCEPTED;
}
/// <summary>
/// Sets the function to be invoked whenever a Direct Method call from the IoT Hub is received.
/// </summary>
/// <param name="callback">The callback function invoked when a Direct Method call is
/// received</param>
void AzureIoT_SetDirectMethodCallback(DirectMethodCallFnType callback)
{
directMethodCallCb = callback;
}
/// <summary>
/// Sets the function callback invoked whenever a Device Twin update from the IoT Hub is
/// received.
/// </summary>
/// <param name="callback">The callback function invoked when a Device Twin update is
/// received</param>
void AzureIoT_SetDeviceTwinUpdateCallback(TwinUpdateFnType callback)
{
twinUpdateCb = callback;
}
/// <summary>
/// Callback when direct method is called.
/// </summary>
static int directMethodCallback(const char *methodName, const unsigned char *payload, size_t size,
unsigned char **response, size_t *responseSize,
void *userContextCallback)
{
LogMessage("INFO: Trying to invoke method %s\n", methodName);
int result = 404;
if (directMethodCallCb != NULL) {
char *responseFromCallback = NULL;
size_t responseFromCallbackSize = 0;
result = directMethodCallCb(methodName, payload, size, &responseFromCallback,
&responseFromCallbackSize);
*responseSize = responseFromCallbackSize;
*response = responseFromCallback;
} else {
LogMessage("INFO: No method '%s' found, HttpStatus=%d\n", methodName, result);
static const char methodNotFound[] = "\"No method found\"";
*responseSize = strlen(methodNotFound);
*response = (unsigned char *)malloc(*responseSize);
if (*response != NULL) {
strncpy((char *)(*response), methodNotFound, *responseSize);
} else {
LogMessage("ERROR: Cannot create response message for method call.\n");
abort();
}
}
return result;
}
/// <summary>
/// Callback invoked when a Device Twin update is received from IoT Hub.
/// </summary>
static void twinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad,
size_t payLoadSize, void *userContextCallback)
{
size_t nullTerminatedJsonSize = payLoadSize + 1;
char *nullTerminatedJsonString = (char *)malloc(nullTerminatedJsonSize);
if (nullTerminatedJsonString == NULL) {
LogMessage("ERROR: Could not allocate buffer for twin update payload.\n");
abort();
}
// Copy the provided buffer to a null terminated buffer.
memcpy(nullTerminatedJsonString, payLoad, payLoadSize);
// Add the null terminator at the end.
nullTerminatedJsonString[nullTerminatedJsonSize - 1] = 0;
JSON_Value *rootProperties = NULL;
rootProperties = json_parse_string(nullTerminatedJsonString);
if (rootProperties == NULL) {
LogMessage("WARNING: Cannot parse the string as JSON content.\n");
goto cleanup;
}
JSON_Object *rootObject = json_value_get_object(rootProperties);
JSON_Object *desiredProperties = json_object_dotget_object(rootObject, "desired");
if (desiredProperties == NULL) {
desiredProperties = rootObject;
}
// Call the provided Twin Device callback if any.
if (twinUpdateCb != NULL) {
twinUpdateCb(desiredProperties);
}
cleanup:
// Release the allocated memory.
json_value_free(rootProperties);
free(nullTerminatedJsonString);
}
/// <summary>
/// Sets the function to be invoked whenever the connection status to the IoT Hub changes.
/// </summary>
/// <param name="callback">The callback function invoked when Azure IoT Hub network connection
/// status changes.</param>
void AzureIoT_SetConnectionStatusCallback(ConnectionStatusFnType callback)
{
hubConnectionStatusCb = callback;
}
/// <summary>
/// Callback function invoked whenever the connection status to IoT Hub changes.
/// </summary>
/// <param name="result">Current authentication status</param>
/// <param name="reason">result's specific reason</param>
/// <param name="userContextCallback">User specified context</param>
static void hubConnectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS result,
IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason,
void *userContextCallback)
{
bool authenticated = (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED);
if (hubConnectionStatusCb) {
hubConnectionStatusCb(result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED);
}
const char *reasonString = getReasonString(reason);
if (!authenticated) {
LogMessage("INFO: IoT Hub connection is down (%s), retrying connection in 5 seconds...\n",
reasonString);
} else {
LogMessage("INFO: connection to the IoT Hub has been established (%s).\n", reasonString);
}
}
/// <summary>
/// Initializes the Azure IoT Hub SDK.
/// </summary>
/// <return>'true' if initialization has been successful.</param>
bool AzureIoT_Initialize(void)
{
if (IoTHub_Init() != 0) {
LogMessage("ERROR: failed initializing platform.\n");
return false;
}
return true;
}
/// <summary>
/// Deinitializes the Azure IoT Hub SDK.
/// </summary>
void AzureIoT_Deinitialize(void)
{
IoTHub_Deinit();
}
/// <summary>
/// Creates and enqueues reported properties state using a prepared json string.
/// The report is not actually sent immediately, but it is sent on the next
/// invocation of AzureIoT_DoPeriodicTasks().
/// </summary>
void AzureIoT_TwinReportStateJson(
char *reportedPropertiesString,
size_t reportedPropertiesSize)
{
if (iothubClientHandle == NULL) {
LogMessage("ERROR: client not initialized\n");
}
else {
if (reportedPropertiesString != NULL) {
if (IoTHubDeviceClient_LL_SendReportedState(iothubClientHandle,
(unsigned char *)reportedPropertiesString, reportedPropertiesSize,
reportStatusCallback, 0) != IOTHUB_CLIENT_OK) {
LogMessage("ERROR: failed to set reported state as '%s'.\n",
reportedPropertiesString);
}
else {
LogMessage("INFO: Reported state as '%s'.\n", reportedPropertiesString);
}
}
else {
LogMessage("ERROR: no JSON string for Device Twin reporting.\n");
}
}
} |
74963.c | /*
* Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2015 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2008 Sun Microsystems, Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "coll_tuned.h"
#include <stdio.h>
#include "mpi.h"
#include "ompi/communicator/communicator.h"
#include "ompi/mca/coll/coll.h"
#include "ompi/mca/coll/base/base.h"
#include "ompi/mca/coll/base/coll_base_topo.h"
#include "coll_tuned.h"
#include "coll_tuned_dynamic_rules.h"
#include "coll_tuned_dynamic_file.h"
static int tuned_module_enable(mca_coll_base_module_t *module,
struct ompi_communicator_t *comm);
/*
* Initial query function that is invoked during MPI_INIT, allowing
* this component to disqualify itself if it doesn't support the
* required level of thread support.
*/
int ompi_coll_tuned_init_query(bool enable_progress_threads,
bool enable_mpi_threads)
{
return OMPI_SUCCESS;
}
/*
* Invoked when there's a new communicator that has been created.
* Look at the communicator and decide which set of functions and
* priority we want to return.
*/
mca_coll_base_module_t *
ompi_coll_tuned_comm_query(struct ompi_communicator_t *comm, int *priority)
{
mca_coll_tuned_module_t *tuned_module;
OPAL_OUTPUT((ompi_coll_tuned_stream, "coll:tuned:module_tuned query called"));
/**
* No support for inter-communicator yet.
*/
if (OMPI_COMM_IS_INTER(comm)) {
*priority = 0;
return NULL;
}
/**
* If it is inter-communicator and size is less than 2 we have specialized modules
* to handle the intra collective communications.
*/
if (OMPI_COMM_IS_INTRA(comm) && ompi_comm_size(comm) < 2) {
*priority = 0;
return NULL;
}
tuned_module = OBJ_NEW(mca_coll_tuned_module_t);
if (NULL == tuned_module) return NULL;
*priority = ompi_coll_tuned_priority;
/*
* Choose whether to use [intra|inter] decision functions
* and if using fixed OR dynamic rule sets.
* Right now you cannot mix them, maybe later on it can be changed
* but this would probably add an extra if and funct call to the path
*/
tuned_module->super.coll_module_enable = tuned_module_enable;
tuned_module->super.ft_event = mca_coll_tuned_ft_event;
/* By default stick with the fied version of the tuned collectives. Later on,
* when the module get enabled, set the correct version based on the availability
* of the dynamic rules.
*/
tuned_module->super.coll_allgather = ompi_coll_tuned_allgather_intra_dec_fixed;
tuned_module->super.coll_allgatherv = ompi_coll_tuned_allgatherv_intra_dec_fixed;
tuned_module->super.coll_allreduce = ompi_coll_tuned_allreduce_intra_dec_fixed;
tuned_module->super.coll_alltoall = ompi_coll_tuned_alltoall_intra_dec_fixed;
tuned_module->super.coll_alltoallv = ompi_coll_tuned_alltoallv_intra_dec_fixed;
tuned_module->super.coll_alltoallw = NULL;
tuned_module->super.coll_barrier = ompi_coll_tuned_barrier_intra_dec_fixed;
tuned_module->super.coll_bcast = ompi_coll_tuned_bcast_intra_dec_fixed;
tuned_module->super.coll_exscan = NULL;
tuned_module->super.coll_gather = ompi_coll_tuned_gather_intra_dec_fixed;
tuned_module->super.coll_gatherv = NULL;
tuned_module->super.coll_reduce = ompi_coll_tuned_reduce_intra_dec_fixed;
tuned_module->super.coll_reduce_scatter = ompi_coll_tuned_reduce_scatter_intra_dec_fixed;
tuned_module->super.coll_scan = NULL;
tuned_module->super.coll_scatter = ompi_coll_tuned_scatter_intra_dec_fixed;
tuned_module->super.coll_scatterv = NULL;
return &(tuned_module->super);
}
/* We put all routines that handle the MCA user forced algorithm and parameter choices here */
/* recheck the setting of forced, called on module create (i.e. for each new comm) */
static int
ompi_coll_tuned_forced_getvalues( enum COLLTYPE type,
coll_tuned_force_algorithm_params_t *forced_values )
{
coll_tuned_force_algorithm_mca_param_indices_t* mca_params;
const int *tmp;
mca_params = &(ompi_coll_tuned_forced_params[type]);
/**
* Set the selected algorithm to 0 by default. Later on we can check this against 0
* to see if it was setted explicitly (if we suppose that setting it to 0 enable the
* default behavior) or not.
*/
mca_base_var_get_value(mca_params->algorithm_param_index, &tmp, NULL, NULL);
forced_values->algorithm = tmp ? tmp[0] : 0;
if( BARRIER != type ) {
mca_base_var_get_value(mca_params->segsize_param_index, &tmp, NULL, NULL);
if (tmp) forced_values->segsize = tmp[0];
mca_base_var_get_value(mca_params->tree_fanout_param_index, &tmp, NULL, NULL);
if (tmp) forced_values->tree_fanout = tmp[0];
mca_base_var_get_value(mca_params->chain_fanout_param_index, &tmp, NULL, NULL);
if (tmp) forced_values->chain_fanout = tmp[0];
mca_base_var_get_value(mca_params->max_requests_param_index, &tmp, NULL, NULL);
if (tmp) forced_values->max_requests = tmp[0];
}
return (MPI_SUCCESS);
}
#define COLL_TUNED_EXECUTE_IF_DYNAMIC(TMOD, TYPE, EXECUTE) \
{ \
int need_dynamic_decision = 0; \
ompi_coll_tuned_forced_getvalues( (TYPE), &((TMOD)->user_forced[(TYPE)]) ); \
(TMOD)->com_rules[(TYPE)] = NULL; \
if( 0 != (TMOD)->user_forced[(TYPE)].algorithm ) { \
need_dynamic_decision = 1; \
EXECUTE; \
} \
if( NULL != mca_coll_tuned_component.all_base_rules ) { \
(TMOD)->com_rules[(TYPE)] \
= ompi_coll_tuned_get_com_rule_ptr( mca_coll_tuned_component.all_base_rules, \
(TYPE), size ); \
if( NULL != (TMOD)->com_rules[(TYPE)] ) { \
need_dynamic_decision = 1; \
} \
} \
if( 1 == need_dynamic_decision ) { \
OPAL_OUTPUT((ompi_coll_tuned_stream,"coll:tuned: enable dynamic selection for "#TYPE)); \
ompi_coll_tuned_use_dynamic_rules = true; \
EXECUTE; \
} \
}
/*
* Init module on the communicator
*/
static int
tuned_module_enable( mca_coll_base_module_t *module,
struct ompi_communicator_t *comm )
{
int size;
mca_coll_tuned_module_t *tuned_module = (mca_coll_tuned_module_t *) module;
mca_coll_base_comm_t *data = NULL;
OPAL_OUTPUT((ompi_coll_tuned_stream,"coll:tuned:module_init called."));
/* Allocate the data that hangs off the communicator */
if (OMPI_COMM_IS_INTER(comm)) {
size = ompi_comm_remote_size(comm);
} else {
size = ompi_comm_size(comm);
}
/**
* we still malloc data as it is used by the TUNED modules
* if we don't allocate it and fall back to a BASIC module routine then confuses debuggers
* we place any special info after the default data
*
* BUT on very large systems we might not be able to allocate all this memory so
* we do check a MCA parameter to see if if we should allocate this memory
*
* The default is set very high
*/
/* if we within the memory/size limit, allow preallocated data */
data = OBJ_NEW(mca_coll_base_comm_t);
if (NULL == data) {
return OMPI_ERROR;
}
if (ompi_coll_tuned_use_dynamic_rules) {
OPAL_OUTPUT((ompi_coll_tuned_stream,"coll:tuned:module_init MCW & Dynamic"));
/**
* Reset it to 0, it will be enabled again if we discover any need for dynamic decisions.
*/
ompi_coll_tuned_use_dynamic_rules = false;
/**
* next dynamic state, recheck all forced rules as well
* warning, we should check to make sure this is really an INTRA comm here...
*/
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLGATHER,
tuned_module->super.coll_allgather = ompi_coll_tuned_allgather_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLGATHERV,
tuned_module->super.coll_allgatherv = ompi_coll_tuned_allgatherv_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLREDUCE,
tuned_module->super.coll_allreduce = ompi_coll_tuned_allreduce_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLTOALL,
tuned_module->super.coll_alltoall = ompi_coll_tuned_alltoall_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLTOALLV,
tuned_module->super.coll_alltoallv = ompi_coll_tuned_alltoallv_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, ALLTOALLW,
tuned_module->super.coll_alltoallw = NULL);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, BARRIER,
tuned_module->super.coll_barrier = ompi_coll_tuned_barrier_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, BCAST,
tuned_module->super.coll_bcast = ompi_coll_tuned_bcast_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, EXSCAN,
tuned_module->super.coll_exscan = NULL);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, GATHER,
tuned_module->super.coll_gather = ompi_coll_tuned_gather_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, GATHERV,
tuned_module->super.coll_gatherv = NULL);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, REDUCE,
tuned_module->super.coll_reduce = ompi_coll_tuned_reduce_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, REDUCESCATTER,
tuned_module->super.coll_reduce_scatter = ompi_coll_tuned_reduce_scatter_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, SCAN,
tuned_module->super.coll_scan = NULL);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, SCATTER,
tuned_module->super.coll_scatter = ompi_coll_tuned_scatter_intra_dec_dynamic);
COLL_TUNED_EXECUTE_IF_DYNAMIC(tuned_module, SCATTERV,
tuned_module->super.coll_scatterv = NULL);
if( false == ompi_coll_tuned_use_dynamic_rules ) {
/* no real need for dynamic decisions */
OPAL_OUTPUT((ompi_coll_tuned_stream, "coll:tuned:module_enable switch back to fixed"
" decision by lack of dynamic rules"));
}
}
/* general n fan out tree */
data->cached_ntree = NULL;
/* binary tree */
data->cached_bintree = NULL;
/* binomial tree */
data->cached_bmtree = NULL;
/* binomial tree */
data->cached_in_order_bmtree = NULL;
/* chains (fanout followed by pipelines) */
data->cached_chain = NULL;
/* standard pipeline */
data->cached_pipeline = NULL;
/* in-order binary tree */
data->cached_in_order_bintree = NULL;
/* All done */
tuned_module->super.base_data = data;
OPAL_OUTPUT((ompi_coll_tuned_stream,"coll:tuned:module_init Tuned is in use"));
return OMPI_SUCCESS;
}
int mca_coll_tuned_ft_event(int state) {
if(OPAL_CRS_CHECKPOINT == state) {
;
}
else if(OPAL_CRS_CONTINUE == state) {
;
}
else if(OPAL_CRS_RESTART == state) {
;
}
else if(OPAL_CRS_TERM == state ) {
;
}
else {
;
}
return OMPI_SUCCESS;
}
|
372563.c | /* I S I Z E . C
* BRL-CAD
*
* Copyright (c) 2008-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 file; see the file named COPYING for more
* information.
*/
/** @file libged/isize.c
*
* The isize command.
*
*/
#include "common.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "./ged_private.h"
int
ged_isize(struct ged *gedp, int argc, const char *argv[])
{
GED_CHECK_DATABASE_OPEN(gedp, GED_ERROR);
GED_CHECK_VIEW(gedp, GED_ERROR);
GED_CHECK_ARGC_GT_0(gedp, argc, GED_ERROR);
/* initialize result */
bu_vls_trunc(gedp->ged_result_str, 0);
/* get the isize (i.e. inverse view size) */
if (argc == 1) {
bu_vls_printf(gedp->ged_result_str, "%g",
gedp->ged_gvp->gv_isize * gedp->ged_wdbp->dbip->dbi_base2local);
return GED_OK;
}
bu_vls_printf(gedp->ged_result_str, "Usage: %s", argv[0]);
return GED_ERROR;
}
/*
* Local Variables:
* tab-width: 8
* mode: C
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
|
960914.c | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Modified for iPXE by Scott K Logan <[email protected]> July 2011
* Original from Linux kernel 3.0.1
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <ipxe/pci.h>
#include "ath9k.h"
static struct pci_device_id ath_pci_id_table[] = {
PCI_ROM(0x168c, 0x0023, "ar5416", "Atheros 5416 PCI", 0), /* PCI */
PCI_ROM(0x168c, 0x0024, "ar5416", "Atheros 5416 PCI-E", 0), /* PCI-E */
PCI_ROM(0x168c, 0x0027, "ar9160", "Atheros 9160 PCI", 0), /* PCI */
PCI_ROM(0x168c, 0x0029, "ar9280", "Atheros 9280 PCI", 0), /* PCI */
PCI_ROM(0x168c, 0x002A, "ar9280", "Atheros 9280 PCI-E", 0), /* PCI-E */
PCI_ROM(0x168c, 0x002B, "ar9285", "Atheros 9285 PCI-E", 0), /* PCI-E */
PCI_ROM(0x168c, 0x002C, "ar2427", "Atheros 2427 PCI-E", 0), /* PCI-E 802.11n bonded out */
PCI_ROM(0x168c, 0x002D, "ar9287", "Atheros 9287 PCI", 0), /* PCI */
PCI_ROM(0x168c, 0x002E, "ar9287", "Atheros 9287 PCI-E", 0), /* PCI-E */
PCI_ROM(0x168c, 0x0030, "ar9300", "Atheros 9300 PCI-E", 0), /* PCI-E AR9300 */
PCI_ROM(0x168c, 0x0032, "ar9485", "Atheros 9485 PCI-E", 0), /* PCI-E AR9485 */
};
/* return bus cachesize in 4B word units */
static void ath_pci_read_cachesize(struct ath_common *common, int *csz)
{
struct ath_softc *sc = (struct ath_softc *) common->priv;
u8 u8tmp;
pci_read_config_byte(sc->pdev, PCI_CACHE_LINE_SIZE, &u8tmp);
*csz = (int)u8tmp;
/*
* This check was put in to avoid "unpleasant" consequences if
* the bootrom has not fully initialized all PCI devices.
* Sometimes the cache line size register is not set
*/
if (*csz == 0)
*csz = DEFAULT_CACHELINE >> 2; /* Use the default size */
}
static int ath_pci_eeprom_read(struct ath_common *common, u32 off, u16 *data)
{
struct ath_hw *ah = (struct ath_hw *) common->ah;
common->ops->read(ah, AR5416_EEPROM_OFFSET +
(off << AR5416_EEPROM_S));
if (!ath9k_hw_wait(ah,
AR_EEPROM_STATUS_DATA,
AR_EEPROM_STATUS_DATA_BUSY |
AR_EEPROM_STATUS_DATA_PROT_ACCESS, 0,
AH_WAIT_TIMEOUT)) {
return 0;
}
*data = MS(common->ops->read(ah, AR_EEPROM_STATUS_DATA),
AR_EEPROM_STATUS_DATA_VAL);
return 1;
}
static void ath_pci_extn_synch_enable(struct ath_common *common)
{
struct ath_softc *sc = (struct ath_softc *) common->priv;
struct pci_device *pdev = sc->pdev;
u8 lnkctl;
pci_read_config_byte(pdev, sc->sc_ah->caps.pcie_lcr_offset, &lnkctl);
lnkctl |= 0x0080;
pci_write_config_byte(pdev, sc->sc_ah->caps.pcie_lcr_offset, lnkctl);
}
static const struct ath_bus_ops ath_pci_bus_ops = {
.ath_bus_type = ATH_PCI,
.read_cachesize = ath_pci_read_cachesize,
.eeprom_read = ath_pci_eeprom_read,
.extn_synch_en = ath_pci_extn_synch_enable,
};
static int ath_pci_probe(struct pci_device *pdev)
{
void *mem;
struct ath_softc *sc;
struct net80211_device *dev;
u8 csz;
u16 subsysid;
u32 val;
int ret = 0;
char hw_name[64];
adjust_pci_device(pdev);
/*
* Cache line size is used to size and align various
* structures used to communicate with the hardware.
*/
pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &csz);
if (csz == 0) {
/*
* Linux 2.4.18 (at least) writes the cache line size
* register as a 16-bit wide register which is wrong.
* We must have this setup properly for rx buffer
* DMA to work so force a reasonable value here if it
* comes up zero.
*/
csz =16;
pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, csz);
}
/*
* The default setting of latency timer yields poor results,
* set it to the value used by other systems. It may be worth
* tweaking this setting more.
*/
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xa8);
/*
* Disable the RETRY_TIMEOUT register (0x41) to keep
* PCI Tx retries from interfering with C3 CPU state.
*/
pci_read_config_dword(pdev, 0x40, &val);
if ((val & 0x0000ff00) != 0)
pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
mem = ioremap(pdev->membase, 0x10000);
if (!mem) {
DBG("ath9K: PCI memory map error\n") ;
ret = -EIO;
goto err_iomap;
}
dev = net80211_alloc(sizeof(struct ath_softc));
if (!dev) {
DBG("ath9k: No memory for net80211_device\n");
ret = -ENOMEM;
goto err_alloc_hw;
}
pci_set_drvdata(pdev, dev);
dev->netdev->dev = (struct device *)pdev;
sc = dev->priv;
sc->dev = dev;
sc->pdev = pdev;
sc->mem = mem;
/* Will be cleared in ath9k_start() */
sc->sc_flags |= SC_OP_INVALID;
sc->irq = pdev->irq;
pci_read_config_word(pdev, PCI_SUBSYSTEM_ID, &subsysid);
ret = ath9k_init_device(pdev->device, sc, subsysid, &ath_pci_bus_ops);
if (ret) {
DBG("ath9k: Failed to initialize device\n");
goto err_init;
}
ath9k_hw_name(sc->sc_ah, hw_name, sizeof(hw_name));
DBG("ath9k: %s mem=0x%lx, irq=%d\n",
hw_name, (unsigned long)mem, pdev->irq);
return 0;
err_init:
net80211_free(dev);
err_alloc_hw:
iounmap(mem);
err_iomap:
return ret;
}
static void ath_pci_remove(struct pci_device *pdev)
{
struct net80211_device *dev = pci_get_drvdata(pdev);
struct ath_softc *sc = dev->priv;
void *mem = sc->mem;
if (!is_ath9k_unloaded)
sc->sc_ah->ah_flags |= AH_UNPLUGGED;
ath9k_deinit_device(sc);
net80211_free(sc->dev);
iounmap(mem);
}
struct pci_driver ath_pci_driver __pci_driver = {
.id_count = ARRAY_SIZE(ath_pci_id_table),
.ids = ath_pci_id_table,
.probe = ath_pci_probe,
.remove = ath_pci_remove,
};
|
355225.c | /*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function dgbequb
* Author: Intel Corporation
* Generated November 2015
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_dgbequb( int matrix_layout, lapack_int m, lapack_int n,
lapack_int kl, lapack_int ku, const double* ab,
lapack_int ldab, double* r, double* c,
double* rowcnd, double* colcnd, double* amax )
{
if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_dgbequb", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
if( LAPACKE_get_nancheck() ) {
/* Optionally check input matrices for NaNs */
if( LAPACKE_dgb_nancheck( matrix_layout, m, n, kl, ku, ab, ldab ) ) {
return -6;
}
}
#endif
return LAPACKE_dgbequb_work( matrix_layout, m, n, kl, ku, ab, ldab, r, c,
rowcnd, colcnd, amax );
}
|
115077.c | /*
* SSL server demonstration program
*
* Copyright (C) 2006-2011, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "polarssl/config.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/certs.h"
#include "polarssl/x509.h"
#include "polarssl/ssl.h"
#include "polarssl/net.h"
#include "polarssl/error.h"
#if defined(POLARSSL_SSL_CACHE_C)
#include "polarssl/ssl_cache.h"
#endif
#define HTTP_RESPONSE \
"HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
"<h2>PolarSSL Test Server</h2>\r\n" \
"<p>Successful connection using: %s</p>\r\n"
#define DEBUG_LEVEL 0
void my_debug( void *ctx, int level, const char *str )
{
if( level < DEBUG_LEVEL )
{
fprintf( (FILE *) ctx, "%s", str );
fflush( (FILE *) ctx );
}
}
#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_CERTS_C) || \
!defined(POLARSSL_ENTROPY_C) || !defined(POLARSSL_SSL_TLS_C) || \
!defined(POLARSSL_SSL_SRV_C) || !defined(POLARSSL_NET_C) || \
!defined(POLARSSL_RSA_C) || !defined(POLARSSL_CTR_DRBG_C)
int main( int argc, char *argv[] )
{
((void) argc);
((void) argv);
printf("POLARSSL_BIGNUM_C and/or POLARSSL_CERTS_C and/or POLARSSL_ENTROPY_C "
"and/or POLARSSL_SSL_TLS_C and/or POLARSSL_SSL_SRV_C and/or "
"POLARSSL_NET_C and/or POLARSSL_RSA_C and/or "
"POLARSSL_CTR_DRBG_C not defined.\n");
return( 0 );
}
#else
int main( int argc, char *argv[] )
{
int ret, len;
int listen_fd;
int client_fd = -1;
unsigned char buf[1024];
char *pers = "ssl_server";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_cert srvcert;
rsa_context rsa;
#if defined(POLARSSL_SSL_CACHE_C)
ssl_cache_context cache;
#endif
((void) argc);
((void) argv);
#if defined(POLARSSL_SSL_CACHE_C)
ssl_cache_init( &cache );
#endif
/*
* 1. Load the certificates and private RSA key
*/
printf( "\n . Loading the server cert. and key..." );
fflush( stdout );
memset( &srvcert, 0, sizeof( x509_cert ) );
/*
* This demonstration program uses embedded test certificates.
* Instead, you may want to use x509parse_crtfile() to read the
* server and CA certificates, as well as x509parse_keyfile().
*/
ret = x509parse_crt( &srvcert, (unsigned char *) test_srv_crt,
strlen( test_srv_crt ) );
if( ret != 0 )
{
printf( " failed\n ! x509parse_crt returned %d\n\n", ret );
goto exit;
}
ret = x509parse_crt( &srvcert, (unsigned char *) test_ca_crt,
strlen( test_ca_crt ) );
if( ret != 0 )
{
printf( " failed\n ! x509parse_crt returned %d\n\n", ret );
goto exit;
}
rsa_init( &rsa, RSA_PKCS_V15, 0 );
ret = x509parse_key( &rsa, (unsigned char *) test_srv_key,
strlen( test_srv_key ), NULL, 0 );
if( ret != 0 )
{
printf( " failed\n ! x509parse_key returned %d\n\n", ret );
goto exit;
}
printf( " ok\n" );
/*
* 2. Setup the listening TCP socket
*/
printf( " . Bind on https://localhost:4433/ ..." );
fflush( stdout );
if( ( ret = net_bind( &listen_fd, NULL, 4433 ) ) != 0 )
{
printf( " failed\n ! net_bind returned %d\n\n", ret );
goto exit;
}
printf( " ok\n" );
/*
* 3. Seed the RNG
*/
printf( " . Seeding the random number generator..." );
fflush( stdout );
entropy_init( &entropy );
if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
(unsigned char *) pers, strlen( pers ) ) ) != 0 )
{
printf( " failed\n ! ctr_drbg_init returned %d\n", ret );
goto exit;
}
printf( " ok\n" );
/*
* 4. Setup stuff
*/
printf( " . Setting up the SSL data...." );
fflush( stdout );
if( ( ret = ssl_init( &ssl ) ) != 0 )
{
printf( " failed\n ! ssl_init returned %d\n\n", ret );
goto exit;
}
ssl_set_endpoint( &ssl, SSL_IS_SERVER );
ssl_set_authmode( &ssl, SSL_VERIFY_NONE );
ssl_set_rng( &ssl, ctr_drbg_random, &ctr_drbg );
ssl_set_dbg( &ssl, my_debug, stdout );
#if defined(POLARSSL_SSL_CACHE_C)
ssl_set_session_cache( &ssl, ssl_cache_get, &cache,
ssl_cache_set, &cache );
#endif
ssl_set_ca_chain( &ssl, srvcert.next, NULL, NULL );
ssl_set_own_cert( &ssl, &srvcert, &rsa );
printf( " ok\n" );
reset:
#ifdef POLARSSL_ERROR_C
if( ret != 0 )
{
char error_buf[100];
error_strerror( ret, error_buf, 100 );
printf("Last error was: %d - %s\n\n", ret, error_buf );
}
#endif
if( client_fd != -1 )
net_close( client_fd );
ssl_session_reset( &ssl );
/*
* 3. Wait until a client connects
*/
#if defined(_WIN32_WCE)
{
SHELLEXECUTEINFO sei;
ZeroMemory( &sei, sizeof( SHELLEXECUTEINFO ) );
sei.cbSize = sizeof( SHELLEXECUTEINFO );
sei.fMask = 0;
sei.hwnd = 0;
sei.lpVerb = _T( "open" );
sei.lpFile = _T( "https://localhost:4433/" );
sei.lpParameters = NULL;
sei.lpDirectory = NULL;
sei.nShow = SW_SHOWNORMAL;
ShellExecuteEx( &sei );
}
#elif defined(_WIN32)
ShellExecute( NULL, "open", "https://localhost:4433/",
NULL, NULL, SW_SHOWNORMAL );
#endif
client_fd = -1;
printf( " . Waiting for a remote connection ..." );
fflush( stdout );
if( ( ret = net_accept( listen_fd, &client_fd, NULL ) ) != 0 )
{
printf( " failed\n ! net_accept returned %d\n\n", ret );
goto exit;
}
ssl_set_bio( &ssl, net_recv, &client_fd,
net_send, &client_fd );
printf( " ok\n" );
/*
* 5. Handshake
*/
printf( " . Performing the SSL/TLS handshake..." );
fflush( stdout );
while( ( ret = ssl_handshake( &ssl ) ) != 0 )
{
if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
{
printf( " failed\n ! ssl_handshake returned %d\n\n", ret );
goto reset;
}
}
printf( " ok\n" );
/*
* 6. Read the HTTP Request
*/
printf( " < Read from client:" );
fflush( stdout );
do
{
len = sizeof( buf ) - 1;
memset( buf, 0, sizeof( buf ) );
ret = ssl_read( &ssl, buf, len );
if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
continue;
if( ret <= 0 )
{
switch( ret )
{
case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
printf( " connection was closed gracefully\n" );
break;
case POLARSSL_ERR_NET_CONN_RESET:
printf( " connection was reset by peer\n" );
break;
default:
printf( " ssl_read returned -0x%x\n", -ret );
break;
}
break;
}
len = ret;
printf( " %d bytes read\n\n%s", len, (char *) buf );
if( ret > 0 )
break;
}
while( 1 );
/*
* 7. Write the 200 Response
*/
printf( " > Write to client:" );
fflush( stdout );
len = sprintf( (char *) buf, HTTP_RESPONSE,
ssl_get_ciphersuite( &ssl ) );
while( ( ret = ssl_write( &ssl, buf, len ) ) <= 0 )
{
if( ret == POLARSSL_ERR_NET_CONN_RESET )
{
printf( " failed\n ! peer closed the connection\n\n" );
goto reset;
}
if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
{
printf( " failed\n ! ssl_write returned %d\n\n", ret );
goto exit;
}
}
len = ret;
printf( " %d bytes written\n\n%s\n", len, (char *) buf );
ret = 0;
goto reset;
exit:
#ifdef POLARSSL_ERROR_C
if( ret != 0 )
{
char error_buf[100];
error_strerror( ret, error_buf, 100 );
printf("Last error was: %d - %s\n\n", ret, error_buf );
}
#endif
net_close( client_fd );
x509_free( &srvcert );
rsa_free( &rsa );
ssl_free( &ssl );
#if defined(POLARSSL_SSL_CACHE_C)
ssl_cache_free( &cache );
#endif
#if defined(_WIN32)
printf( " Press Enter to exit this program.\n" );
fflush( stdout ); getchar();
#endif
return( ret );
}
#endif /* POLARSSL_BIGNUM_C && POLARSSL_CERTS_C && POLARSSL_ENTROPY_C &&
POLARSSL_SSL_TLS_C && POLARSSL_SSL_SRV_C && POLARSSL_NET_C &&
POLARSSL_RSA_C && POLARSSL_CTR_DRBG_C */
|
692878.c | /* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#include <stdio.h>
#include <openssl/bn.h>
#include <string.h>
#include <openssl/e_os2.h>
#if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__) || defined(__MINGW32__)
# include <sys/types.h>
# include <unistd.h>
#else
# include <process.h>
typedef int pid_t;
#endif
#if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
# define getpid GetThreadID
extern int GetThreadID(void);
#elif defined(_WIN32) && !defined(__WATCOMC__)
# define getpid _getpid
#endif
#include <openssl/crypto.h>
#include <openssl/dso.h>
#include <openssl/engine.h>
#include <openssl/buffer.h>
#ifndef OPENSSL_NO_RSA
# include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
# include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
# include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_HW
# ifndef OPENSSL_NO_HW_AEP
# ifdef FLAT_INC
# include "aep.h"
# else
# include "vendor_defns/aep.h"
# endif
# define AEP_LIB_NAME "aep engine"
# define FAIL_TO_SW 0x10101010
# include "e_aep_err.c"
static int aep_init(ENGINE *e);
static int aep_finish(ENGINE *e);
static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
static int aep_destroy(ENGINE *e);
static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR hConnection);
static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection);
static AEP_RV aep_close_connection(AEP_CONNECTION_HNDL hConnection);
static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use);
/* BIGNUM stuff */
# ifndef OPENSSL_NO_RSA
static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *q, const BIGNUM *dmp1,
const BIGNUM *dmq1, const BIGNUM *iqmp,
BN_CTX *ctx);
# endif
/* RSA stuff */
# ifndef OPENSSL_NO_RSA
static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx);
# endif
/* This function is aliased to mod_exp (with the mont stuff dropped). */
# ifndef OPENSSL_NO_RSA
static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
# endif
/* DSA stuff */
# ifndef OPENSSL_NO_DSA
static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont);
static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
# endif
/* DH stuff */
/* This function is aliased to mod_exp (with the DH and mont dropped). */
# ifndef OPENSSL_NO_DH
static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx);
# endif
/* rand stuff */
# ifdef AEPRAND
static int aep_rand(unsigned char *buf, int num);
static int aep_rand_status(void);
# endif
/* Bignum conversion stuff */
static AEP_RV GetBigNumSize(AEP_VOID_PTR ArbBigNum, AEP_U32 *BigNumSize);
static AEP_RV MakeAEPBigNum(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize,
unsigned char *AEP_BigNum);
static AEP_RV ConvertAEPBigNum(void *ArbBigNum, AEP_U32 BigNumSize,
unsigned char *AEP_BigNum);
/* The definitions for control commands specific to this engine */
# define AEP_CMD_SO_PATH ENGINE_CMD_BASE
static const ENGINE_CMD_DEFN aep_cmd_defns[] = {
{AEP_CMD_SO_PATH,
"SO_PATH",
"Specifies the path to the 'aep' shared library",
ENGINE_CMD_FLAG_STRING},
{0, NULL, NULL, 0}
};
# ifndef OPENSSL_NO_RSA
/* Our internal RSA_METHOD that we provide pointers to */
static RSA_METHOD aep_rsa = {
"Aep RSA method",
NULL, /* rsa_pub_encrypt */
NULL, /* rsa_pub_decrypt */
NULL, /* rsa_priv_encrypt */
NULL, /* rsa_priv_encrypt */
aep_rsa_mod_exp, /* rsa_mod_exp */
aep_mod_exp_mont, /* bn_mod_exp */
NULL, /* init */
NULL, /* finish */
0, /* flags */
NULL, /* app_data */
NULL, /* rsa_sign */
NULL, /* rsa_verify */
NULL /* rsa_keygen */
};
# endif
# ifndef OPENSSL_NO_DSA
/* Our internal DSA_METHOD that we provide pointers to */
static DSA_METHOD aep_dsa = {
"Aep DSA method",
NULL, /* dsa_do_sign */
NULL, /* dsa_sign_setup */
NULL, /* dsa_do_verify */
aep_dsa_mod_exp, /* dsa_mod_exp */
aep_mod_exp_dsa, /* bn_mod_exp */
NULL, /* init */
NULL, /* finish */
0, /* flags */
NULL, /* app_data */
NULL, /* dsa_paramgen */
NULL /* dsa_keygen */
};
# endif
# ifndef OPENSSL_NO_DH
/* Our internal DH_METHOD that we provide pointers to */
static DH_METHOD aep_dh = {
"Aep DH method",
NULL,
NULL,
aep_mod_exp_dh,
NULL,
NULL,
0,
NULL,
NULL
};
# endif
# ifdef AEPRAND
/* our internal RAND_method that we provide pointers to */
static RAND_METHOD aep_random = {
/*
* "AEP RAND method",
*/
NULL,
aep_rand,
NULL,
NULL,
aep_rand,
aep_rand_status,
};
# endif
/*
* Define an array of structures to hold connections
*/
static AEP_CONNECTION_ENTRY aep_app_conn_table[MAX_PROCESS_CONNECTIONS];
/*
* Used to determine if this is a new process
*/
static pid_t recorded_pid = 0;
# ifdef AEPRAND
static AEP_U8 rand_block[RAND_BLK_SIZE];
static AEP_U32 rand_block_bytes = 0;
# endif
/* Constants used when creating the ENGINE */
static const char *engine_aep_id = "aep";
static const char *engine_aep_name = "Aep hardware engine support";
static int max_key_len = 2176;
/*
* This internal function is used by ENGINE_aep() and possibly by the
* "dynamic" ENGINE support too
*/
static int bind_aep(ENGINE *e)
{
# ifndef OPENSSL_NO_RSA
const RSA_METHOD *meth1;
# endif
# ifndef OPENSSL_NO_DSA
const DSA_METHOD *meth2;
# endif
# ifndef OPENSSL_NO_DH
const DH_METHOD *meth3;
# endif
if (!ENGINE_set_id(e, engine_aep_id) ||
!ENGINE_set_name(e, engine_aep_name) ||
# ifndef OPENSSL_NO_RSA
!ENGINE_set_RSA(e, &aep_rsa) ||
# endif
# ifndef OPENSSL_NO_DSA
!ENGINE_set_DSA(e, &aep_dsa) ||
# endif
# ifndef OPENSSL_NO_DH
!ENGINE_set_DH(e, &aep_dh) ||
# endif
# ifdef AEPRAND
!ENGINE_set_RAND(e, &aep_random) ||
# endif
!ENGINE_set_init_function(e, aep_init) ||
!ENGINE_set_destroy_function(e, aep_destroy) ||
!ENGINE_set_finish_function(e, aep_finish) ||
!ENGINE_set_ctrl_function(e, aep_ctrl) ||
!ENGINE_set_cmd_defns(e, aep_cmd_defns))
return 0;
# ifndef OPENSSL_NO_RSA
/*
* We know that the "PKCS1_SSLeay()" functions hook properly to the
* aep-specific mod_exp and mod_exp_crt so we use those functions. NB: We
* don't use ENGINE_openssl() or anything "more generic" because
* something like the RSAref code may not hook properly, and if you own
* one of these cards then you have the right to do RSA operations on it
* anyway!
*/
meth1 = RSA_PKCS1_SSLeay();
aep_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
aep_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
aep_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
aep_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
# endif
# ifndef OPENSSL_NO_DSA
/*
* Use the DSA_OpenSSL() method and just hook the mod_exp-ish bits.
*/
meth2 = DSA_OpenSSL();
aep_dsa.dsa_do_sign = meth2->dsa_do_sign;
aep_dsa.dsa_sign_setup = meth2->dsa_sign_setup;
aep_dsa.dsa_do_verify = meth2->dsa_do_verify;
aep_dsa = *DSA_get_default_method();
aep_dsa.dsa_mod_exp = aep_dsa_mod_exp;
aep_dsa.bn_mod_exp = aep_mod_exp_dsa;
# endif
# ifndef OPENSSL_NO_DH
/* Much the same for Diffie-Hellman */
meth3 = DH_OpenSSL();
aep_dh.generate_key = meth3->generate_key;
aep_dh.compute_key = meth3->compute_key;
aep_dh.bn_mod_exp = meth3->bn_mod_exp;
# endif
/* Ensure the aep error handling is set up */
ERR_load_AEPHK_strings();
return 1;
}
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_helper(ENGINE *e, const char *id)
{
if (id && (strcmp(id, engine_aep_id) != 0))
return 0;
if (!bind_aep(e))
return 0;
return 1;
}
IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
# else
static ENGINE *engine_aep(void)
{
ENGINE *ret = ENGINE_new();
if (!ret)
return NULL;
if (!bind_aep(ret)) {
ENGINE_free(ret);
return NULL;
}
return ret;
}
void ENGINE_load_aep(void)
{
/* Copied from eng_[openssl|dyn].c */
ENGINE *toadd = engine_aep();
if (!toadd)
return;
ENGINE_add(toadd);
ENGINE_free(toadd);
ERR_clear_error();
}
# endif
/*
* This is a process-global DSO handle used for loading and unloading the Aep
* library. NB: This is only set (or unset) during an init() or finish() call
* (reference counts permitting) and they're operating with global locks, so
* this should be thread-safe implicitly.
*/
static DSO *aep_dso = NULL;
/*
* These are the static string constants for the DSO file name and the
* function symbol names to bind to.
*/
static const char *AEP_LIBNAME = NULL;
static const char *get_AEP_LIBNAME(void)
{
if (AEP_LIBNAME)
return AEP_LIBNAME;
return "aep";
}
static void free_AEP_LIBNAME(void)
{
if (AEP_LIBNAME)
OPENSSL_free((void *)AEP_LIBNAME);
AEP_LIBNAME = NULL;
}
static long set_AEP_LIBNAME(const char *name)
{
free_AEP_LIBNAME();
return ((AEP_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
}
static const char *AEP_F1 = "AEP_ModExp";
static const char *AEP_F2 = "AEP_ModExpCrt";
# ifdef AEPRAND
static const char *AEP_F3 = "AEP_GenRandom";
# endif
static const char *AEP_F4 = "AEP_Finalize";
static const char *AEP_F5 = "AEP_Initialize";
static const char *AEP_F6 = "AEP_OpenConnection";
static const char *AEP_F7 = "AEP_SetBNCallBacks";
static const char *AEP_F8 = "AEP_CloseConnection";
/*
* These are the function pointers that are (un)set when the library has
* successfully (un)loaded.
*/
static t_AEP_OpenConnection *p_AEP_OpenConnection = NULL;
static t_AEP_CloseConnection *p_AEP_CloseConnection = NULL;
static t_AEP_ModExp *p_AEP_ModExp = NULL;
static t_AEP_ModExpCrt *p_AEP_ModExpCrt = NULL;
# ifdef AEPRAND
static t_AEP_GenRandom *p_AEP_GenRandom = NULL;
# endif
static t_AEP_Initialize *p_AEP_Initialize = NULL;
static t_AEP_Finalize *p_AEP_Finalize = NULL;
static t_AEP_SetBNCallBacks *p_AEP_SetBNCallBacks = NULL;
/* (de)initialisation functions. */
static int aep_init(ENGINE *e)
{
t_AEP_ModExp *p1;
t_AEP_ModExpCrt *p2;
# ifdef AEPRAND
t_AEP_GenRandom *p3;
# endif
t_AEP_Finalize *p4;
t_AEP_Initialize *p5;
t_AEP_OpenConnection *p6;
t_AEP_SetBNCallBacks *p7;
t_AEP_CloseConnection *p8;
int to_return = 0;
if (aep_dso != NULL) {
AEPHKerr(AEPHK_F_AEP_INIT, AEPHK_R_ALREADY_LOADED);
goto err;
}
/* Attempt to load libaep.so. */
aep_dso = DSO_load(NULL, get_AEP_LIBNAME(), NULL, 0);
if (aep_dso == NULL) {
AEPHKerr(AEPHK_F_AEP_INIT, AEPHK_R_NOT_LOADED);
goto err;
}
if (!(p1 = (t_AEP_ModExp *) DSO_bind_func(aep_dso, AEP_F1)) ||
!(p2 = (t_AEP_ModExpCrt *) DSO_bind_func(aep_dso, AEP_F2)) ||
# ifdef AEPRAND
!(p3 = (t_AEP_GenRandom *) DSO_bind_func(aep_dso, AEP_F3)) ||
# endif
!(p4 = (t_AEP_Finalize *) DSO_bind_func(aep_dso, AEP_F4)) ||
!(p5 = (t_AEP_Initialize *) DSO_bind_func(aep_dso, AEP_F5)) ||
!(p6 = (t_AEP_OpenConnection *) DSO_bind_func(aep_dso, AEP_F6)) ||
!(p7 = (t_AEP_SetBNCallBacks *) DSO_bind_func(aep_dso, AEP_F7)) ||
!(p8 = (t_AEP_CloseConnection *) DSO_bind_func(aep_dso, AEP_F8))) {
AEPHKerr(AEPHK_F_AEP_INIT, AEPHK_R_NOT_LOADED);
goto err;
}
/* Copy the pointers */
p_AEP_ModExp = p1;
p_AEP_ModExpCrt = p2;
# ifdef AEPRAND
p_AEP_GenRandom = p3;
# endif
p_AEP_Finalize = p4;
p_AEP_Initialize = p5;
p_AEP_OpenConnection = p6;
p_AEP_SetBNCallBacks = p7;
p_AEP_CloseConnection = p8;
to_return = 1;
return to_return;
err:
if (aep_dso)
DSO_free(aep_dso);
aep_dso = NULL;
p_AEP_OpenConnection = NULL;
p_AEP_ModExp = NULL;
p_AEP_ModExpCrt = NULL;
# ifdef AEPRAND
p_AEP_GenRandom = NULL;
# endif
p_AEP_Initialize = NULL;
p_AEP_Finalize = NULL;
p_AEP_SetBNCallBacks = NULL;
p_AEP_CloseConnection = NULL;
return to_return;
}
/* Destructor (complements the "ENGINE_aep()" constructor) */
static int aep_destroy(ENGINE *e)
{
free_AEP_LIBNAME();
ERR_unload_AEPHK_strings();
return 1;
}
static int aep_finish(ENGINE *e)
{
int to_return = 0, in_use;
AEP_RV rv;
if (aep_dso == NULL) {
AEPHKerr(AEPHK_F_AEP_FINISH, AEPHK_R_NOT_LOADED);
goto err;
}
rv = aep_close_all_connections(0, &in_use);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_FINISH, AEPHK_R_CLOSE_HANDLES_FAILED);
goto err;
}
if (in_use) {
AEPHKerr(AEPHK_F_AEP_FINISH, AEPHK_R_CONNECTIONS_IN_USE);
goto err;
}
rv = p_AEP_Finalize();
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_FINISH, AEPHK_R_FINALIZE_FAILED);
goto err;
}
if (!DSO_free(aep_dso)) {
AEPHKerr(AEPHK_F_AEP_FINISH, AEPHK_R_UNIT_FAILURE);
goto err;
}
aep_dso = NULL;
p_AEP_CloseConnection = NULL;
p_AEP_OpenConnection = NULL;
p_AEP_ModExp = NULL;
p_AEP_ModExpCrt = NULL;
# ifdef AEPRAND
p_AEP_GenRandom = NULL;
# endif
p_AEP_Initialize = NULL;
p_AEP_Finalize = NULL;
p_AEP_SetBNCallBacks = NULL;
to_return = 1;
err:
return to_return;
}
static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
{
int initialised = ((aep_dso == NULL) ? 0 : 1);
switch (cmd) {
case AEP_CMD_SO_PATH:
if (p == NULL) {
AEPHKerr(AEPHK_F_AEP_CTRL, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (initialised) {
AEPHKerr(AEPHK_F_AEP_CTRL, AEPHK_R_ALREADY_LOADED);
return 0;
}
return set_AEP_LIBNAME((const char *)p);
default:
break;
}
AEPHKerr(AEPHK_F_AEP_CTRL, AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED);
return 0;
}
static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx)
{
int to_return = 0;
int r_len = 0;
AEP_CONNECTION_HNDL hConnection;
AEP_RV rv;
r_len = BN_num_bits(m);
/* Perform in software if modulus is too large for hardware. */
if (r_len > max_key_len) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
return BN_mod_exp(r, a, p, m, ctx);
}
/*
* Grab a connection from the pool
*/
rv = aep_get_connection(&hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_GET_HANDLE_FAILED);
return BN_mod_exp(r, a, p, m, ctx);
}
/*
* To the card with the mod exp
*/
rv = p_AEP_ModExp(hConnection, (void *)a, (void *)p, (void *)m, (void *)r,
NULL);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_MOD_EXP_FAILED);
rv = aep_close_connection(hConnection);
return BN_mod_exp(r, a, p, m, ctx);
}
/*
* Return the connection to the pool
*/
rv = aep_return_connection(hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_RETURN_CONNECTION_FAILED);
goto err;
}
to_return = 1;
err:
return to_return;
}
# ifndef OPENSSL_NO_RSA
static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *q, const BIGNUM *dmp1,
const BIGNUM *dmq1, const BIGNUM *iqmp,
BN_CTX *ctx)
{
AEP_RV rv = AEP_R_OK;
AEP_CONNECTION_HNDL hConnection;
/*
* Grab a connection from the pool
*/
rv = aep_get_connection(&hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT, AEPHK_R_GET_HANDLE_FAILED);
return FAIL_TO_SW;
}
/*
* To the card with the mod exp
*/
rv = p_AEP_ModExpCrt(hConnection, (void *)a, (void *)p, (void *)q,
(void *)dmp1, (void *)dmq1, (void *)iqmp, (void *)r,
NULL);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT, AEPHK_R_MOD_EXP_CRT_FAILED);
rv = aep_close_connection(hConnection);
return FAIL_TO_SW;
}
/*
* Return the connection to the pool
*/
rv = aep_return_connection(hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT, AEPHK_R_RETURN_CONNECTION_FAILED);
goto err;
}
err:
return rv;
}
# endif
# ifdef AEPRAND
static int aep_rand(unsigned char *buf, int len)
{
AEP_RV rv = AEP_R_OK;
AEP_CONNECTION_HNDL hConnection;
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
/*
* Can the request be serviced with what's already in the buffer?
*/
if (len <= rand_block_bytes) {
memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
rand_block_bytes -= len;
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
} else
/*
* If not the get another block of random bytes
*/
{
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
rv = aep_get_connection(&hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_RAND, AEPHK_R_GET_HANDLE_FAILED);
goto err_nounlock;
}
if (len > RAND_BLK_SIZE) {
rv = p_AEP_GenRandom(hConnection, len, 2, buf, NULL);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_RAND, AEPHK_R_GET_RANDOM_FAILED);
goto err_nounlock;
}
} else {
CRYPTO_w_lock(CRYPTO_LOCK_RAND);
rv = p_AEP_GenRandom(hConnection, RAND_BLK_SIZE, 2,
&rand_block[0], NULL);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_RAND, AEPHK_R_GET_RANDOM_FAILED);
goto err;
}
rand_block_bytes = RAND_BLK_SIZE;
memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len);
rand_block_bytes -= len;
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
}
rv = aep_return_connection(hConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_RAND, AEPHK_R_RETURN_CONNECTION_FAILED);
goto err_nounlock;
}
}
return 1;
err:
CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
err_nounlock:
return 0;
}
static int aep_rand_status(void)
{
return 1;
}
# endif
# ifndef OPENSSL_NO_RSA
static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
{
int to_return = 0;
AEP_RV rv = AEP_R_OK;
if (!aep_dso) {
AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP, AEPHK_R_NOT_LOADED);
goto err;
}
/*
* See if we have all the necessary bits for a crt
*/
if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
rv = aep_mod_exp_crt(r0, I, rsa->p, rsa->q, rsa->dmp1, rsa->dmq1,
rsa->iqmp, ctx);
if (rv == FAIL_TO_SW) {
const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
to_return = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
goto err;
} else if (rv != AEP_R_OK)
goto err;
} else {
if (!rsa->d || !rsa->n) {
AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP, AEPHK_R_MISSING_KEY_COMPONENTS);
goto err;
}
rv = aep_mod_exp(r0, I, rsa->d, rsa->n, ctx);
if (rv != AEP_R_OK)
goto err;
}
to_return = 1;
err:
return to_return;
}
# endif
# ifndef OPENSSL_NO_DSA
static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
BIGNUM t;
int to_return = 0;
BN_init(&t);
/* let rr = a1 ^ p1 mod m */
if (!aep_mod_exp(rr, a1, p1, m, ctx))
goto end;
/* let t = a2 ^ p2 mod m */
if (!aep_mod_exp(&t, a2, p2, m, ctx))
goto end;
/* let rr = rr * t mod m */
if (!BN_mod_mul(rr, rr, &t, m, ctx))
goto end;
to_return = 1;
end:
BN_free(&t);
return to_return;
}
static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx)
{
return aep_mod_exp(r, a, p, m, ctx);
}
# endif
# ifndef OPENSSL_NO_RSA
/* This function is aliased to mod_exp (with the mont stuff dropped). */
static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
{
return aep_mod_exp(r, a, p, m, ctx);
}
# endif
# ifndef OPENSSL_NO_DH
/* This function is aliased to mod_exp (with the dh and mont dropped). */
static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *m_ctx)
{
return aep_mod_exp(r, a, p, m, ctx);
}
# endif
static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection)
{
int count;
AEP_RV rv = AEP_R_OK;
/*
* Get the current process id
*/
pid_t curr_pid;
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
curr_pid = getpid();
/*
* Check if this is the first time this is being called from the current
* process
*/
if (recorded_pid != curr_pid) {
/*
* Remember our pid so we can check if we're in a new process
*/
recorded_pid = curr_pid;
/*
* Call Finalize to make sure we have not inherited some data from a
* parent process
*/
p_AEP_Finalize();
/*
* Initialise the AEP API
*/
rv = p_AEP_Initialize(NULL);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_GET_CONNECTION, AEPHK_R_INIT_FAILURE);
recorded_pid = 0;
goto end;
}
/*
* Set the AEP big num call back functions
*/
rv = p_AEP_SetBNCallBacks(&GetBigNumSize, &MakeAEPBigNum,
&ConvertAEPBigNum);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,
AEPHK_R_SETBNCALLBACK_FAILURE);
recorded_pid = 0;
goto end;
}
# ifdef AEPRAND
/*
* Reset the rand byte count
*/
rand_block_bytes = 0;
# endif
/*
* Init the structures
*/
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
aep_app_conn_table[count].conn_state = NotConnected;
aep_app_conn_table[count].conn_hndl = 0;
}
/*
* Open a connection
*/
rv = p_AEP_OpenConnection(phConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_GET_CONNECTION, AEPHK_R_UNIT_FAILURE);
recorded_pid = 0;
goto end;
}
aep_app_conn_table[0].conn_state = InUse;
aep_app_conn_table[0].conn_hndl = *phConnection;
goto end;
}
/*
* Check the existing connections to see if we can find a free one
*/
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
if (aep_app_conn_table[count].conn_state == Connected) {
aep_app_conn_table[count].conn_state = InUse;
*phConnection = aep_app_conn_table[count].conn_hndl;
goto end;
}
}
/*
* If no connections available, we're going to have to try to open a new
* one
*/
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
if (aep_app_conn_table[count].conn_state == NotConnected) {
/*
* Open a connection
*/
rv = p_AEP_OpenConnection(phConnection);
if (rv != AEP_R_OK) {
AEPHKerr(AEPHK_F_AEP_GET_CONNECTION, AEPHK_R_UNIT_FAILURE);
goto end;
}
aep_app_conn_table[count].conn_state = InUse;
aep_app_conn_table[count].conn_hndl = *phConnection;
goto end;
}
}
rv = AEP_R_GENERAL_ERROR;
end:
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
return rv;
}
static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection)
{
int count;
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
/*
* Find the connection item that matches this connection handle
*/
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
if (aep_app_conn_table[count].conn_hndl == hConnection) {
aep_app_conn_table[count].conn_state = Connected;
break;
}
}
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
return AEP_R_OK;
}
static AEP_RV aep_close_connection(AEP_CONNECTION_HNDL hConnection)
{
int count;
AEP_RV rv = AEP_R_OK;
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
/*
* Find the connection item that matches this connection handle
*/
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
if (aep_app_conn_table[count].conn_hndl == hConnection) {
rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
if (rv != AEP_R_OK)
goto end;
aep_app_conn_table[count].conn_state = NotConnected;
aep_app_conn_table[count].conn_hndl = 0;
break;
}
}
end:
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
return rv;
}
static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use)
{
int count;
AEP_RV rv = AEP_R_OK;
*in_use = 0;
if (use_engine_lock)
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
for (count = 0; count < MAX_PROCESS_CONNECTIONS; count++) {
switch (aep_app_conn_table[count].conn_state) {
case Connected:
rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl);
if (rv != AEP_R_OK)
goto end;
aep_app_conn_table[count].conn_state = NotConnected;
aep_app_conn_table[count].conn_hndl = 0;
break;
case InUse:
(*in_use)++;
break;
case NotConnected:
break;
}
}
end:
if (use_engine_lock)
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
return rv;
}
/*
* BigNum call back functions, used to convert OpenSSL bignums into AEP
* bignums. Note only 32bit Openssl build support
*/
static AEP_RV GetBigNumSize(AEP_VOID_PTR ArbBigNum, AEP_U32 *BigNumSize)
{
BIGNUM *bn;
/*
* Cast the ArbBigNum pointer to our BIGNUM struct
*/
bn = (BIGNUM *)ArbBigNum;
# ifdef SIXTY_FOUR_BIT_LONG
*BigNumSize = bn->top << 3;
# else
/*
* Size of the bignum in bytes is equal to the bn->top (no of 32 bit
* words) multiplies by 4
*/
*BigNumSize = bn->top << 2;
# endif
return AEP_R_OK;
}
static AEP_RV MakeAEPBigNum(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize,
unsigned char *AEP_BigNum)
{
BIGNUM *bn;
# ifndef SIXTY_FOUR_BIT_LONG
unsigned char *buf;
int i;
# endif
/*
* Cast the ArbBigNum pointer to our BIGNUM struct
*/
bn = (BIGNUM *)ArbBigNum;
# ifdef SIXTY_FOUR_BIT_LONG
memcpy(AEP_BigNum, bn->d, BigNumSize);
# else
/*
* Must copy data into a (monotone) least significant byte first format
* performing endian conversion if necessary
*/
for (i = 0; i < bn->top; i++) {
buf = (unsigned char *)&bn->d[i];
*((AEP_U32 *)AEP_BigNum) = (AEP_U32)
((unsigned)buf[1] << 8 | buf[0]) |
((unsigned)buf[3] << 8 | buf[2]) << 16;
AEP_BigNum += 4;
}
# endif
return AEP_R_OK;
}
/*
* Turn an AEP Big Num back to a user big num
*/
static AEP_RV ConvertAEPBigNum(void *ArbBigNum, AEP_U32 BigNumSize,
unsigned char *AEP_BigNum)
{
BIGNUM *bn;
# ifndef SIXTY_FOUR_BIT_LONG
int i;
# endif
bn = (BIGNUM *)ArbBigNum;
/*
* Expand the result bn so that it can hold our big num. Size is in bits
*/
bn_expand(bn, (int)(BigNumSize << 3));
# ifdef SIXTY_FOUR_BIT_LONG
bn->top = BigNumSize >> 3;
if ((BigNumSize & 7) != 0)
bn->top++;
memset(bn->d, 0, bn->top << 3);
memcpy(bn->d, AEP_BigNum, BigNumSize);
# else
bn->top = BigNumSize >> 2;
for (i = 0; i < bn->top; i++) {
bn->d[i] = (AEP_U32)
((unsigned)AEP_BigNum[3] << 8 | AEP_BigNum[2]) << 16 |
((unsigned)AEP_BigNum[1] << 8 | AEP_BigNum[0]);
AEP_BigNum += 4;
}
# endif
return AEP_R_OK;
}
# endif /* !OPENSSL_NO_HW_AEP */
#endif /* !OPENSSL_NO_HW */
|
132731.c | // Auto-generated file. Do not edit!
// Template: src/f16-f32-vcvt/neon-int16.c.in
// Generator: tools/xngen
//
// Copyright 2021 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 <arm_neon.h>
#include <xnnpack/common.h>
#include <xnnpack/vcvt.h>
void xnn_f16_f32_vcvt_ukernel__neon_int16_x8(
size_t n,
const void* input,
float* output,
const void* params)
{
assert(n != 0);
assert(n % sizeof(float) == 0);
assert(input != NULL);
assert(output != NULL);
const uint16x8_t vsign_mask = vmovq_n_u16(0x8000);
const uint16x8_t vexp_offset = vmovq_n_u16(0x7000);
const float32x4_t vexp_scale = vmovq_n_f32(0x1.0p-112f);
const uint32x4_t vmagic_mask = vmovq_n_u32(0x3F000000);
const float32x4_t vmagic_bias = vmovq_n_f32(0.5f);
const uint16x8_t vdenorm_cutoff = vmovq_n_u16(0x0400);
const uint16_t* i = (const uint16_t*) input;
for (; n >= 8 * sizeof(float); n -= 8 * sizeof(float)) {
const uint16x8_t vh = vld1q_u16(i); i += 8;
const uint16x8_t vsign = vandq_u16(vh, vsign_mask);
const uint16x8_t vnonsign = veorq_u16(vh, vsign);
const uint16x8x2_t vprenorm = vzipq_u16(vshlq_n_u16(vnonsign, 13), vsraq_n_u16(vexp_offset, vnonsign, 3));
const float32x4_t vnorm_lo = vmulq_f32(vreinterpretq_f32_u16(vprenorm.val[0]), vexp_scale);
const float32x4_t vnorm_hi = vmulq_f32(vreinterpretq_f32_u16(vprenorm.val[1]), vexp_scale);
const float32x4_t vdenorm_lo = vsubq_f32(vreinterpretq_f32_u32(vaddw_u16(vmagic_mask, vget_low_u16(vnonsign))), vmagic_bias);
const float32x4_t vdenorm_hi = vsubq_f32(vreinterpretq_f32_u32(vaddw_u16(vmagic_mask, vget_high_u16(vnonsign))), vmagic_bias);
const uint16x8_t vmask = vcgtq_u16(vnonsign, vdenorm_cutoff);
const uint32x4_t vxmask_lo = vreinterpretq_u32_s32(vmovl_s16(vreinterpret_s16_u16(vget_low_u16(vmask))));
const uint32x4_t vf_lo = vorrq_u32(vshll_n_u16(vget_low_u16(vsign), 16),
vreinterpretq_u32_f32(vbslq_f32(vxmask_lo, vnorm_lo, vdenorm_lo)));
const uint32x4_t vxmask_hi = vreinterpretq_u32_s32(vmovl_s16(vreinterpret_s16_u16(vget_high_u16(vmask))));
const uint32x4_t vf_hi = vorrq_u32(vshll_n_u16(vget_high_u16(vsign), 16),
vreinterpretq_u32_f32(vbslq_f32(vxmask_hi, vnorm_hi, vdenorm_hi)));
vst1q_f32(output, vreinterpretq_f32_u32(vf_lo)); output += 4;
vst1q_f32(output, vreinterpretq_f32_u32(vf_hi)); output += 4;
}
if XNN_UNPREDICTABLE(n != 0) {
const uint16x8_t vh = vld1q_u16(i); i += 8;
const uint16x8_t vsign = vandq_u16(vh, vsign_mask);
const uint16x8_t vnonsign = veorq_u16(vh, vsign);
const uint16x8x2_t vprenorm = vzipq_u16(vshlq_n_u16(vnonsign, 13), vsraq_n_u16(vexp_offset, vnonsign, 3));
const float32x4_t vnorm_lo = vmulq_f32(vreinterpretq_f32_u16(vprenorm.val[0]), vexp_scale);
const float32x4_t vnorm_hi = vmulq_f32(vreinterpretq_f32_u16(vprenorm.val[1]), vexp_scale);
const float32x4_t vdenorm_lo = vsubq_f32(vreinterpretq_f32_u32(vaddw_u16(vmagic_mask, vget_low_u16(vnonsign))), vmagic_bias);
const float32x4_t vdenorm_hi = vsubq_f32(vreinterpretq_f32_u32(vaddw_u16(vmagic_mask, vget_high_u16(vnonsign))), vmagic_bias);
const uint16x8_t vmask = vcgtq_u16(vnonsign, vdenorm_cutoff);
const uint32x4_t vxmask_lo = vreinterpretq_u32_s32(vmovl_s16(vreinterpret_s16_u16(vget_low_u16(vmask))));
uint32x4_t vf = vorrq_u32(vshll_n_u16(vget_low_u16(vsign), 16),
vreinterpretq_u32_f32(vbslq_f32(vxmask_lo, vnorm_lo, vdenorm_lo)));
if (n & (4 * sizeof(float))) {
vst1q_f32(output, vreinterpretq_f32_u32(vf)); output += 4;
const uint32x4_t vxmask_hi = vreinterpretq_u32_s32(vmovl_s16(vreinterpret_s16_u16(vget_high_u16(vmask))));
vf = vorrq_u32(vshll_n_u16(vget_high_u16(vsign), 16),
vreinterpretq_u32_f32(vbslq_f32(vxmask_hi, vnorm_hi, vdenorm_hi)));
}
uint32x2_t vf_lo = vget_low_u32(vf);
if (n & (2 * sizeof(float))) {
vst1_f32(output, vreinterpret_f32_u32(vf_lo)); output += 2;
vf_lo = vget_high_u32(vf);
}
if (n & (1 * sizeof(float))) {
vst1_lane_f32(output, vreinterpret_f32_u32(vf_lo), 0);
}
}
}
|
713709.c | //------------------------------------------------------------------------------
// GB_Asaxpy3B: hard-coded saxpy3 method for a semiring
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB_AxB_defs__min_firsti_int64.h"
#ifndef GBCOMPACT
//------------------------------------------------------------------------------
// C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
GrB_Info GB (_Asaxpy3B__min_firsti_int64)
(
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_packed_in_place,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
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__min_firsti_int64) (C,
A, A_is_pattern, B, B_is_pattern,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
else if (!Mask_comp)
{
// C<M> = A*B
return (GB (_Asaxpy3B_M__min_firsti_int64) (C,
M, Mask_struct, M_packed_in_place,
A, A_is_pattern, B, B_is_pattern,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
else
{
// C<!M> = A*B
return (GB (_Asaxpy3B_notM__min_firsti_int64) (C,
M, Mask_struct, M_packed_in_place,
A, A_is_pattern, B, B_is_pattern,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
#endif
}
#endif
|
869961.c | /**
******************************************************************************
* @file stm32f7xx_hal_pcd_ex.c
* @author MCD Application Team
* @version V1.1.2
* @date 23-September-2016
* @brief PCD HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Extended features functions
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal.h"
/** @addtogroup STM32F7xx_HAL_Driver
* @{
*/
/** @defgroup PCDEx PCDEx
* @brief PCD Extended HAL module driver
* @{
*/
#ifdef HAL_PCD_MODULE_ENABLED
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions
* @{
*/
/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions
* @brief PCDEx control functions
*
@verbatim
===============================================================================
##### Extended features functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Update FIFO configuration
@endverbatim
* @{
*/
/**
* @brief Set Tx FIFO
* @param hpcd: PCD handle
* @param fifo: The number of Tx fifo
* @param size: Fifo size
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size)
{
uint8_t i = 0;
uint32_t Tx_Offset = 0;
/* TXn min size = 16 words. (n : Transmit FIFO index)
When a TxFIFO is not used, the Configuration should be as follows:
case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes)
--> Txm can use the space allocated for Txn.
case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes)
--> Txn should be configured with the minimum space of 16 words
The FIFO is used optimally when used TxFIFOs are allocated in the top
of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones.
When DMA is used 3n * FIFO locations should be reserved for internal DMA registers */
Tx_Offset = hpcd->Instance->GRXFSIZ;
if(fifo == 0)
{
hpcd->Instance->DIEPTXF0_HNPTXFSIZ = (uint32_t)(((uint32_t)size << 16) | Tx_Offset);
}
else
{
Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16;
for (i = 0; i < (fifo - 1); i++)
{
Tx_Offset += (hpcd->Instance->DIEPTXF[i] >> 16);
}
/* Multiply Tx_Size by 2 to get higher performance */
hpcd->Instance->DIEPTXF[fifo - 1] = (uint32_t)(((uint32_t)size << 16) | Tx_Offset);
}
return HAL_OK;
}
/**
* @brief Set Rx FIFO
* @param hpcd: PCD handle
* @param size: Size of Rx fifo
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size)
{
hpcd->Instance->GRXFSIZ = size;
return HAL_OK;
}
/**
* @brief Activate LPM Feature
* @param hpcd: PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = ENABLE;
hpcd->LPM_State = LPM_L0;
USBx->GINTMSK |= USB_OTG_GINTMSK_LPMINTM;
USBx->GLPMCFG |= (USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL);
return HAL_OK;
}
/**
* @brief DeActivate LPM feature.
* @param hpcd: PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = DISABLE;
USBx->GINTMSK &= ~USB_OTG_GINTMSK_LPMINTM;
USBx->GLPMCFG &= ~(USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL);
return HAL_OK;
}
/**
* @brief Send LPM message to user layer callback.
* @param hpcd: PCD handle
* @param msg: LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_PCDEx_LPM_Callback could be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_PCD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
392025.c | /*
* Copyright(c) 2012-2021 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#include "ocf/ocf.h"
#include "ocf_priv.h"
#include "metadata/metadata.h"
#include "engine/cache_engine.h"
#include "utils/utils_part.h"
int ocf_cache_io_class_get_info(ocf_cache_t cache, uint32_t io_class,
struct ocf_io_class_info *info)
{
ocf_part_id_t part_id = io_class;
OCF_CHECK_NULL(cache);
if (!info)
return -OCF_ERR_INVAL;
if (io_class >= OCF_IO_CLASS_MAX)
return -OCF_ERR_INVAL;
if (!ocf_part_is_valid(&cache->user_parts[part_id])) {
/* Partition does not exist */
return -OCF_ERR_IO_CLASS_NOT_EXIST;
}
if (env_strncpy(info->name, OCF_IO_CLASS_NAME_MAX - 1,
cache->user_parts[part_id].config->name,
sizeof(cache->user_parts[part_id].config->name))) {
return -OCF_ERR_INVAL;
}
info->priority = cache->user_parts[part_id].config->priority;
info->curr_size = ocf_cache_is_device_attached(cache) ?
cache->user_parts[part_id].runtime->curr_size : 0;
info->min_size = cache->user_parts[part_id].config->min_size;
info->max_size = cache->user_parts[part_id].config->max_size;
info->eviction_policy_type = cache->conf_meta->eviction_policy_type;
info->cleaning_policy_type = cache->conf_meta->cleaning_policy_type;
info->cache_mode = cache->user_parts[part_id].config->cache_mode;
return 0;
}
int ocf_io_class_visit(ocf_cache_t cache, ocf_io_class_visitor_t visitor,
void *cntx)
{
struct ocf_user_part *part;
ocf_part_id_t part_id;
int result = 0;
OCF_CHECK_NULL(cache);
if (!visitor)
return -OCF_ERR_INVAL;
for_each_part(cache, part, part_id) {
if (!ocf_part_is_valid(part))
continue;
result = visitor(cache, part_id, cntx);
if (result)
break;
}
return result;
}
|
908356.c | // SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2019 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* Example program for Host Bandwidth Managment
*
* This program loads a cgroup skb BPF program to enforce cgroup output
* (egress) or input (ingress) bandwidth limits.
*
* USAGE: hbm [-d] [-l] [-n <id>] [-r <rate>] [-s] [-t <secs>] [-w] [-h] [prog]
* Where:
* -d Print BPF trace debug buffer
* -l Also limit flows doing loopback
* -n <#> To create cgroup \"/hbm#\" and attach prog
* Default is /hbm1
* --no_cn Do not return cn notifications
* -r <rate> Rate limit in Mbps
* -s Get HBM stats (marked, dropped, etc.)
* -t <time> Exit after specified seconds (default is 0)
* -w Work conserving flag. cgroup can increase its bandwidth
* beyond the rate limit specified while there is available
* bandwidth. Current implementation assumes there is only
* NIC (eth0), but can be extended to support multiple NICs.
* Currrently only supported for egress.
* -h Print this info
* prog BPF program file name. Name defaults to hbm_out_kern.o
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/unistd.h>
#include <linux/bpf.h>
#include <bpf/bpf.h>
#include <getopt.h>
#include "bpf_load.h"
#include "bpf_rlimit.h"
#include "cgroup_helpers.h"
#include "hbm.h"
#include "bpf_util.h"
#include "bpf.h"
#include "libbpf.h"
bool outFlag = true;
int minRate = 1000; /* cgroup rate limit in Mbps */
int rate = 1000; /* can grow if rate conserving is enabled */
int dur = 1;
bool stats_flag;
bool loopback_flag;
bool debugFlag;
bool work_conserving_flag;
bool no_cn_flag;
bool edt_flag;
static void Usage(void);
static void read_trace_pipe2(void);
static void do_error(char *msg, bool errno_flag);
#define DEBUGFS "/sys/kernel/debug/tracing/"
struct bpf_object *obj;
int bpfprog_fd;
int cgroup_storage_fd;
static void read_trace_pipe2(void)
{
int trace_fd;
FILE *outf;
char *outFname = "hbm_out.log";
trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
if (trace_fd < 0) {
printf("Error opening trace_pipe\n");
return;
}
// Future support of ingress
// if (!outFlag)
// outFname = "hbm_in.log";
outf = fopen(outFname, "w");
if (outf == NULL)
printf("Error creating %s\n", outFname);
while (1) {
static char buf[4097];
ssize_t sz;
sz = read(trace_fd, buf, sizeof(buf) - 1);
if (sz > 0) {
buf[sz] = 0;
puts(buf);
if (outf != NULL) {
fprintf(outf, "%s\n", buf);
fflush(outf);
}
}
}
}
static void do_error(char *msg, bool errno_flag)
{
if (errno_flag)
printf("ERROR: %s, errno: %d\n", msg, errno);
else
printf("ERROR: %s\n", msg);
exit(1);
}
static int prog_load(char *prog)
{
struct bpf_prog_load_attr prog_load_attr = {
.prog_type = BPF_PROG_TYPE_CGROUP_SKB,
.file = prog,
.expected_attach_type = BPF_CGROUP_INET_EGRESS,
};
int map_fd;
struct bpf_map *map;
int ret = 0;
if (access(prog, O_RDONLY) < 0) {
printf("Error accessing file %s: %s\n", prog, strerror(errno));
return 1;
}
if (bpf_prog_load_xattr(&prog_load_attr, &obj, &bpfprog_fd))
ret = 1;
if (!ret) {
map = bpf_object__find_map_by_name(obj, "queue_stats");
map_fd = bpf_map__fd(map);
if (map_fd < 0) {
printf("Map not found: %s\n", strerror(map_fd));
ret = 1;
}
}
if (ret) {
printf("ERROR: load_bpf_file failed for: %s\n", prog);
printf(" Output from verifier:\n%s\n------\n", bpf_log_buf);
ret = -1;
} else {
ret = map_fd;
}
return ret;
}
static int run_bpf_prog(char *prog, int cg_id)
{
int map_fd;
int rc = 0;
int key = 0;
int cg1 = 0;
int type = BPF_CGROUP_INET_EGRESS;
char cg_dir[100];
struct hbm_queue_stats qstats = {0};
sprintf(cg_dir, "/hbm%d", cg_id);
map_fd = prog_load(prog);
if (map_fd == -1)
return 1;
if (setup_cgroup_environment()) {
printf("ERROR: setting cgroup environment\n");
goto err;
}
cg1 = create_and_get_cgroup(cg_dir);
if (!cg1) {
printf("ERROR: create_and_get_cgroup\n");
goto err;
}
if (join_cgroup(cg_dir)) {
printf("ERROR: join_cgroup\n");
goto err;
}
qstats.rate = rate;
qstats.stats = stats_flag ? 1 : 0;
qstats.loopback = loopback_flag ? 1 : 0;
qstats.no_cn = no_cn_flag ? 1 : 0;
if (bpf_map_update_elem(map_fd, &key, &qstats, BPF_ANY)) {
printf("ERROR: Could not update map element\n");
goto err;
}
if (!outFlag)
type = BPF_CGROUP_INET_INGRESS;
if (bpf_prog_attach(bpfprog_fd, cg1, type, 0)) {
printf("ERROR: bpf_prog_attach fails!\n");
log_err("Attaching prog");
goto err;
}
if (work_conserving_flag) {
struct timeval t0, t_last, t_new;
FILE *fin;
unsigned long long last_eth_tx_bytes, new_eth_tx_bytes;
signed long long last_cg_tx_bytes, new_cg_tx_bytes;
signed long long delta_time, delta_bytes, delta_rate;
int delta_ms;
#define DELTA_RATE_CHECK 10000 /* in us */
#define RATE_THRESHOLD 9500000000 /* 9.5 Gbps */
bpf_map_lookup_elem(map_fd, &key, &qstats);
if (gettimeofday(&t0, NULL) < 0)
do_error("gettimeofday failed", true);
t_last = t0;
fin = fopen("/sys/class/net/eth0/statistics/tx_bytes", "r");
if (fscanf(fin, "%llu", &last_eth_tx_bytes) != 1)
do_error("fscanf fails", false);
fclose(fin);
last_cg_tx_bytes = qstats.bytes_total;
while (true) {
usleep(DELTA_RATE_CHECK);
if (gettimeofday(&t_new, NULL) < 0)
do_error("gettimeofday failed", true);
delta_ms = (t_new.tv_sec - t0.tv_sec) * 1000 +
(t_new.tv_usec - t0.tv_usec)/1000;
if (delta_ms > dur * 1000)
break;
delta_time = (t_new.tv_sec - t_last.tv_sec) * 1000000 +
(t_new.tv_usec - t_last.tv_usec);
if (delta_time == 0)
continue;
t_last = t_new;
fin = fopen("/sys/class/net/eth0/statistics/tx_bytes",
"r");
if (fscanf(fin, "%llu", &new_eth_tx_bytes) != 1)
do_error("fscanf fails", false);
fclose(fin);
printf(" new_eth_tx_bytes:%llu\n",
new_eth_tx_bytes);
bpf_map_lookup_elem(map_fd, &key, &qstats);
new_cg_tx_bytes = qstats.bytes_total;
delta_bytes = new_eth_tx_bytes - last_eth_tx_bytes;
last_eth_tx_bytes = new_eth_tx_bytes;
delta_rate = (delta_bytes * 8000000) / delta_time;
printf("%5d - eth_rate:%.1fGbps cg_rate:%.3fGbps",
delta_ms, delta_rate/1000000000.0,
rate/1000.0);
if (delta_rate < RATE_THRESHOLD) {
/* can increase cgroup rate limit, but first
* check if we are using the current limit.
* Currently increasing by 6.25%, unknown
* if that is the optimal rate.
*/
int rate_diff100;
delta_bytes = new_cg_tx_bytes -
last_cg_tx_bytes;
last_cg_tx_bytes = new_cg_tx_bytes;
delta_rate = (delta_bytes * 8000000) /
delta_time;
printf(" rate:%.3fGbps",
delta_rate/1000000000.0);
rate_diff100 = (((long long)rate)*1000000 -
delta_rate) * 100 /
(((long long) rate) * 1000000);
printf(" rdiff:%d", rate_diff100);
if (rate_diff100 <= 3) {
rate += (rate >> 4);
if (rate > RATE_THRESHOLD / 1000000)
rate = RATE_THRESHOLD / 1000000;
qstats.rate = rate;
printf(" INC\n");
} else {
printf("\n");
}
} else {
/* Need to decrease cgroup rate limit.
* Currently decreasing by 12.5%, unknown
* if that is optimal
*/
printf(" DEC\n");
rate -= (rate >> 3);
if (rate < minRate)
rate = minRate;
qstats.rate = rate;
}
if (bpf_map_update_elem(map_fd, &key, &qstats, BPF_ANY))
do_error("update map element fails", false);
}
} else {
sleep(dur);
}
// Get stats!
if (stats_flag && bpf_map_lookup_elem(map_fd, &key, &qstats)) {
char fname[100];
FILE *fout;
if (!outFlag)
sprintf(fname, "hbm.%d.in", cg_id);
else
sprintf(fname, "hbm.%d.out", cg_id);
fout = fopen(fname, "w");
fprintf(fout, "id:%d\n", cg_id);
fprintf(fout, "ERROR: Could not lookup queue_stats\n");
} else if (stats_flag && qstats.lastPacketTime >
qstats.firstPacketTime) {
long long delta_us = (qstats.lastPacketTime -
qstats.firstPacketTime)/1000;
unsigned int rate_mbps = ((qstats.bytes_total -
qstats.bytes_dropped) * 8 /
delta_us);
double percent_pkts, percent_bytes;
char fname[100];
FILE *fout;
int k;
static const char *returnValNames[] = {
"DROP_PKT",
"ALLOW_PKT",
"DROP_PKT_CWR",
"ALLOW_PKT_CWR"
};
#define RET_VAL_COUNT 4
// Future support of ingress
// if (!outFlag)
// sprintf(fname, "hbm.%d.in", cg_id);
// else
sprintf(fname, "hbm.%d.out", cg_id);
fout = fopen(fname, "w");
fprintf(fout, "id:%d\n", cg_id);
fprintf(fout, "rate_mbps:%d\n", rate_mbps);
fprintf(fout, "duration:%.1f secs\n",
(qstats.lastPacketTime - qstats.firstPacketTime) /
1000000000.0);
fprintf(fout, "packets:%d\n", (int)qstats.pkts_total);
fprintf(fout, "bytes_MB:%d\n", (int)(qstats.bytes_total /
1000000));
fprintf(fout, "pkts_dropped:%d\n", (int)qstats.pkts_dropped);
fprintf(fout, "bytes_dropped_MB:%d\n",
(int)(qstats.bytes_dropped /
1000000));
// Marked Pkts and Bytes
percent_pkts = (qstats.pkts_marked * 100.0) /
(qstats.pkts_total + 1);
percent_bytes = (qstats.bytes_marked * 100.0) /
(qstats.bytes_total + 1);
fprintf(fout, "pkts_marked_percent:%6.2f\n", percent_pkts);
fprintf(fout, "bytes_marked_percent:%6.2f\n", percent_bytes);
// Dropped Pkts and Bytes
percent_pkts = (qstats.pkts_dropped * 100.0) /
(qstats.pkts_total + 1);
percent_bytes = (qstats.bytes_dropped * 100.0) /
(qstats.bytes_total + 1);
fprintf(fout, "pkts_dropped_percent:%6.2f\n", percent_pkts);
fprintf(fout, "bytes_dropped_percent:%6.2f\n", percent_bytes);
// ECN CE markings
percent_pkts = (qstats.pkts_ecn_ce * 100.0) /
(qstats.pkts_total + 1);
fprintf(fout, "pkts_ecn_ce:%6.2f (%d)\n", percent_pkts,
(int)qstats.pkts_ecn_ce);
// Average cwnd
fprintf(fout, "avg cwnd:%d\n",
(int)(qstats.sum_cwnd / (qstats.sum_cwnd_cnt + 1)));
// Average rtt
fprintf(fout, "avg rtt:%d\n",
(int)(qstats.sum_rtt / (qstats.pkts_total + 1)));
// Average credit
if (edt_flag)
fprintf(fout, "avg credit_ms:%.03f\n",
(qstats.sum_credit /
(qstats.pkts_total + 1.0)) / 1000000.0);
else
fprintf(fout, "avg credit:%d\n",
(int)(qstats.sum_credit /
(1500 * ((int)qstats.pkts_total ) + 1)));
// Return values stats
for (k = 0; k < RET_VAL_COUNT; k++) {
percent_pkts = (qstats.returnValCount[k] * 100.0) /
(qstats.pkts_total + 1);
fprintf(fout, "%s:%6.2f (%d)\n", returnValNames[k],
percent_pkts, (int)qstats.returnValCount[k]);
}
fclose(fout);
}
if (debugFlag)
read_trace_pipe2();
return rc;
err:
rc = 1;
if (cg1)
close(cg1);
cleanup_cgroup_environment();
return rc;
}
static void Usage(void)
{
printf("This program loads a cgroup skb BPF program to enforce\n"
"cgroup output (egress) bandwidth limits.\n\n"
"USAGE: hbm [-o] [-d] [-l] [-n <id>] [--no_cn] [-r <rate>]\n"
" [-s] [-t <secs>] [-w] [-h] [prog]\n"
" Where:\n"
" -o indicates egress direction (default)\n"
" -d print BPF trace debug buffer\n"
" --edt use fq's Earliest Departure Time\n"
" -l also limit flows using loopback\n"
" -n <#> to create cgroup \"/hbm#\" and attach prog\n"
" Default is /hbm1\n"
" --no_cn disable CN notifications\n"
" -r <rate> Rate in Mbps\n"
" -s Update HBM stats\n"
" -t <time> Exit after specified seconds (default is 0)\n"
" -w Work conserving flag. cgroup can increase\n"
" bandwidth beyond the rate limit specified\n"
" while there is available bandwidth. Current\n"
" implementation assumes there is only eth0\n"
" but can be extended to support multiple NICs\n"
" -h print this info\n"
" prog BPF program file name. Name defaults to\n"
" hbm_out_kern.o\n");
}
int main(int argc, char **argv)
{
char *prog = "hbm_out_kern.o";
int k;
int cg_id = 1;
char *optstring = "iodln:r:st:wh";
struct option loptions[] = {
{"no_cn", 0, NULL, 1},
{"edt", 0, NULL, 2},
{NULL, 0, NULL, 0}
};
while ((k = getopt_long(argc, argv, optstring, loptions, NULL)) != -1) {
switch (k) {
case 1:
no_cn_flag = true;
break;
case 2:
prog = "hbm_edt_kern.o";
edt_flag = true;
break;
case'o':
break;
case 'd':
debugFlag = true;
break;
case 'l':
loopback_flag = true;
break;
case 'n':
cg_id = atoi(optarg);
break;
case 'r':
minRate = atoi(optarg) * 1.024;
rate = minRate;
break;
case 's':
stats_flag = true;
break;
case 't':
dur = atoi(optarg);
break;
case 'w':
work_conserving_flag = true;
break;
case '?':
if (optopt == 'n' || optopt == 'r' || optopt == 't')
fprintf(stderr,
"Option -%c requires an argument.\n\n",
optopt);
case 'h':
// fallthrough
default:
Usage();
return 0;
}
}
if (optind < argc)
prog = argv[optind];
printf("HBM prog: %s\n", prog != NULL ? prog : "NULL");
return run_bpf_prog(prog, cg_id);
}
|
575195.c | /*
* Copyright (c) 2019 Gerson Fernando Budke
* Copyright (c) 2016 Piotr Mienkowski
* SPDX-License-Identifier: Apache-2.0
*/
/** @file
* @brief System module to support early Atmel SAM V71 MCU configuration
*/
#include <zephyr/device.h>
#include <zephyr/init.h>
#include <soc.h>
#include <zephyr/arch/cpu.h>
/**
* @brief Perform SoC configuration at boot.
*
* This should be run early during the boot process but after basic hardware
* initialization is done.
*
* @return 0
*/
static int atmel_samv71_config(const struct device *dev)
{
#ifdef CONFIG_SOC_ATMEL_SAMV71_DISABLE_ERASE_PIN
/* Disable ERASE function on PB12 pin, this is controlled by Bus
* Matrix
*/
MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO12;
#endif
/* In Cortex-M based SoCs JTAG interface can be used to perform
* IEEE1149.1 JTAG Boundary scan only. It can not be used as a debug
* interface therefore there is no harm done by disabling the JTAG TDI
* pin by default.
*/
/* Disable TDI function on PB4 pin, this is controlled by Bus Matrix
*/
MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO4;
#ifdef CONFIG_LOG_BACKEND_SWO
/* Disable PCK3 clock used by ETM module */
PMC->PMC_SCDR = PMC_SCDR_PCK3;
while ((PMC->PMC_SCSR) & PMC_SCSR_PCK3) {
;
}
/* Select PLLA clock as PCK3 clock */
PMC->PMC_PCK[3] = PMC_MCKR_CSS_PLLA_CLK;
/* Enable PCK3 clock */
PMC->PMC_SCER = PMC_SCER_PCK3;
/* Wait for PCK3 setup to complete */
while (!((PMC->PMC_SR) & PMC_SR_PCKRDY3)) {
;
}
/* Enable TDO/TRACESWO function on PB5 pin */
MATRIX->CCFG_SYSIO &= ~CCFG_SYSIO_SYSIO5;
#else
/* Disable TDO/TRACESWO function on PB5 pin */
MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO5;
#endif
return 0;
}
SYS_INIT(atmel_samv71_config, PRE_KERNEL_1, 1);
|
234812.c | /* Copyright(c) 1986 Association of Universities for Research in Astronomy Inc.
*/
#include <stdio.h>
#define import_kernel
#define import_knames
#define import_spp
#include <iraf.h>
/* ZFDELE -- Delete a file.
*/
int
ZFDELE (
PKCHAR *fname,
XINT *status
)
{
extern int vm_delete(char *fname, int force);
vm_delete ((char *)fname, 0);
if (unlink ((char *)fname) == ERR)
*status = XERR;
else
*status = XOK;
return (*status);
}
|
801323.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "X2AP-PDU-Contents"
* found in "/home/lixh/enb_folder/openair2/X2AP/MESSAGES/ASN1/R14/x2ap-14.6.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -fno-include-deps -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/X2AP_R14`
*/
#include "X2AP_ServedCellsToActivate.h"
#include "X2AP_ServedCellsToActivate-Item.h"
static asn_per_constraints_t asn_PER_type_X2AP_ServedCellsToActivate_constr_1 CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 8, 8, 1, 256 } /* (SIZE(1..256)) */,
0, 0 /* No PER value map */
};
static asn_TYPE_member_t asn_MBR_X2AP_ServedCellsToActivate_1[] = {
{ ATF_POINTER, 0, 0,
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2)),
0,
&asn_DEF_X2AP_ServedCellsToActivate_Item,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
""
},
};
static const ber_tlv_tag_t asn_DEF_X2AP_ServedCellsToActivate_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_SET_OF_specifics_t asn_SPC_X2AP_ServedCellsToActivate_specs_1 = {
sizeof(struct X2AP_ServedCellsToActivate),
offsetof(struct X2AP_ServedCellsToActivate, _asn_ctx),
0, /* XER encoding is XMLDelimitedItemList */
};
asn_TYPE_descriptor_t asn_DEF_X2AP_ServedCellsToActivate = {
"ServedCellsToActivate",
"ServedCellsToActivate",
&asn_OP_SEQUENCE_OF,
asn_DEF_X2AP_ServedCellsToActivate_tags_1,
sizeof(asn_DEF_X2AP_ServedCellsToActivate_tags_1)
/sizeof(asn_DEF_X2AP_ServedCellsToActivate_tags_1[0]), /* 1 */
asn_DEF_X2AP_ServedCellsToActivate_tags_1, /* Same as above */
sizeof(asn_DEF_X2AP_ServedCellsToActivate_tags_1)
/sizeof(asn_DEF_X2AP_ServedCellsToActivate_tags_1[0]), /* 1 */
{ 0, &asn_PER_type_X2AP_ServedCellsToActivate_constr_1, SEQUENCE_OF_constraint },
asn_MBR_X2AP_ServedCellsToActivate_1,
1, /* Single element */
&asn_SPC_X2AP_ServedCellsToActivate_specs_1 /* Additional specs */
};
|
826465.c | // RUN: %ocheck 0 %s -DINT_TY=int
// RUN: %ocheck 0 %s -DINT_TY=long\ long
void *memset(void *, int, unsigned long);
f()
{
return 3;
}
void abort(void);
main()
{
#include "../ocheck-init.c"
volatile INT_TY i;
// write non-zero bits to 'i'
memset(&i, 0xff, sizeof i);
// ensure we sign extend the V_FLAG/_Bool and store to all bits of 'i'
i = !!f();
if(i != 1)
abort();
return 0;
}
|
712481.c | #include <stdio.h>
#include <stdlib.h> // exit free
#include <string.h> // strstr
int main(int argc, char *argv[])
{
FILE *fp = NULL;
char *line = NULL;
size_t linecap = 0;
if ( 2 > argc ) {
fprintf(stderr, "wgrep: searchterm [file ...]\n");
exit(EXIT_FAILURE);
}
if ( 3 <= argc && NULL == (fp = fopen(argv[2], "r")) ) {
fprintf(stderr, "wgrep: cannot open file\n");
exit(EXIT_FAILURE);
}
// $ ./wgrep searchterm
// take input from stdin
if ( 2 == argc )
fp = stdin;
while ( 0 < getline(&line, &linecap, fp) )
if ( strstr(line, argv[1] ) )
printf("%s", line);
// getline malloc space for line if line is NULL
free(line);
fclose(fp);
return 0;
}
|
670126.c | /* Hash Tables Implementation.
*
* This file implements in memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*
* Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "fmacros.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <limits.h>
#include <sys/time.h>
#include "dict.h"
#include "zmalloc.h"
#ifndef DICT_BENCHMARK_MAIN
#include "redisassert.h"
#else
#include <assert.h>
#endif
/* Using dictEnableResize() / dictDisableResize() we make possible to
* enable/disable resizing of the hash table as needed. This is very important
* for Redis, as we use copy-on-write and don't want to move too much memory
* around when there is a child performing saving operations.
*
* Note that even when dict_can_resize is set to 0, not all resizes are
* prevented: a hash table is still allowed to grow if the ratio between
* the number of elements and the buckets > dict_force_resize_ratio. */
static int dict_can_resize = 1;
static unsigned int dict_force_resize_ratio = 5;
/* -------------------------- private prototypes ---------------------------- */
static int _dictExpandIfNeeded(dict *ht);
static unsigned long _dictNextPower(unsigned long size);
static long _dictKeyIndex(dict *ht, const void *key, uint64_t hash, dictEntry **existing);
static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
/* -------------------------- hash functions -------------------------------- */
static uint8_t dict_hash_function_seed[16];
void dictSetHashFunctionSeed(uint8_t *seed) {
memcpy(dict_hash_function_seed,seed,sizeof(dict_hash_function_seed));
}
uint8_t *dictGetHashFunctionSeed(void) {
return dict_hash_function_seed;
}
/* The default hashing function uses SipHash implementation
* in siphash.c. */
uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k);
uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k);
uint64_t dictGenHashFunction(const void *key, int len) {
return siphash(key,len,dict_hash_function_seed);
}
uint64_t dictGenCaseHashFunction(const unsigned char *buf, int len) {
return siphash_nocase(buf,len,dict_hash_function_seed);
}
/* ----------------------------- API implementation ------------------------- */
/* Reset a hash table already initialized with ht_init().
* NOTE: This function should only be called by ht_destroy(). */
static void _dictReset(dictht *ht)
{
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
}
/* Create a new hash table */
dict *dictCreate(dictType *type,
void *privDataPtr)
{
dict *d = zmalloc(sizeof(*d));
_dictInit(d,type,privDataPtr);
return d;
}
/* Initialize the hash table */
int _dictInit(dict *d, dictType *type,
void *privDataPtr)
{
_dictReset(&d->ht[0]);
_dictReset(&d->ht[1]);
d->type = type;
d->privdata = privDataPtr;
d->rehashidx = -1;
d->iterators = 0;
return DICT_OK;
}
/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USED/BUCKETS ratio near to <= 1 */
int dictResize(dict *d)
{
unsigned long minimal;
if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
minimal = d->ht[0].used;
if (minimal < DICT_HT_INITIAL_SIZE)
minimal = DICT_HT_INITIAL_SIZE;
return dictExpand(d, minimal);
}
/* Expand or create the hash table */
int dictExpand(dict *d, unsigned long size)
{
/* the size is invalid if it is smaller than the number of
* elements already inside the hash table */
if (dictIsRehashing(d) || d->ht[0].used > size)
return DICT_ERR;
dictht n; /* the new hash table */
unsigned long realsize = _dictNextPower(size);
/* Rehashing to the same table size is not useful. */
if (realsize == d->ht[0].size) return DICT_ERR;
/* Allocate the new hash table and initialize all pointers to NULL */
n.size = realsize;
n.sizemask = realsize-1;
n.table = zcalloc(realsize*sizeof(dictEntry*));
n.used = 0;
/* Is this the first initialization? If so it's not really a rehashing
* we just set the first hash table so that it can accept keys. */
if (d->ht[0].table == NULL) {
d->ht[0] = n;
return DICT_OK;
}
/* Prepare a second hash table for incremental rehashing */
d->ht[1] = n;
d->rehashidx = 0;
return DICT_OK;
}
/* Performs N steps of incremental rehashing. Returns 1 if there are still
* keys to move from the old to the new hash table, otherwise 0 is returned.
*
* Note that a rehashing step consists in moving a bucket (that may have more
* than one key as we use chaining) from the old to the new hash table, however
* since part of the hash table may be composed of empty spaces, it is not
* guaranteed that this function will rehash even a single bucket, since it
* will visit at max N*10 empty buckets in total, otherwise the amount of
* work it does would be unbound and the function may block for a long time. */
int dictRehash(dict *d, int n) {
int empty_visits = n*10; /* Max number of empty buckets to visit. */
if (!dictIsRehashing(d)) return 0;
while(n-- && d->ht[0].used != 0) {
dictEntry *de, *nextde;
/* Note that rehashidx can't overflow as we are sure there are more
* elements because ht[0].used != 0 */
assert(d->ht[0].size > (unsigned long)d->rehashidx);
while(d->ht[0].table[d->rehashidx] == NULL) {
d->rehashidx++;
if (--empty_visits == 0) return 1;
}
de = d->ht[0].table[d->rehashidx];
/* Move all the keys in this bucket from the old to the new hash HT */
while(de) {
uint64_t h;
nextde = de->next;
/* Get the index in the new hash table */
h = dictHashKey(d, de->key) & d->ht[1].sizemask;
de->next = d->ht[1].table[h];
d->ht[1].table[h] = de;
d->ht[0].used--;
d->ht[1].used++;
de = nextde;
}
d->ht[0].table[d->rehashidx] = NULL;
d->rehashidx++;
}
/* Check if we already rehashed the whole table... */
if (d->ht[0].used == 0) {
zfree(d->ht[0].table);
d->ht[0] = d->ht[1];
_dictReset(&d->ht[1]);
d->rehashidx = -1;
return 0;
}
/* More to rehash... */
return 1;
}
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
/* Rehash in ms+"delta" milliseconds. The value of "delta" is larger
* than 0, and is smaller than 1 in most cases. The exact upper bound
* depends on the running time of dictRehash(d,100).*/
int dictRehashMilliseconds(dict *d, int ms) {
long long start = timeInMilliseconds();
int rehashes = 0;
while(dictRehash(d,100)) {
rehashes += 100;
if (timeInMilliseconds()-start > ms) break;
}
return rehashes;
}
/* This function performs just a step of rehashing, and only if there are
* no safe iterators bound to our hash table. When we have iterators in the
* middle of a rehashing we can't mess with the two hash tables otherwise
* some element can be missed or duplicated.
*
* This function is called by common lookup or update operations in the
* dictionary so that the hash table automatically migrates from H1 to H2
* while it is actively used. */
static void _dictRehashStep(dict *d) {
if (d->iterators == 0) dictRehash(d,1);
}
/* Add an element to the target hash table */
int dictAdd(dict *d, void *key, void *val)
{
dictEntry *entry = dictAddRaw(d,key,NULL);
if (!entry) return DICT_ERR;
dictSetVal(d, entry, val);
return DICT_OK;
}
/* Low level add or find:
* This function adds the entry but instead of setting a value returns the
* dictEntry structure to the user, that will make sure to fill the value
* field as he wishes.
*
* This function is also directly exposed to the user API to be called
* mainly in order to store non-pointers inside the hash value, example:
*
* entry = dictAddRaw(dict,mykey,NULL);
* if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
*
* Return values:
*
* If key already exists NULL is returned, and "*existing" is populated
* with the existing entry if existing is not NULL.
*
* If key was added, the hash entry is returned to be manipulated by the caller.
*/
dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
{
long index;
dictEntry *entry;
dictht *ht;
if (dictIsRehashing(d)) _dictRehashStep(d);
/* Get the index of the new element, or -1 if
* the element already exists. */
if ((index = _dictKeyIndex(d, key, dictHashKey(d,key), existing)) == -1)
return NULL;
/* Allocate the memory and store the new entry.
* Insert the element in top, with the assumption that in a database
* system it is more likely that recently added entries are accessed
* more frequently. */
ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
entry = zmalloc(sizeof(*entry));
entry->next = ht->table[index];
ht->table[index] = entry;
ht->used++;
/* Set the hash entry fields. */
dictSetKey(d, entry, key);
return entry;
}
/* Add or Overwrite:
* Add an element, discarding the old value if the key already exists.
* Return 1 if the key was added from scratch, 0 if there was already an
* element with such key and dictReplace() just performed a value update
* operation. */
int dictReplace(dict *d, void *key, void *val)
{
dictEntry *entry, *existing, auxentry;
/* Try to add the element. If the key
* does not exists dictAdd will succeed. */
entry = dictAddRaw(d,key,&existing);
if (entry) {
dictSetVal(d, entry, val);
return 1;
}
/* Set the new value and free the old one. Note that it is important
* to do that in this order, as the value may just be exactly the same
* as the previous one. In this context, think to reference counting,
* you want to increment (set), and then decrement (free), and not the
* reverse. */
auxentry = *existing;
dictSetVal(d, existing, val);
dictFreeVal(d, &auxentry);
return 0;
}
/* Add or Find:
* dictAddOrFind() is simply a version of dictAddRaw() that always
* returns the hash entry of the specified key, even if the key already
* exists and can't be added (in that case the entry of the already
* existing key is returned.)
*
* See dictAddRaw() for more information. */
dictEntry *dictAddOrFind(dict *d, void *key) {
dictEntry *entry, *existing;
entry = dictAddRaw(d,key,&existing);
return entry ? entry : existing;
}
/* Search and remove an element. This is an helper function for
* dictDelete() and dictUnlink(), please check the top comment
* of those functions. */
static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
uint64_t h, idx;
dictEntry *he, *prevHe;
int table;
if (d->ht[0].used == 0 && d->ht[1].used == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
prevHe = NULL;
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key)) {
/* Unlink the element from the list */
if (prevHe)
prevHe->next = he->next;
else
d->ht[table].table[idx] = he->next;
if (!nofree) {
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
d->ht[table].used--;
return he;
}
prevHe = he;
he = he->next;
}
if (!dictIsRehashing(d)) break;
}
return NULL; /* not found */
}
/* Remove an element, returning DICT_OK on success or DICT_ERR if the
* element was not found. */
int dictDelete(dict *ht, const void *key) {
return dictGenericDelete(ht,key,0) ? DICT_OK : DICT_ERR;
}
/* Remove an element from the table, but without actually releasing
* the key, value and dictionary entry. The dictionary entry is returned
* if the element was found (and unlinked from the table), and the user
* should later call `dictFreeUnlinkedEntry()` with it in order to release it.
* Otherwise if the key is not found, NULL is returned.
*
* This function is useful when we want to remove something from the hash
* table but want to use its value before actually deleting the entry.
* Without this function the pattern would require two lookups:
*
* entry = dictFind(...);
* // Do something with entry
* dictDelete(dictionary,entry);
*
* Thanks to this function it is possible to avoid this, and use
* instead:
*
* entry = dictUnlink(dictionary,entry);
* // Do something with entry
* dictFreeUnlinkedEntry(entry); // <- This does not need to lookup again.
*/
dictEntry *dictUnlink(dict *ht, const void *key) {
return dictGenericDelete(ht,key,1);
}
/* You need to call this function to really free the entry after a call
* to dictUnlink(). It's safe to call this function with 'he' = NULL. */
void dictFreeUnlinkedEntry(dict *d, dictEntry *he) {
if (he == NULL) return;
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
/* Destroy an entire dictionary */
int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
unsigned long i;
/* Free all the elements */
for (i = 0; i < ht->size && ht->used > 0; i++) {
dictEntry *he, *nextHe;
if (callback && (i & 65535) == 0) callback(d->privdata);
if ((he = ht->table[i]) == NULL) continue;
while(he) {
nextHe = he->next;
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
ht->used--;
he = nextHe;
}
}
/* Free the table and the allocated cache structure */
zfree(ht->table);
/* Re-initialize the table */
_dictReset(ht);
return DICT_OK; /* never fails */
}
/* Clear & Release the hash table */
void dictRelease(dict *d)
{
_dictClear(d,&d->ht[0],NULL);
_dictClear(d,&d->ht[1],NULL);
zfree(d);
}
dictEntry *dictFind(dict *d, const void *key)
{
dictEntry *he;
uint64_t h, idx, table;
if (dictSize(d) == 0) return NULL; /* dict is empty */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key))
return he;
he = he->next;
}
if (!dictIsRehashing(d)) return NULL;
}
return NULL;
}
void *dictFetchValue(dict *d, const void *key) {
dictEntry *he;
he = dictFind(d,key);
return he ? dictGetVal(he) : NULL;
}
/* A fingerprint is a 64 bit number that represents the state of the dictionary
* at a given time, it's just a few dict properties xored together.
* When an unsafe iterator is initialized, we get the dict fingerprint, and check
* the fingerprint again when the iterator is released.
* If the two fingerprints are different it means that the user of the iterator
* performed forbidden operations against the dictionary while iterating. */
long long dictFingerprint(dict *d) {
long long integers[6], hash = 0;
int j;
integers[0] = (long) d->ht[0].table;
integers[1] = d->ht[0].size;
integers[2] = d->ht[0].used;
integers[3] = (long) d->ht[1].table;
integers[4] = d->ht[1].size;
integers[5] = d->ht[1].used;
/* We hash N integers by summing every successive integer with the integer
* hashing of the previous sum. Basically:
*
* Result = hash(hash(hash(int1)+int2)+int3) ...
*
* This way the same set of integers in a different order will (likely) hash
* to a different number. */
for (j = 0; j < 6; j++) {
hash += integers[j];
/* For the hashing step we use Tomas Wang's 64 bit integer hash. */
hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
hash = hash ^ (hash >> 24);
hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
hash = hash ^ (hash >> 14);
hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
hash = hash ^ (hash >> 28);
hash = hash + (hash << 31);
}
return hash;
}
dictIterator *dictGetIterator(dict *d)
{
dictIterator *iter = zmalloc(sizeof(*iter));
iter->d = d;
iter->table = 0;
iter->index = -1;
iter->safe = 0;
iter->entry = NULL;
iter->nextEntry = NULL;
return iter;
}
dictIterator *dictGetSafeIterator(dict *d) {
dictIterator *i = dictGetIterator(d);
i->safe = 1;
return i;
}
dictEntry *dictNext(dictIterator *iter)
{
while (1) {
if (iter->entry == NULL) {
dictht *ht = &iter->d->ht[iter->table];
if (iter->index == -1 && iter->table == 0) {
if (iter->safe)
iter->d->iterators++;
else
iter->fingerprint = dictFingerprint(iter->d);
}
iter->index++;
if (iter->index >= (long) ht->size) {
if (dictIsRehashing(iter->d) && iter->table == 0) {
iter->table++;
iter->index = 0;
ht = &iter->d->ht[1];
} else {
break;
}
}
iter->entry = ht->table[iter->index];
} else {
iter->entry = iter->nextEntry;
}
if (iter->entry) {
/* We need to save the 'next' here, the iterator user
* may delete the entry we are returning. */
iter->nextEntry = iter->entry->next;
return iter->entry;
}
}
return NULL;
}
void dictReleaseIterator(dictIterator *iter)
{
if (!(iter->index == -1 && iter->table == 0)) {
if (iter->safe)
iter->d->iterators--;
else
assert(iter->fingerprint == dictFingerprint(iter->d));
}
zfree(iter);
}
/* Return a random entry from the hash table. Useful to
* implement randomized algorithms */
dictEntry *dictGetRandomKey(dict *d)
{
dictEntry *he, *orighe;
unsigned long h;
int listlen, listele;
if (dictSize(d) == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
if (dictIsRehashing(d)) {
do {
/* We are sure there are no elements in indexes from 0
* to rehashidx-1 */
h = d->rehashidx + (randomULong() % (dictSlots(d) - d->rehashidx));
he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
d->ht[0].table[h];
} while(he == NULL);
} else {
do {
h = randomULong() & d->ht[0].sizemask;
he = d->ht[0].table[h];
} while(he == NULL);
}
/* Now we found a non empty bucket, but it is a linked
* list and we need to get a random element from the list.
* The only sane way to do so is counting the elements and
* select a random index. */
listlen = 0;
orighe = he;
while(he) {
he = he->next;
listlen++;
}
listele = random() % listlen;
he = orighe;
while(listele--) he = he->next;
return he;
}
/* This function samples the dictionary to return a few keys from random
* locations.
*
* It does not guarantee to return all the keys specified in 'count', nor
* it does guarantee to return non-duplicated elements, however it will make
* some effort to do both things.
*
* Returned pointers to hash table entries are stored into 'des' that
* points to an array of dictEntry pointers. The array must have room for
* at least 'count' elements, that is the argument we pass to the function
* to tell how many random elements we need.
*
* The function returns the number of items stored into 'des', that may
* be less than 'count' if the hash table has less than 'count' elements
* inside, or if not enough elements were found in a reasonable amount of
* steps.
*
* Note that this function is not suitable when you need a good distribution
* of the returned items, but only when you need to "sample" a given number
* of continuous elements to run some kind of algorithm or to produce
* statistics. However the function is much faster than dictGetRandomKey()
* at producing N elements. */
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) {
unsigned long j; /* internal hash table id, 0 or 1. */
unsigned long tables; /* 1 or 2 tables? */
unsigned long stored = 0, maxsizemask;
unsigned long maxsteps;
if (dictSize(d) < count) count = dictSize(d);
maxsteps = count*10;
/* Try to do a rehashing work proportional to 'count'. */
for (j = 0; j < count; j++) {
if (dictIsRehashing(d))
_dictRehashStep(d);
else
break;
}
tables = dictIsRehashing(d) ? 2 : 1;
maxsizemask = d->ht[0].sizemask;
if (tables > 1 && maxsizemask < d->ht[1].sizemask)
maxsizemask = d->ht[1].sizemask;
/* Pick a random point inside the larger table. */
unsigned long i = randomULong() & maxsizemask;
unsigned long emptylen = 0; /* Continuous empty entries so far. */
while(stored < count && maxsteps--) {
for (j = 0; j < tables; j++) {
/* Invariant of the dict.c rehashing: up to the indexes already
* visited in ht[0] during the rehashing, there are no populated
* buckets, so we can skip ht[0] for indexes between 0 and idx-1. */
if (tables == 2 && j == 0 && i < (unsigned long) d->rehashidx) {
/* Moreover, if we are currently out of range in the second
* table, there will be no elements in both tables up to
* the current rehashing index, so we jump if possible.
* (this happens when going from big to small table). */
if (i >= d->ht[1].size)
i = d->rehashidx;
else
continue;
}
if (i >= d->ht[j].size) continue; /* Out of range for this table. */
dictEntry *he = d->ht[j].table[i];
/* Count contiguous empty buckets, and jump to other
* locations if they reach 'count' (with a minimum of 5). */
if (he == NULL) {
emptylen++;
if (emptylen >= 5 && emptylen > count) {
i = randomULong() & maxsizemask;
emptylen = 0;
}
} else {
emptylen = 0;
while (he) {
/* Collect all the elements of the buckets found non
* empty while iterating. */
*des = he;
des++;
he = he->next;
stored++;
if (stored == count) return stored;
}
}
}
i = (i+1) & maxsizemask;
}
return stored;
}
/* This is like dictGetRandomKey() from the POV of the API, but will do more
* work to ensure a better distribution of the returned element.
*
* This function improves the distribution because the dictGetRandomKey()
* problem is that it selects a random bucket, then it selects a random
* element from the chain in the bucket. However elements being in different
* chain lengths will have different probabilities of being reported. With
* this function instead what we do is to consider a "linear" range of the table
* that may be constituted of N buckets with chains of different lengths
* appearing one after the other. Then we report a random element in the range.
* In this way we smooth away the problem of different chain lengths. */
#define GETFAIR_NUM_ENTRIES 15
dictEntry *dictGetFairRandomKey(dict *d) {
dictEntry *entries[GETFAIR_NUM_ENTRIES];
unsigned int count = dictGetSomeKeys(d,entries,GETFAIR_NUM_ENTRIES);
/* Note that dictGetSomeKeys() may return zero elements in an unlucky
* run() even if there are actually elements inside the hash table. So
* when we get zero, we call the true dictGetRandomKey() that will always
* yeld the element if the hash table has at least one. */
if (count == 0) return dictGetRandomKey(d);
unsigned int idx = rand() % count;
return entries[idx];
}
/* Function to reverse bits. Algorithm from:
* http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
static unsigned long rev(unsigned long v) {
unsigned long s = CHAR_BIT * sizeof(v); // bit size; must be power of 2
unsigned long mask = ~0UL;
while ((s >>= 1) > 0) {
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
return v;
}
/* dictScan() is used to iterate over the elements of a dictionary.
*
* Iterating works the following way:
*
* 1) Initially you call the function using a cursor (v) value of 0.
* 2) The function performs one step of the iteration, and returns the
* new cursor value you must use in the next call.
* 3) When the returned cursor is 0, the iteration is complete.
*
* The function guarantees all elements present in the
* dictionary get returned between the start and end of the iteration.
* However it is possible some elements get returned multiple times.
*
* For every element returned, the callback argument 'fn' is
* called with 'privdata' as first argument and the dictionary entry
* 'de' as second argument.
*
* HOW IT WORKS.
*
* The iteration algorithm was designed by Pieter Noordhuis.
* The main idea is to increment a cursor starting from the higher order
* bits. That is, instead of incrementing the cursor normally, the bits
* of the cursor are reversed, then the cursor is incremented, and finally
* the bits are reversed again.
*
* This strategy is needed because the hash table may be resized between
* iteration calls.
*
* dict.c hash tables are always power of two in size, and they
* use chaining, so the position of an element in a given table is given
* by computing the bitwise AND between Hash(key) and SIZE-1
* (where SIZE-1 is always the mask that is equivalent to taking the rest
* of the division between the Hash of the key and SIZE).
*
* For example if the current hash table size is 16, the mask is
* (in binary) 1111. The position of a key in the hash table will always be
* the last four bits of the hash output, and so forth.
*
* WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
*
* If the hash table grows, elements can go anywhere in one multiple of
* the old bucket: for example let's say we already iterated with
* a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).
*
* If the hash table will be resized to 64 elements, then the new mask will
* be 111111. The new buckets you obtain by substituting in ??1100
* with either 0 or 1 can be targeted only by keys we already visited
* when scanning the bucket 1100 in the smaller hash table.
*
* By iterating the higher bits first, because of the inverted counter, the
* cursor does not need to restart if the table size gets bigger. It will
* continue iterating using cursors without '1100' at the end, and also
* without any other combination of the final 4 bits already explored.
*
* Similarly when the table size shrinks over time, for example going from
* 16 to 8, if a combination of the lower three bits (the mask for size 8
* is 111) were already completely explored, it would not be visited again
* because we are sure we tried, for example, both 0111 and 1111 (all the
* variations of the higher bit) so we don't need to test it again.
*
* WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
*
* Yes, this is true, but we always iterate the smaller table first, then
* we test all the expansions of the current cursor into the larger
* table. For example if the current cursor is 101 and we also have a
* larger table of size 16, we also test (0)101 and (1)101 inside the larger
* table. This reduces the problem back to having only one table, where
* the larger one, if it exists, is just an expansion of the smaller one.
*
* LIMITATIONS
*
* This iterator is completely stateless, and this is a huge advantage,
* including no additional memory used.
*
* The disadvantages resulting from this design are:
*
* 1) It is possible we return elements more than once. However this is usually
* easy to deal with in the application level.
* 2) The iterator must return multiple elements per call, as it needs to always
* return all the keys chained in a given bucket, and all the expansions, so
* we are sure we don't miss keys moving during rehashing.
* 3) The reverse cursor is somewhat hard to understand at first, but this
* comment is supposed to help.
*/
unsigned long dictScan(dict *d,
unsigned long v,
dictScanFunction *fn,
dictScanBucketFunction* bucketfn,
void *privdata)
{
dictht *t0, *t1;
const dictEntry *de, *next;
unsigned long m0, m1;
if (dictSize(d) == 0) return 0;
/* Having a safe iterator means no rehashing can happen, see _dictRehashStep.
* This is needed in case the scan callback tries to do dictFind or alike. */
d->iterators++;
if (!dictIsRehashing(d)) {
t0 = &(d->ht[0]);
m0 = t0->sizemask;
/* Emit entries at cursor */
if (bucketfn) bucketfn(privdata, &t0->table[v & m0]);
de = t0->table[v & m0];
while (de) {
next = de->next;
fn(privdata, de);
de = next;
}
/* Set unmasked bits so incrementing the reversed cursor
* operates on the masked bits */
v |= ~m0;
/* Increment the reverse cursor */
v = rev(v);
v++;
v = rev(v);
} else {
t0 = &d->ht[0];
t1 = &d->ht[1];
/* Make sure t0 is the smaller and t1 is the bigger table */
if (t0->size > t1->size) {
t0 = &d->ht[1];
t1 = &d->ht[0];
}
m0 = t0->sizemask;
m1 = t1->sizemask;
/* Emit entries at cursor */
if (bucketfn) bucketfn(privdata, &t0->table[v & m0]);
de = t0->table[v & m0];
while (de) {
next = de->next;
fn(privdata, de);
de = next;
}
/* Iterate over indices in larger table that are the expansion
* of the index pointed to by the cursor in the smaller table */
do {
/* Emit entries at cursor */
if (bucketfn) bucketfn(privdata, &t1->table[v & m1]);
de = t1->table[v & m1];
while (de) {
next = de->next;
fn(privdata, de);
de = next;
}
/* Increment the reverse cursor not covered by the smaller mask.*/
v |= ~m1;
v = rev(v);
v++;
v = rev(v);
/* Continue while bits covered by mask difference is non-zero */
} while (v & (m0 ^ m1));
}
/* undo the ++ at the top */
d->iterators--;
return v;
}
/* ------------------------- private functions ------------------------------ */
/* Expand the hash table if needed */
static int _dictExpandIfNeeded(dict *d)
{
/* Incremental rehashing already in progress. Return. */
if (dictIsRehashing(d)) return DICT_OK;
/* If the hash table is empty expand it to the initial size. */
if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
/* If we reached the 1:1 ratio, and we are allowed to resize the hash
* table (global setting) or we should avoid it but the ratio between
* elements/buckets is over the "safe" threshold, we resize doubling
* the number of buckets. */
if (d->ht[0].used >= d->ht[0].size &&
(dict_can_resize ||
d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
{
return dictExpand(d, d->ht[0].used*2);
}
return DICT_OK;
}
/* Our hash table capability is a power of two */
static unsigned long _dictNextPower(unsigned long size)
{
unsigned long i = DICT_HT_INITIAL_SIZE;
if (size >= LONG_MAX) return LONG_MAX + 1LU;
while(1) {
if (i >= size)
return i;
i *= 2;
}
}
/* Returns the index of a free slot that can be populated with
* a hash entry for the given 'key'.
* If the key already exists, -1 is returned
* and the optional output parameter may be filled.
*
* Note that if we are in the process of rehashing the hash table, the
* index is always returned in the context of the second (new) hash table. */
static long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **existing)
{
unsigned long idx, table;
dictEntry *he;
if (existing) *existing = NULL;
/* Expand the hash table if needed */
if (_dictExpandIfNeeded(d) == DICT_ERR)
return -1;
for (table = 0; table <= 1; table++) {
idx = hash & d->ht[table].sizemask;
/* Search if this slot does not already contain the given key */
he = d->ht[table].table[idx];
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key)) {
if (existing) *existing = he;
return -1;
}
he = he->next;
}
if (!dictIsRehashing(d)) break;
}
return idx;
}
void dictEmpty(dict *d, void(callback)(void*)) {
_dictClear(d,&d->ht[0],callback);
_dictClear(d,&d->ht[1],callback);
d->rehashidx = -1;
d->iterators = 0;
}
void dictEnableResize(void) {
dict_can_resize = 1;
}
void dictDisableResize(void) {
dict_can_resize = 0;
}
uint64_t dictGetHash(dict *d, const void *key) {
return dictHashKey(d, key);
}
/* Finds the dictEntry reference by using pointer and pre-calculated hash.
* oldkey is a dead pointer and should not be accessed.
* the hash value should be provided using dictGetHash.
* no string / key comparison is performed.
* return value is the reference to the dictEntry if found, or NULL if not found. */
dictEntry **dictFindEntryRefByPtrAndHash(dict *d, const void *oldptr, uint64_t hash) {
dictEntry *he, **heref;
unsigned long idx, table;
if (dictSize(d) == 0) return NULL; /* dict is empty */
for (table = 0; table <= 1; table++) {
idx = hash & d->ht[table].sizemask;
heref = &d->ht[table].table[idx];
he = *heref;
while(he) {
if (oldptr==he->key)
return heref;
heref = &he->next;
he = *heref;
}
if (!dictIsRehashing(d)) return NULL;
}
return NULL;
}
/* ------------------------------- Debugging ---------------------------------*/
#define DICT_STATS_VECTLEN 50
size_t _dictGetStatsHt(char *buf, size_t bufsize, dictht *ht, int tableid) {
unsigned long i, slots = 0, chainlen, maxchainlen = 0;
unsigned long totchainlen = 0;
unsigned long clvector[DICT_STATS_VECTLEN];
size_t l = 0;
if (ht->used == 0) {
return snprintf(buf,bufsize,
"No stats available for empty dictionaries\n");
}
/* Compute stats. */
for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
for (i = 0; i < ht->size; i++) {
dictEntry *he;
if (ht->table[i] == NULL) {
clvector[0]++;
continue;
}
slots++;
/* For each hash entry on this slot... */
chainlen = 0;
he = ht->table[i];
while(he) {
chainlen++;
he = he->next;
}
clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
if (chainlen > maxchainlen) maxchainlen = chainlen;
totchainlen += chainlen;
}
/* Generate human readable stats. */
l += snprintf(buf+l,bufsize-l,
"Hash table %d stats (%s):\n"
" table size: %ld\n"
" number of elements: %ld\n"
" different slots: %ld\n"
" max chain length: %ld\n"
" avg chain length (counted): %.02f\n"
" avg chain length (computed): %.02f\n"
" Chain length distribution:\n",
tableid, (tableid == 0) ? "main hash table" : "rehashing target",
ht->size, ht->used, slots, maxchainlen,
(float)totchainlen/slots, (float)ht->used/slots);
for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
if (clvector[i] == 0) continue;
if (l >= bufsize) break;
l += snprintf(buf+l,bufsize-l,
" %s%ld: %ld (%.02f%%)\n",
(i == DICT_STATS_VECTLEN-1)?">= ":"",
i, clvector[i], ((float)clvector[i]/ht->size)*100);
}
/* Unlike snprintf(), return the number of characters actually written. */
if (bufsize) buf[bufsize-1] = '\0';
return strlen(buf);
}
void dictGetStats(char *buf, size_t bufsize, dict *d) {
size_t l;
char *orig_buf = buf;
size_t orig_bufsize = bufsize;
l = _dictGetStatsHt(buf,bufsize,&d->ht[0],0);
buf += l;
bufsize -= l;
if (dictIsRehashing(d) && bufsize > 0) {
_dictGetStatsHt(buf,bufsize,&d->ht[1],1);
}
/* Make sure there is a NULL term at the end. */
if (orig_bufsize) orig_buf[orig_bufsize-1] = '\0';
}
/* ------------------------------- Benchmark ---------------------------------*/
#ifdef DICT_BENCHMARK_MAIN
#include "sds.h"
uint64_t hashCallback(const void *key) {
return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
}
int compareCallback(void *privdata, const void *key1, const void *key2) {
int l1,l2;
DICT_NOTUSED(privdata);
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
void freeCallback(void *privdata, void *val) {
DICT_NOTUSED(privdata);
sdsfree(val);
}
dictType BenchmarkDictType = {
hashCallback,
NULL,
NULL,
compareCallback,
freeCallback,
NULL
};
#define start_benchmark() start = timeInMilliseconds()
#define end_benchmark(msg) do { \
elapsed = timeInMilliseconds()-start; \
printf(msg ": %ld items in %lld ms\n", count, elapsed); \
} while(0);
/* dict-benchmark [count] */
int main(int argc, char **argv) {
long j;
long long start, elapsed;
dict *dict = dictCreate(&BenchmarkDictType,NULL);
long count = 0;
if (argc == 2) {
count = strtol(argv[1],NULL,10);
} else {
count = 5000000;
}
start_benchmark();
for (j = 0; j < count; j++) {
int retval = dictAdd(dict,sdsfromlonglong(j),(void*)j);
assert(retval == DICT_OK);
}
end_benchmark("Inserting");
assert((long)dictSize(dict) == count);
/* Wait for rehashing. */
while (dictIsRehashing(dict)) {
dictRehashMilliseconds(dict,100);
}
start_benchmark();
for (j = 0; j < count; j++) {
sds key = sdsfromlonglong(j);
dictEntry *de = dictFind(dict,key);
assert(de != NULL);
sdsfree(key);
}
end_benchmark("Linear access of existing elements");
start_benchmark();
for (j = 0; j < count; j++) {
sds key = sdsfromlonglong(j);
dictEntry *de = dictFind(dict,key);
assert(de != NULL);
sdsfree(key);
}
end_benchmark("Linear access of existing elements (2nd round)");
start_benchmark();
for (j = 0; j < count; j++) {
sds key = sdsfromlonglong(rand() % count);
dictEntry *de = dictFind(dict,key);
assert(de != NULL);
sdsfree(key);
}
end_benchmark("Random access of existing elements");
start_benchmark();
for (j = 0; j < count; j++) {
dictEntry *de = dictGetRandomKey(dict);
assert(de != NULL);
}
end_benchmark("Accessing random keys");
start_benchmark();
for (j = 0; j < count; j++) {
sds key = sdsfromlonglong(rand() % count);
key[0] = 'X';
dictEntry *de = dictFind(dict,key);
assert(de == NULL);
sdsfree(key);
}
end_benchmark("Accessing missing");
start_benchmark();
for (j = 0; j < count; j++) {
sds key = sdsfromlonglong(j);
int retval = dictDelete(dict,key);
assert(retval == DICT_OK);
key[0] += 17; /* Change first number to letter. */
retval = dictAdd(dict,key,(void*)j);
assert(retval == DICT_OK);
}
end_benchmark("Removing and adding");
}
#endif
|
657660.c | /*
* @Author: JunQiLiu
* @Date: 2021-09-11 09:20:34
* @LastEditTime: 2021-09-18 01:35:58
* @Description:
* @FilePath: \stm32f401ccu6_rtthread\applications\modbus_slave_app.c
*
*/
#include "modbus_slave_app.h"
#define LOG_TAG "MB_Slave"
#define LOG_LVL LOG_LVL_DBG
#include <ulog.h>
#define SLAVE_ADDR 81
#define PORT_NUM 2
#define PORT_BAUDRATE 9600
#define PORT_PARITY MB_PAR_NONE
#define MB_POLL_THREAD_PRIORITY 10
#define MB_SEND_THREAD_PRIORITY RT_THREAD_PRIORITY_MAX - 1
#define MB_POLL_CYCLE_MS 50
extern USHORT usSRegHoldBuf[S_REG_HOLDING_NREGS];
static void send_thread_entry(void *parameter)
{
USHORT *usRegHoldingBuf;
usRegHoldingBuf = usSRegHoldBuf;
rt_base_t level;
while (1)
{
/* Test Modbus Master */
level = rt_hw_interrupt_disable();
usRegHoldingBuf[3] = (USHORT)(rt_tick_get() / 100);
rt_hw_interrupt_enable(level);
rt_thread_mdelay(1000);
}
}
static void mb_slave_poll(void *parameter)
{
uint8_t ucSlaveAddr = usSRegHoldBuf[1];\
uint8_t readBuf[8];
rt_base_t level;
if (rt_strstr(parameter, "RTU"))
{
#ifdef PKG_MODBUS_SLAVE_RTU
eMBInit(MB_RTU, ucSlaveAddr, PORT_NUM, PORT_BAUDRATE, PORT_PARITY);
LOG_D("Modbus RTU Slave Init");
#else
rt_kprintf("Error: Please open RTU mode first");
#endif
}
else if (rt_strstr(parameter, "ASCII"))
{
#ifdef PKG_MODBUS_SLAVE_ASCII
eMBInit(MB_ASCII, SLAVE_ADDR, PORT_NUM, PORT_BAUDRATE, PORT_PARITY);
#else
rt_kprintf("Error: Please open ASCII mode first");
#endif
}
else if (rt_strstr(parameter, "TCP"))
{
#ifdef PKG_MODBUS_SLAVE_TCP
eMBTCPInit(0);
#else
rt_kprintf("Error: Please open TCP mode first");
#endif
}
else
{
rt_kprintf("Error: unknown parameter");
}
eMBEnable();
while (1)
{
eMBPoll();
if(ucSlaveAddr != usSRegHoldBuf[1])
{
level = rt_hw_interrupt_disable();
fal_partition_read(fal_partition_find("ef"),0,readBuf,8);
fal_partition_erase(fal_partition_find("ef"),0,8);
readBuf[0] = usSRegHoldBuf[1];
fal_partition_write(fal_partition_find("ef"),0,readBuf,8);
rt_hw_interrupt_enable(level);
rt_hw_cpu_reset();
}
rt_thread_mdelay(MB_POLL_CYCLE_MS);
}
}
int modbusSlaveAppStart(void)
{
rt_thread_t tid1 = RT_NULL;//, tid2 = RT_NULL;
tid1 = rt_thread_create("md_s_poll", mb_slave_poll, "RTU", 1024, MB_POLL_THREAD_PRIORITY, 10);
if (tid1 != RT_NULL)
{
rt_thread_startup(tid1);
}
else
{
goto __exit;
}
// tid2 = rt_thread_create("md_s_send", send_thread_entry, RT_NULL, 512, MB_SEND_THREAD_PRIORITY, 10);
// if (tid2 != RT_NULL)
// {
// rt_thread_startup(tid2);
// }
// else
// {
// goto __exit;
// }
return RT_EOK;
__exit:
if (tid1)
rt_thread_delete(tid1);
// if (tid2)
// rt_thread_delete(tid2);
return -RT_ERROR;
}
|
963684.c | #include <arpa/inet.h> /* inet_ntoa */
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define LISTENQ 1024 /* second argument to listen() */
#define MAXLINE 1024 /* max length of a line */
#define RIO_BUFSIZE 1024
#ifndef DEFAULT_PORT
#define DEFAULT_PORT 9999 /* use this port if none given as arg to main() */
#endif
#ifndef FORK_COUNT
#define FORK_COUNT 4
#endif
#ifndef NO_LOG_ACCESS
#define LOG_ACCESS
#endif
typedef struct {
int rio_fd; /* descriptor for this buf */
int rio_cnt; /* unread byte in this buf */
char *rio_bufptr; /* next unread byte in this buf */
char rio_buf[RIO_BUFSIZE]; /* internal buffer */
} rio_t;
/* Simplifies calls to bind(), connect(), and accept() */
typedef struct sockaddr SA;
typedef struct {
char filename[512];
off_t offset; /* for support Range */
size_t end;
} http_request;
typedef struct {
const char *extension;
const char *mime_type;
} mime_map;
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
mime_map meme_types[] = {
{".aac", "audio/aac"},
{".abw", "application/x-abiword"},
{".arc", "application/x-freearc"},
{".avi", "video/x-msvideo"},
{".azw", "application/vnd.amazon.ebook"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".bz", "application/x-bzip"},
{".bz2", "application/x-bzip2"},
{".csh", "application/x-csh"},
{".css", "text/css"},
{".csv", "text/csv"},
{".doc", "application/msword"},
{".docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".eot", "application/vnd.ms-fontobject"},
{".epub", "application/epub+zip"},
{".gz", "application/gzip"},
{".gif", "image/gif"},
{".htm", "text/html"},
{".html", "text/html"},
{".ico", "image/vnd.microsoft.icon"},
{".ics", "text/calendar"},
{".jar", "application/java-archive"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "text/javascript"},
{".json", "application/json"},
{".jsonld", "application/ld+json"},
{".mid", "audio/midi audio/x-midi"},
{".midi", "audio/midi audio/x-midi"},
{".mjs", "text/javascript"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mpeg", "video/mpeg"},
{".mpkg", "application/vnd.apple.installer+xml"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".oga", "audio/ogg"},
{".ogv", "video/ogg"},
{".ogx", "application/ogg"},
{".opus", "audio/opus"},
{".otf", "font/otf"},
{".png", "image/png"},
{".pdf", "application/pdf"},
{".php", "application/x-httpd-php"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx",
"application/"
"vnd.openxmlformats-officedocument.presentationml.presentation"},
{".rar", "application/vnd.rar"},
{".rtf", "application/rtf"},
{".sh", "application/x-sh"},
{".svg", "image/svg+xml"},
{".swf", "application/x-shockwave-flash"},
{".tar", "application/x-tar"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".ts", "video/mp2t"},
{".ttf", "font/ttf"},
{".txt", "text/plain"},
{".vsd", "application/vnd.visio"},
{".wav", "audio/wav"},
{".weba", "audio/webm"},
{".webm", "video/webm"},
{".webp", "image/webp"},
{".woff", "font/woff"},
{".woff2", "font/woff2"},
{".xhtml", "application/xhtml+xml"},
{".xls", "application/vnd.ms-excel"},
{".xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xml", "text/xml"},
{".xul", "application/vnd.mozilla.xul+xml"},
{".zip", "application/zip"},
{".3gp", "video/3gpp"},
{".3g2", "video/3gpp2"},
{".7z", "application/x-7z-compressed"},
{NULL, NULL},
};
char *default_mime_type = "text/plain";
void rio_readinitb(rio_t *rp, int fd)
{
rp->rio_fd = fd;
rp->rio_cnt = 0;
rp->rio_bufptr = rp->rio_buf;
}
/*
* rio_read - This is a wrapper for the Unix read() function that
* transfers min(n, rio_cnt) bytes from an internal buffer to a user
* buffer, where n is the number of bytes requested by the user and
* rio_cnt is the number of unread bytes in the internal buffer. On
* entry, rio_read() refills the internal buffer via a call to
* read() if the internal buffer is empty.
*/
/* $begin rio_read */
static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n)
{
int cnt;
while (rp->rio_cnt <= 0) { /* refill if buf is empty */
rp->rio_cnt = read(rp->rio_fd, rp->rio_buf, sizeof(rp->rio_buf));
if (rp->rio_cnt < 0) {
if (errno != EINTR) { /* interrupted by sig handler return */
return -1;
}
} else if (rp->rio_cnt == 0) { /* EOF */
return 0;
} else
rp->rio_bufptr = rp->rio_buf; /* reset buffer ptr */
}
/* Copy min(n, rp->rio_cnt) bytes from internal buf to user buf */
cnt = n;
if (rp->rio_cnt < n) {
cnt = rp->rio_cnt;
}
memcpy(usrbuf, rp->rio_bufptr, cnt);
rp->rio_bufptr += cnt;
rp->rio_cnt -= cnt;
return cnt;
}
ssize_t writen(int fd, void *usrbuf, size_t n)
{
size_t nleft = n;
char *bufp = usrbuf;
while (nleft > 0) {
ssize_t nwritten = write(fd, bufp, nleft);
if (nwritten <= 0) {
if (errno == EINTR) { /* interrupted by sig handler return */
nwritten = 0; /* and call write() again */
} else {
return -1; /* errorno set by write() */
}
}
nleft -= nwritten;
bufp += nwritten;
}
return n;
}
/*
* rio_readlineb - robustly read a text line (buffered)
*/
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
int n;
char c, *bufp = usrbuf;
for (n = 1; n < maxlen; n++) {
int rc;
if ((rc = rio_read(rp, &c, 1)) == 1) {
*bufp++ = c;
if (c == '\n') {
break;
}
} else if (rc == 0) {
if (n == 1) {
return 0; /* EOF, no data read */
} else {
break; /* EOF, some data was read */
}
} else {
return -1; /* error */
}
}
*bufp = 0;
return n;
}
static const char *get_mime_type(char *filename)
{
char *dot = strrchr(filename, '.');
if (dot) { // strrchar Locate last occurrence of character in string
mime_map *map = meme_types;
while (map->extension) {
if (strcmp(map->extension, dot) == 0) {
return map->mime_type;
}
map++;
}
}
return default_mime_type;
}
void send_response(int out_fd)
{
char *buf =
"HTTP/1.1 200 OK\r\n%s%s%s%s%s%s"
"Content-Type: text/html\r\n\r\n"
"<html><head><style>"
"body{font-family: monospace; font-size: 13px;}"
"td {padding: 1.5px 6px;}"
"</style><link rel=\"shortcut icon\" href=\"#\">"
"</head><body><table>\n";
writen(out_fd, buf, strlen(buf));
}
int open_listenfd(int port)
{
int listenfd, optval = 1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return -1;
}
/* Eliminates "Address already in use" error from bind. */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *) &optval,
sizeof(int)) < 0) {
return -1;
}
// 6 is TCP's protocol number
// enable this, much faster : 4000 req/s -> 17000 req/s
if (setsockopt(listenfd, 6, TCP_CORK, (const void *) &optval, sizeof(int)) <
0) {
return -1;
}
/* Listenfd will be an endpoint for all requests to port
on any IP address for this host */
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short) port);
if (bind(listenfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0) {
return -1;
}
/* Make it a listening socket ready to accept connection requests */
if (listen(listenfd, LISTENQ) < 0) {
return -1;
}
return listenfd;
}
void url_decode(char *src, char *dest, int max)
{
char *p = src;
char code[3] = {0};
while (*p && --max) {
if (*p == '%') {
memcpy(code, ++p, 2);
*dest++ = (char) strtoul(code, NULL, 16);
p += 2;
} else {
*dest++ = *p++;
}
}
*dest = '\0';
}
void parse_request(int fd, http_request *req)
{
rio_t rio;
char buf[MAXLINE], method[MAXLINE], uri[MAXLINE];
req->offset = 0;
req->end = 0; /* default */
rio_readinitb(&rio, fd);
rio_readlineb(&rio, buf, MAXLINE);
sscanf(buf, "%1023s %1023s", method, uri); /* version is not cared */
/* read all */
while (buf[0] != '\n' && buf[1] != '\n') { /* \n || \r\n */
rio_readlineb(&rio, buf, MAXLINE);
if (buf[0] == 'R' && buf[1] == 'a' && buf[2] == 'n') {
sscanf(buf, "Range: bytes=%lu-%lu", (unsigned long *) &req->offset,
(unsigned long *) &req->end);
// Range: [start, end]
if (req->end != 0) {
req->end++;
}
}
}
char *filename = uri;
if (uri[0] == '/') {
filename = uri + 1;
int length = strlen(filename);
if (length == 0) {
filename = ".";
} else {
int i = 0;
for (; i < length; ++i) {
if (filename[i] == '?') {
filename[i] = '\0';
break;
}
}
}
}
url_decode(filename, req->filename, MAXLINE);
}
#ifdef LOG_ACCESS
void log_access(int status, struct sockaddr_in *c_addr, http_request *req)
{
printf("%s:%d %d - '%s' (%s)\n", inet_ntoa(c_addr->sin_addr),
ntohs(c_addr->sin_port), status, req->filename,
get_mime_type(req->filename));
}
#endif
char *process(int fd, struct sockaddr_in *clientaddr)
{
#ifdef LOG_ACCESS
printf("accept request, fd is %d, pid is %d\n", fd, getpid());
#endif
http_request req;
parse_request(fd, &req);
int status = 200;
char *p = req.filename;
/* Change '/' to ' ' */
while (*p) {
++p;
if (*p == '/') {
*p = ' ';
}
}
#ifdef LOG_ACCESS
log_access(status, clientaddr, &req);
#endif
char *ret = malloc(strlen(req.filename) + 1);
strncpy(ret, req.filename, strlen(req.filename) + 1);
send_response(fd);
return ret;
}
|
318339.c | /*
COPYRIGHT XionBot Developement Team 2003 - 2005
http://xionbot.sourceforge.net
Licensed under the (Open Source) GNU Public License (GPL).
A copy of the GPL license should have been supplied.
http://www.gnu.org/licenses/gpl.txt
*/
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#include "irc_channel.h"
#include "irc_user.h"
struct userNode* user_get_handle(char *nick) {
struct userNode *user;
if(blankstr(nick))
return NULL;
for(user = user_first;user != NULL;user = user->next) {
if(istrcmp(user->nick, nick))
return user;
}
return NULL;
}
static void init_user_struct(struct userNode *user) {
user->next = NULL;
user->prev = NULL;
user->chanlist_first = NULL;
user->chanlist_last = NULL;
clearstr(user->host, MAX_MASKLEN);
clearstr(user->hostmask, MAX_HOSTMASKLEN);
clearstr(user->info, MAX_INFOLEN);
clearstr(user->nick, MAX_NICKLEN);
clearstr(user->user, MAX_USERLEN);
user->user_mode = 0;
user->chan_count = 0;
return ;
}
struct userNode* user_adduser(char *nick) {
struct userNode *user;
if(blankstr(nick))
return NULL;
if(user_get_handle(nick))
return NULL;
user = (struct userNode*)mallocm(sizeof(struct userNode));
if(user == NULL)
return NULL;
init_user_struct(user);
xstrcpy(user->nick, nick, MAX_MSGLEN);
if(istrcmp(user->nick, bot.current_nick))
me = user;
LL_ADDNODE(user, user_first, user_last)
user_count++;
return user;
}
unsigned int user_deluser(struct userNode *user) {
struct chanlist *hChanList;
if(user == NULL)
return 0;
/* Remove the user from each channel's user list
then recycle user's own channel list. */
for(hChanList = user->chanlist_first;hChanList != NULL;hChanList = hChanList->next)
chan_del_chanuser(hChanList->chanuser_info);
user_free_chanlist(user);
LL_DELNODE(user, user_first, user_last)
user_count--;
freem(user);
return 1;
}
struct chanlist* user_get_chanlist(struct userNode *user, struct chanNode *chan) {
struct chanlist *hChanList;
if((user == NULL) || (chan == NULL))
return NULL;
for(hChanList = user->chanlist_first;hChanList != NULL;hChanList = hChanList->next) {
if(istrcmp(hChanList->chan->name, chan->name))
return hChanList;
}
return NULL;
}
struct chanlist* user_add_userchan(struct userNode *user, struct chanNode *chan) {
struct chanlist *hChanList;
if((user == NULL) || (chan == NULL))
return NULL;
if(user_get_chanlist(user, chan))
return NULL;
hChanList = (struct chanlist*)mallocm(sizeof(struct chanlist));
if(!hChanList)
return NULL;
hChanList->next = NULL;
hChanList->prev = NULL;
hChanList->user = user;
hChanList->chan = chan;
hChanList->chanuser_info = NULL;
LL_ADDNODE(hChanList, user->chanlist_first, user->chanlist_last)
user->chan_count++;
return hChanList;
}
unsigned int user_del_userchan(struct chanlist *hChanList) {
struct userNode *user;
if(hChanList == NULL)
return 0;
user = hChanList->user;
if(user == NULL)
return 0;
LL_DELNODE(hChanList, user->chanlist_first, user->chanlist_last)
user->chan_count--;
freem(hChanList);
return 1;
}
unsigned int user_fillmask(struct userNode *user, char *hostmask) {
unsigned int i, x, len, len2, len3;
if((user == NULL) || (blankstr(hostmask)))
return 0;
len = strlen(hostmask);
len2 = strlen(user->nick);
for(i = len2+1, x = 0;x < (len2+MAX_USERLEN);i++, x++) {
if(hostmask[i] == '@')
break;
user->user[x] = hostmask[i];
}
user->user[x] = 0;
len3 = len2+strlen(user->user)+2;
for(x = 0, i++;x < (len3+MAX_MASKLEN);i++, x++) {
if(!hostmask[i])
break;
user->host[x] = hostmask[i];
}
user->host[x] = 0;
xstrcpy(user->hostmask, hostmask, MAX_HOSTMASKLEN);
return 1;
}
void user_free_chanlist(struct userNode *user) {
struct chanlist *temp_list, *temp_list2;
temp_list = user->chanlist_last;
while(temp_list != NULL) {
temp_list2 = temp_list->prev;
freem(temp_list);
if(temp_list2 == NULL) break;
temp_list2->next = NULL;
temp_list = temp_list2;
}
user->chanlist_first = NULL;
user->chanlist_last = NULL;
user->chan_count = 0;
return ;
}
void user_free_data(void) {
struct userNode *temp_user, *temp_user2;
temp_user = user_last;
while(temp_user != NULL) {
temp_user2 = temp_user->prev;
user_free_chanlist(temp_user);
freem(temp_user);
if(temp_user2 == NULL) break;
temp_user2->next = NULL;
temp_user = temp_user2;
}
user_first = NULL;
user_last = NULL;
user_count = 0;
return ;
}
|
417432.c | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <pyexceptions.h>
#include <pyutils.h>
#include <java_class/Exception.h>
#include <java_class/Throwable.h>
#include <java_class/StackTraceElement.h>
int
JcpPyErr_Throw(JNIEnv* env)
{
PyObject *type, *value, *traceback;
PyObject *args;
PyObject *message;
PyObject *type_str, *value_str;
PyObject *traceback_module;
PyObject *extract_method;
PyObject *pymsg = NULL;
PyObject *pystack = NULL;
jobject jpyexception = NULL;
if (!PyErr_Occurred()) {
return 0;
}
PyErr_Fetch(&type, &value, &traceback);
if (type) {
// get the message of exception.
if (PyObject_TypeCheck(value, (PyTypeObject*) PyExc_BaseException)) {
args = PyObject_GetAttrString(value, "args");
if (args != NULL && PyTuple_Check(args) && PyTuple_Size(args) > 0) {
message = PyTuple_GetItem(args, 0);
Py_INCREF(message);
Py_DECREF(value);
Py_DECREF(args);
value = message;
}
}
type_str = PyObject_Str(type);
value_str = PyObject_Str(value);
if (value_str != NULL && PyUnicode_Check(value_str)) {
pymsg = PyUnicode_FromFormat("%U: %U", type_str, value_str);
Py_DECREF(type_str);
Py_DECREF(value_str);
}
jpyexception = JavaPythonException_New(env, JcpPyString_AsJString(env, pymsg));
if (traceback) {
traceback_module = PyImport_ImportModule("traceback");
if (traceback_module == NULL) {
printf("Failed to import `traceback` module\n");
}
extract_method = PyUnicode_FromString("extract_tb");
if (traceback_module != NULL && extract_method != NULL) {
pystack = PyObject_CallMethodObjArgs(traceback_module, extract_method,
traceback, NULL);
}
if (PyErr_Occurred()) {
PyErr_Print();
}
Py_XDECREF(traceback_module);
Py_XDECREF(extract_method);
}
if (pystack != NULL) {
jsize stackSize = (jsize) PyList_Size(pystack);
jobjectArray stack_elements = (*env)->NewObjectArray(env, stackSize,
JSTACK_TRACE_ELEMENT_TYPE, NULL);
if ((*env)->ExceptionCheck(env) || !stack_elements) {
PyErr_Format(PyExc_RuntimeError, "Failed to create stack_elements.");
Py_DECREF(pystack);
return 1;
}
for (int i = 0; i < stackSize; i++) {
PyObject* stack_frame = PyList_GetItem(pystack, i);
// self.filename, self.lineno, self.name, self.line
const char* frame_filename = PyUnicode_AsUTF8(PySequence_GetItem(stack_frame, 0));
int frame_lineno = (int) PyLong_AsLong(PySequence_GetItem(stack_frame, 1));
const char* frame_func_name = PyUnicode_AsUTF8(PySequence_GetItem(stack_frame, 2));
PyObject* frame_line = PySequence_GetItem(stack_frame, 3);
if (frame_line != Py_None) {
int name_size = strlen(frame_filename);
// create the file name without `.py` suffix.
char* frame_filename_no_suffix = malloc(sizeof(char) * (name_size + 1));
strcpy(frame_filename_no_suffix, frame_filename);
char* lastDot = strrchr(frame_filename_no_suffix, '.');
if (lastDot != NULL) {
*lastDot = '\0';
}
// create the file name without directory prefix.
char* frame_filename_no_dir = malloc(sizeof(char) * (name_size + 1));
char* lastFileSep = strrchr(frame_filename, '/');
if (lastFileSep != NULL) {
strcpy(frame_filename_no_dir, lastFileSep + 1);
} else {
strcpy(frame_filename_no_dir, frame_filename);
}
jstring jframe_filename_no_dir = (*env)->NewStringUTF(env,
frame_filename_no_dir);
jstring jframe_file_no_suffix = (*env)->NewStringUTF(env,
frame_filename_no_suffix);
jstring jframe_func_name = (*env)->NewStringUTF(env, frame_func_name);
jobject stack_trace_element = JavaStackTraceElement_New(env,
jframe_file_no_suffix,
jframe_func_name,
jframe_filename_no_dir,
frame_lineno);
if ((*env)->ExceptionCheck(env) || !stack_trace_element) {
PyErr_Format(PyExc_RuntimeError,
"Failed to create `StackTraceElement` for %s:%i.",
frame_func_name, frame_line);
free(frame_filename_no_suffix);
free(frame_filename_no_dir);
Py_DECREF(pystack);
return 1;
}
(*env)->SetObjectArrayElement(env, stack_elements, i, stack_trace_element);
free(frame_filename_no_suffix);
free(frame_filename_no_dir);
(*env)->DeleteLocalRef(env, jframe_filename_no_dir);
(*env)->DeleteLocalRef(env, jframe_file_no_suffix);
(*env)->DeleteLocalRef(env, jframe_func_name);
(*env)->DeleteLocalRef(env, stack_trace_element);
}
}
Py_DECREF(pystack);
jobjectArray jstack = JavaThrowable_getStackTrace(env, jpyexception);
jsize jstack_length = (*env)->GetArrayLength(env, jstack);
// create a new stack including python stack.
jobjectArray reverse_jstack = (*env)->NewObjectArray(env,
(jsize) (stackSize + jstack_length),
JSTACK_TRACE_ELEMENT_TYPE,
NULL);
for (int i = stackSize - 1; i > -1; i--) {
jobject stack_trace_element = (*env)->GetObjectArrayElement(env, stack_elements, i);
if (stack_trace_element != NULL) {
(*env)->SetObjectArrayElement(env, reverse_jstack, i, stack_trace_element);
(*env)->DeleteLocalRef(env, stack_trace_element);
}
}
for (int i = 0; i < jstack_length; i++) {
jobject stack_trace_element = (*env)->GetObjectArrayElement(env, jstack, i);
if (stack_trace_element != NULL) {
(*env)->SetObjectArrayElement(env, reverse_jstack, i + stackSize,
stack_trace_element);
(*env)->DeleteLocalRef(env, stack_trace_element);
}
}
(*env)->DeleteLocalRef(env, jstack);
(*env)->DeleteLocalRef(env, stack_elements);
JavaThrowable_setStackTrace(env, jpyexception, reverse_jstack);
if ((*env)->ExceptionCheck(env)) {
fprintf(stderr,
"Error while throwing a Python exception, unexpected java exception.\n");
PyErr_Restore(type, value, traceback);
PyErr_Print();
return 1;
}
(*env)->DeleteLocalRef(env, reverse_jstack);
}
}
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
if (jpyexception != NULL) {
(*env)->Throw(env, jpyexception);
}
return 1;
}
|
430374.c | void
out( char c ) {
*((char*) 0x20000) = c;
}
//#include <stdio.h>
//#define out( c ) putchar( c )
void
print( char* s ) {
while (*s)
out( *s++ );
}
void
println( char* s ) {
print( s );
out( '\n' );
}
char*
bin2str( short n, int radix, char* buf ) {
char digits[] = "0123456789ABCDEF";
char* p = &buf[33];
short quo = n;
if (n < 0)
quo = -quo;
*p-- = 0;
while (quo >= radix) {
*p-- = digits[(quo%radix)];
quo /= radix;
}
*p = digits[quo];
if (n < 0)
*--p = '-';
return p;
}
void
sort( short a[], int left, int right ) {
if (right > left) {
int i = left;
int j = right;
short tmp = 0;
short p = a[right];
do {
while (a[i] < p)
i++;
while (a[j] > p)
j--;
if (i <= j) {
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
} while (i <= j);
if (left < j)
sort( a, left, j );
if (i < right)
sort( a, i, right );
}
}
void
run( short array[], int size ) {
sort( array, 0, size - 1 );
print( "[" );
for (int i = 0; i < size; i++) {
char buf[34];
char* s = bin2str( array[i], 10, buf );
print( s );
if (i < size - 1)
print( ", " );
}
println( "]" );
}
void
main() {
run( (short[]){10, 9, 8, 7, 7, 7, 7, 3, 2, 1}, 10 );
run( (short[]){10, 9, 8, 7, 7, 5, 7, 3, 2, 1}, 10 );
run( (short[]){10, 9, 8, 7, 5, 7, 4, 3, 2, 1}, 10 );
run( (short[]){10, 9}, 2 );
run( (short[]){10}, 1 );
run( (short[]){}, 0 );
} |
69437.c | //
// BRHederaSerialize.c
//
// Created by Carl Cherry on Oct. 17, 2019.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
#include "BRHederaSerialize.h"
#include "BRHederaAddress.h"
#include "proto/Transaction.pb-c.h"
#include "proto/TransactionBody.pb-c.h"
#include <stdlib.h>
const size_t max_memo_size = 100L;
Proto__AccountID * createAccountID (BRHederaAddress address)
{
Proto__AccountID *protoAccountID = calloc(1, sizeof(Proto__AccountID));
proto__account_id__init(protoAccountID);
protoAccountID->shardnum = hederaAddressGetShard (address);
protoAccountID->realmnum = hederaAddressGetRealm (address);
protoAccountID->accountnum = hederaAddressGetAccount (address);
return protoAccountID;
}
Proto__Timestamp * createTimeStamp (BRHederaTimeStamp timeStamp)
{
Proto__Timestamp *ts = calloc(1, sizeof(Proto__Timestamp));
proto__timestamp__init(ts);
ts->seconds = timeStamp.seconds;
ts->nanos = timeStamp.nano;
return ts;
}
Proto__TransactionID * createProtoTransactionID (BRHederaAddress address, BRHederaTimeStamp timeStamp)
{
Proto__TransactionID *txID = calloc(1, sizeof(Proto__TransactionID));
proto__transaction_id__init(txID);
txID->transactionvalidstart = createTimeStamp(timeStamp);
txID->accountid = createAccountID(address);
return txID;
}
Proto__Duration * createTransactionDuration(int64_t seconds)
{
Proto__Duration * duration = calloc(1, sizeof(Proto__Duration));
proto__duration__init(duration);
duration->seconds = seconds;
return duration;
}
Proto__AccountAmount * createAccountAmount (BRHederaAddress address, int64_t amount)
{
Proto__AccountAmount * accountAmount = calloc(1, sizeof(Proto__AccountAmount));
proto__account_amount__init(accountAmount);
accountAmount->accountid = createAccountID(address);
accountAmount->amount = amount;
return accountAmount;
}
uint8_t * hederaTransactionBodyPack (BRHederaAddress source,
BRHederaAddress target,
BRHederaAddress nodeAddress,
BRHederaUnitTinyBar amount,
BRHederaTimeStamp timeStamp,
BRHederaUnitTinyBar fee,
const char * memo,
size_t *size)
{
Proto__TransactionBody *body = calloc(1, sizeof(Proto__TransactionBody));
proto__transaction_body__init(body);
// Create a transaction ID
body->transactionid = createProtoTransactionID(source, timeStamp);
body->nodeaccountid = createAccountID(nodeAddress);
body->transactionfee = (uint64_t)fee;
// Docs say the limit of 100 is enforced. The max size of not defined
// in the .proto file so I guess we just have to trust that it is string with max 100 chars
if (memo) body->memo = strndup(memo, max_memo_size);
// Set the duration
// *** NOTE 1 *** if the transaction is unable to be verified in this
// duration then it will fail. The default value in the Hedera Java SDK
// is 120. I have set ours to 180 since it requires a couple of extra hops
// *** NOTE 2 *** if you change this value then it will break the unit tests
// since it will change the serialized bytes.
body->transactionvalidduration = createTransactionDuration(180);
// We are creating a "Cryto Transfer" transaction which has a transfer list
body->data_case = PROTO__TRANSACTION_BODY__DATA_WK_TRANSFER;
body->cryptotransfer = calloc(1, sizeof(Proto__CryptoTransferTransactionBody));
proto__crypto_transfer_transaction_body__init(body->cryptotransfer);
body->cryptotransfer->transfers = calloc(1, sizeof(Proto__TransferList));
proto__transfer_list__init(body->cryptotransfer->transfers);
// We are only supporting sending from A to B at this point - so create 2 transfers
body->cryptotransfer->transfers->n_accountamounts = 2;
body->cryptotransfer->transfers->accountamounts = calloc(2, sizeof(Proto__AccountAmount*));
// NOTE - the amounts in the transfer MUST add up to 0
body->cryptotransfer->transfers->accountamounts[0] = createAccountAmount(source, -(amount));
body->cryptotransfer->transfers->accountamounts[1] = createAccountAmount(target, amount);
// Serialize the transaction body
*size = proto__transaction_body__get_packed_size(body);
uint8_t * buffer = calloc(1, *size);
proto__transaction_body__pack(body, buffer);
// Free the body object now that we have serialized to bytes
proto__transaction_body__free_unpacked(body, NULL);
return buffer;
}
Proto__SignatureMap * createSigMap(uint8_t *signature, uint8_t * publicKey)
{
Proto__SignatureMap * sigMap = calloc(1, sizeof(Proto__SignatureMap));
proto__signature_map__init(sigMap);
sigMap->sigpair = calloc(1, sizeof(Proto__SignaturePair*)); // A single signature
sigMap->sigpair[0] = calloc(1, sizeof(Proto__SignaturePair));
proto__signature_pair__init(sigMap->sigpair[0]);
sigMap->sigpair[0]->signature_case = PROTO__SIGNATURE_PAIR__SIGNATURE_ED25519;
// We need to take copies of the the following fields or else we
// get a double free assert. They will get freed later in the call
// to proto__transaction__free_unpacked
uint8_t * pubKeyBuffer = calloc(1, 32);
memcpy(pubKeyBuffer, publicKey, 32);
uint8_t * sigCopy = calloc(1, 64);
memcpy(sigCopy, signature, 64);
sigMap->sigpair[0]->pubkeyprefix.data = pubKeyBuffer;
sigMap->sigpair[0]->pubkeyprefix.len = 32;
sigMap->sigpair[0]->ed25519.data = sigCopy;
sigMap->sigpair[0]->ed25519.len = 64;
sigMap->n_sigpair = 1;
return sigMap;
}
uint8_t * hederaTransactionPack (uint8_t * signature, size_t signatureSize,
uint8_t * publicKey, size_t publicKeySize,
uint8_t * body, size_t bodySize,
size_t * serializedSize)
{
struct _Proto__Transaction * transaction = calloc(1, sizeof(struct _Proto__Transaction));
proto__transaction__init(transaction);
transaction->body_data_case = PROTO__TRANSACTION__BODY_DATA_BODY_BYTES;
// Attach the signature and the bytes to our transaction object
transaction->sigmap = createSigMap(signature, publicKey);
// The call to free_unpacked below will delete the .data field, so take
// a copy here so we don't get a double free
uint8_t * bodyCopy = calloc(1, bodySize);
memcpy(bodyCopy, body, bodySize);
transaction->bodybytes.data = bodyCopy;
transaction->bodybytes.len = bodySize;
transaction->body_data_case = PROTO__TRANSACTION__BODY_DATA_BODY_BYTES;
// Get the packed bytes
*serializedSize = proto__transaction__get_packed_size(transaction);
uint8_t * serializeBytes = calloc(1, *serializedSize);
proto__transaction__pack(transaction, serializeBytes);
// Free the transaction now that we have serialized to bytes
proto__transaction__free_unpacked(transaction, NULL);
return serializeBytes;
}
|
710899.c | /*
* Copyright (C) 2002 Stichting NLnet, Netherlands, [email protected].
*
* 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 STICHTING NLNET
* DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* STICHTING NLNET 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.
*
* The development of Dynamically Loadable Zones (DLZ) for Bind 9 was
* conceived and contributed by Rob Butler.
*
* 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 ROB BUTLER
* DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* ROB BUTLER 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.
*/
/*
* Copyright (C) 1999-2001 Internet Software Consortium.
*
* 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 INTERNET SOFTWARE CONSORTIUM
* DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* INTERNET SOFTWARE CONSORTIUM 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.
*/
#ifdef DLZ_BDB
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dns/log.h>
#include <dns/sdlz.h>
#include <dns/result.h>
#include <isc/mem.h>
#include <isc/print.h>
#include <isc/result.h>
#include <isc/util.h>
#include <named/globals.h>
#include <dlz/dlz_bdb_driver.h>
#include <db.h>
static dns_sdlzimplementation_t *dlz_bdb = NULL;
/* should the bdb driver use threads. */
#ifdef ISC_PLATFORM_USETHREADS
#define bdb_threads DB_THREAD
#else
#define bdb_threads 0
#endif
/* BDB database names */
#define dlz_data "dns_data"
#define dlz_zone "dns_zone"
#define dlz_host "dns_host"
#define dlz_client "dns_client"
/*%
* This structure contains all the Berkeley DB handles
* for this instance of the BDB driver.
*/
typedef struct bdb_instance {
DB_ENV *dbenv; /*%< BDB environment */
DB *data; /*%< dns_data database handle */
DB *zone; /*%< zone database handle */
DB *host; /*%< host database handle */
DB *client; /*%< client database handle */
isc_mem_t *mctx; /*%< memory context */
} bdb_instance_t;
typedef struct parsed_data {
char *zone;
char *host;
char *type;
int ttl;
char *data;
} parsed_data_t;
/* forward reference */
static isc_result_t
bdb_findzone(void *driverarg, void *dbdata, const char *name);
/*%
* Parses the DBT from the Berkeley DB into a parsed_data record
* The parsed_data record should be allocated before and passed into the
* bdb_parse_data function. The char (type & data) fields should not
* be "free"d as that memory is part of the DBT data field. It will be
* "free"d when the DBT is freed.
*/
static isc_result_t
bdb_parse_data(char *in, parsed_data_t *pd) {
char *endp, *ttlStr;
char *tmp = in;
char *lastchar = (char *) &tmp[strlen(tmp) + 1];
/*%
* String should be formated as:
* zone(a space)host(a space)ttl(a space)type(a space)remaining data
* examples:
* example.com www 10 A 127.0.0.1
* example.com mail 10 A 127.0.0.2
* example.com @ 10 MX 20 mail.example.com
*/
/* save pointer to zone */
pd->zone = tmp;
/* find space after zone and change it to a '\0' */
tmp = strchr(tmp, ' ');
/* verify we found a space */
if (tmp == NULL)
return ISC_R_FAILURE;
/* change the space to a null (string terminator) */
tmp[0] = '\0';
/* make sure it is safe to increment pointer */
if (++tmp > lastchar)
return ISC_R_FAILURE;
/* save pointer to host */
pd->host = tmp;
/* find space after type and change it to a '\0' */
tmp = strchr(tmp, ' ');
/* verify we found a space */
if (tmp == NULL)
return ISC_R_FAILURE;
/* change the space to a null (string terminator) */
tmp[0] = '\0';
/* make sure it is safe to increment pointer */
if (++tmp > lastchar)
return ISC_R_FAILURE;
/* save pointer to dns type */
pd->type = tmp;
/* find space after type and change it to a '\0' */
tmp = strchr(tmp, ' ');
/* verify we found a space */
if (tmp == NULL)
return ISC_R_FAILURE;
/* change the space to a null (string terminator) */
tmp[0] = '\0';
/* make sure it is safe to increment pointer */
if (++tmp > lastchar)
return ISC_R_FAILURE;
/* save pointer to dns ttl */
ttlStr = tmp;
/* find space after ttl and change it to a '\0' */
tmp = strchr(tmp, ' ');
/* verify we found a space */
if (tmp == NULL)
return ISC_R_FAILURE;
/* change the space to a null (string terminator) */
tmp[0] = '\0';
/* make sure it is safe to increment pointer */
if (++tmp > lastchar)
return ISC_R_FAILURE;
/* save pointer to remainder of DNS data */
pd->data = tmp;
/* convert ttl string to integer */
pd->ttl = strtol(ttlStr, &endp, 10);
if (*endp != '\0' || pd->ttl < 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB driver ttl must be a postive number");
return ISC_R_FAILURE;
}
/* if we get this far everything should have worked. */
return ISC_R_SUCCESS;
}
/*
* DLZ methods
*/
static isc_result_t
bdb_allowzonexfr(void *driverarg, void *dbdata, const char *name,
const char *client)
{
isc_result_t result;
bdb_instance_t *db = (bdb_instance_t *) dbdata;
DBC *client_cursor = NULL;
DBT key, data;
/* check to see if we are authoritative for the zone first. */
result = bdb_findzone(driverarg, dbdata, name);
if (result != ISC_R_SUCCESS)
return (ISC_R_NOTFOUND);
memset(&key, 0, sizeof(DBT));
key.flags = DB_DBT_MALLOC;
key.data = strdup(name);
if (key.data == NULL) {
result = ISC_R_NOMEMORY;
goto xfr_cleanup;
}
key.size = strlen(key.data);
memset(&data, 0, sizeof(DBT));
data.flags = DB_DBT_MALLOC;
data.data = strdup(client);
if (data.data == NULL) {
result = ISC_R_NOMEMORY;
goto xfr_cleanup;
}
data.size = strlen(data.data);
/* get a cursor to loop through zone data */
if (db->client->cursor(db->client, NULL, &client_cursor, 0) != 0) {
result = ISC_R_FAILURE;
goto xfr_cleanup;
}
switch(client_cursor->c_get(client_cursor, &key, &data, DB_GET_BOTH)) {
case DB_NOTFOUND:
case DB_SECONDARY_BAD:
result = ISC_R_NOTFOUND;
break;
case 0:
result = ISC_R_SUCCESS;
break;
default:
result = ISC_R_FAILURE;
}
xfr_cleanup:
/* free any memory duplicate string in the key field */
if (key.data != NULL)
free(key.data);
/* free any memory allocated to the data field. */
if (data.data != NULL)
free(data.data);
/* get rid of zone_cursor */
if (client_cursor != NULL)
client_cursor->c_close(client_cursor);
return result;
}
static isc_result_t
bdb_allnodes(const char *zone, void *driverarg, void *dbdata,
dns_sdlzallnodes_t *allnodes)
{
isc_result_t result = ISC_R_NOTFOUND;
bdb_instance_t *db = (bdb_instance_t *) dbdata;
DBC *zone_cursor = NULL;
DBT key, data;
int flags;
int bdbres;
parsed_data_t pd;
char *tmp = NULL, *tmp_zone;
UNUSED(driverarg);
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
key.data = tmp_zone = strdup(zone);
if (key.data == NULL)
return (ISC_R_NOMEMORY);
key.size = strlen(key.data);
/* get a cursor to loop through zone data */
if (db->zone->cursor(db->zone, NULL, &zone_cursor, 0) != 0) {
result = ISC_R_FAILURE;
goto allnodes_cleanup;
}
flags = DB_SET;
while ((bdbres = zone_cursor->c_get(zone_cursor, &key, &data,
flags)) == 0) {
flags = DB_NEXT_DUP;
tmp = realloc(tmp, data.size + 1);
if (tmp == NULL)
goto allnodes_cleanup;
strncpy(tmp, data.data, data.size);
tmp[data.size] = '\0';
if (bdb_parse_data(tmp, &pd) != ISC_R_SUCCESS)
goto allnodes_cleanup;
result = dns_sdlz_putnamedrr(allnodes, pd.host, pd.type,
pd.ttl, pd.data);
if (result != ISC_R_SUCCESS)
goto allnodes_cleanup;
} /* end while loop */
allnodes_cleanup:
if (tmp != NULL)
free(tmp);
/* free any memory duplicate string in the key field */
if (tmp_zone != NULL)
free(tmp_zone);
/* get rid of zone_cursor */
if (zone_cursor != NULL)
zone_cursor->c_close(zone_cursor);
return result;
}
/*%
* Performs BDB cleanup.
* Used by bdb_create if there is an error starting up.
* Used by bdb_destroy when the driver is shutting down.
*/
static void
bdb_cleanup(bdb_instance_t *db) {
isc_mem_t *mctx;
/* close databases */
if (db->data != NULL)
db->data->close(db->data, 0);
if (db->host != NULL)
db->host->close(db->host, 0);
if (db->zone != NULL)
db->zone->close(db->zone, 0);
if (db->client != NULL)
db->client->close(db->client, 0);
/* close environment */
if (db->dbenv != NULL)
db->dbenv->close(db->dbenv, 0);
/* cleanup memory */
if (db->mctx != NULL) {
/* save mctx for later */
mctx = db->mctx;
/* return, and detach the memory */
isc_mem_put(mctx, db, sizeof(bdb_instance_t));
isc_mem_detach(&mctx);
}
}
static isc_result_t
bdb_findzone(void *driverarg, void *dbdata, const char *name)
{
isc_result_t result;
bdb_instance_t *db = (bdb_instance_t *) dbdata;
DBC *zone_cursor = NULL;
DBT key, data;
UNUSED(driverarg);
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
data.flags = DB_DBT_MALLOC;
key.data = strdup(name);
if (key.data == NULL)
return (ISC_R_NOMEMORY);
key.size = strlen(key.data);
/* get a cursor to loop through zone data */
if (db->zone->cursor(db->zone, NULL, &zone_cursor, 0) != 0) {
result = ISC_R_NOTFOUND;
goto findzone_cleanup;
}
switch(zone_cursor->c_get(zone_cursor, &key, &data, DB_SET)) {
case DB_NOTFOUND:
case DB_SECONDARY_BAD:
result = ISC_R_NOTFOUND;
break;
case 0:
result = ISC_R_SUCCESS;
break;
default:
result = ISC_R_FAILURE;
}
findzone_cleanup:
/* free any memory duplicate string in the key field */
if (key.data != NULL)
free(key.data);
/* free any memory allocated to the data field. */
if (data.data != NULL)
free(data.data);
/* get rid of zone_cursor */
if (zone_cursor != NULL)
zone_cursor->c_close(zone_cursor);
return result;
}
static isc_result_t
bdb_lookup(const char *zone, const char *name, void *driverarg,
void *dbdata, dns_sdlzlookup_t *lookup,
dns_clientinfomethods_t *methods, dns_clientinfo_t *clientinfo)
{
isc_result_t result = ISC_R_NOTFOUND;
bdb_instance_t *db = (bdb_instance_t *) dbdata;
DBC *zone_cursor = NULL;
DBC *host_cursor = NULL;
DBC *join_cursor = NULL;
DBT key, data;
DBC *cur_arr[3];
int bdbres;
parsed_data_t pd;
char *tmp_zone, *tmp_host = NULL;
char *tmp = NULL;
UNUSED(driverarg);
UNUSED(methods);
UNUSED(clientinfo);
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
/* set zone key */
key.data = tmp_zone = strdup(zone);
if (key.data == NULL) {
result = ISC_R_NOMEMORY;
goto lookup_cleanup;
}
key.size = strlen(key.data);
/* get a cursor to loop through zone data */
if (db->zone->cursor(db->zone, NULL, &zone_cursor, 0) != 0) {
result = ISC_R_FAILURE;
goto lookup_cleanup;
}
/* initialize zone_cursor with zone_key */
if (zone_cursor->c_get(zone_cursor, &key, &data, DB_SET) != 0) {
result = ISC_R_NOTFOUND;
goto lookup_cleanup;
}
/* set host key */
key.data = tmp_host = strdup(name);
if (key.data == NULL) {
result = ISC_R_NOMEMORY;
goto lookup_cleanup;
}
key.size = strlen(key.data);
/* get a cursor to loop through host data */
if (db->host->cursor(db->host, NULL, &host_cursor, 0) != 0) {
result = ISC_R_FAILURE;
goto lookup_cleanup;
}
/* initialize host_cursor with host_key */
if (host_cursor->c_get(host_cursor, &key, &data, DB_SET) != 0) {
result = ISC_R_NOTFOUND;
goto lookup_cleanup;
}
cur_arr[0] = zone_cursor;
cur_arr[1] = host_cursor;
cur_arr[2] = NULL;
db->data->join(db->data, cur_arr, &join_cursor, 0);
while ((bdbres = join_cursor->c_get(join_cursor, &key,
&data, 0)) == 0) {
tmp = realloc(tmp, data.size + 1);
if (tmp == NULL)
goto lookup_cleanup;
strncpy(tmp, data.data, data.size);
tmp[data.size] = '\0';
if (bdb_parse_data(tmp, &pd) != ISC_R_SUCCESS)
goto lookup_cleanup;
result = dns_sdlz_putrr(lookup, pd.type, pd.ttl, pd.data);
if (result != ISC_R_SUCCESS)
goto lookup_cleanup;
} /* end while loop */
lookup_cleanup:
if (tmp != NULL)
free(tmp);
if (tmp_zone != NULL)
free(tmp_zone);
if (tmp_host != NULL)
free(tmp_host);
/* get rid of the joined cusor */
if (join_cursor != NULL)
join_cursor->c_close(join_cursor);
/* get rid of zone_cursor */
if (zone_cursor != NULL)
zone_cursor->c_close(zone_cursor);
/* get rid of host_cursor */
if (host_cursor != NULL)
host_cursor->c_close(host_cursor);
return result;
}
/*% Initializes, sets flags and then opens Berkeley databases. */
static isc_result_t
bdb_opendb(DB_ENV *db_env, DBTYPE db_type, DB **db, const char *db_name,
char *db_file, int flags) {
int result;
/* Initialize the database. */
if ((result = db_create(db, db_env, 0)) != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB could not initialize %s database. "
"BDB error: %s",
db_name, db_strerror(result));
return ISC_R_FAILURE;
}
/* set database flags. */
if ((result = (*db)->set_flags(*db, flags)) != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB could not set flags for %s database. "
"BDB error: %s",
db_name, db_strerror(result));
return ISC_R_FAILURE;
}
/* open the database. */
if ((result = (*db)->open(*db, NULL, db_file, db_name, db_type,
DB_RDONLY | bdb_threads, 0)) != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB could not open %s database in %s. "
"BDB error: %s",
db_name, db_file, db_strerror(result));
return ISC_R_FAILURE;
}
return ISC_R_SUCCESS;
}
static isc_result_t
bdb_create(const char *dlzname, unsigned int argc, char *argv[],
void *driverarg, void **dbdata)
{
isc_result_t result;
int bdbres;
bdb_instance_t *db = NULL;
UNUSED(dlzname);
UNUSED(driverarg);
/* verify we have 3 arg's passed to the driver */
if (argc != 3) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"Berkeley DB driver requires at least "
"2 command line args.");
return (ISC_R_FAILURE);
}
/* allocate and zero memory for driver structure */
db = isc_mem_get(ns_g_mctx, sizeof(bdb_instance_t));
if (db == NULL) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"Could not allocate memory for "
"database instance object.");
return (ISC_R_NOMEMORY);
}
memset(db, 0, sizeof(bdb_instance_t));
/* attach to the memory context */
isc_mem_attach(ns_g_mctx, &db->mctx);
/* create BDB environment
* Basically BDB allocates and assigns memory to db->dbenv
*/
bdbres = db_env_create(&db->dbenv, 0);
if (bdbres != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB environment could not be created. "
"BDB error: %s",
db_strerror(bdbres));
result = ISC_R_FAILURE;
goto init_cleanup;
}
/* open BDB environment */
bdbres = db->dbenv->open(db->dbenv, argv[1],
DB_INIT_CDB | DB_INIT_MPOOL |
bdb_threads | DB_CREATE,
0);
if (bdbres != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB environment at '%s' could not be opened. "
"BDB error: %s",
argv[1], db_strerror(bdbres));
result = ISC_R_FAILURE;
goto init_cleanup;
}
/* open dlz_data database. */
result = bdb_opendb(db->dbenv, DB_UNKNOWN, &db->data,
dlz_data, argv[2], 0);
if (result != ISC_R_SUCCESS)
goto init_cleanup;
/* open dlz_host database. */
result = bdb_opendb(db->dbenv, DB_UNKNOWN, &db->host,
dlz_host, argv[2],
DB_DUP | DB_DUPSORT);
if (result != ISC_R_SUCCESS)
goto init_cleanup;
/* open dlz_zone database. */
result = bdb_opendb(db->dbenv, DB_UNKNOWN, &db->zone,
dlz_zone, argv[2],
DB_DUP | DB_DUPSORT);
if (result != ISC_R_SUCCESS)
goto init_cleanup;
/* open dlz_client database. */
result = bdb_opendb(db->dbenv, DB_UNKNOWN, &db->client,
dlz_client, argv[2], DB_DUP | DB_DUPSORT);
if (result != ISC_R_SUCCESS)
goto init_cleanup;
/* associate the host secondary database with the primary database */
bdbres = db->data->associate(db->data, NULL, db->host, NULL, 0);
if (bdbres != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB could not associate %s database with %s. "
"BDB error: %s",
dlz_host, dlz_data, db_strerror(bdbres));
result = ISC_R_FAILURE;
goto init_cleanup;
}
/* associate the zone secondary database with the primary database */
bdbres = db->data->associate(db->data, NULL, db->zone, NULL, 0);
if (bdbres != 0) {
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
"BDB could not associate %s database with %s. "
"BDB error: %s",
dlz_zone, dlz_data, db_strerror(bdbres));
result = ISC_R_FAILURE;
goto init_cleanup;
}
*dbdata = db;
return(ISC_R_SUCCESS);
init_cleanup:
bdb_cleanup(db);
return result;
}
static void
bdb_destroy(void *driverarg, void *dbdata)
{
UNUSED(driverarg);
bdb_cleanup((bdb_instance_t *) dbdata);
}
/* bdb_authority not needed as authority data is returned by lookup */
static dns_sdlzmethods_t dlz_bdb_methods = {
bdb_create,
bdb_destroy,
bdb_findzone,
bdb_lookup,
NULL,
bdb_allnodes,
bdb_allowzonexfr,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
/*%
* Wrapper around dns_sdlzregister().
*/
isc_result_t
dlz_bdb_init(void) {
isc_result_t result;
/*
* Write debugging message to log
*/
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2),
"Registering DLZ bdb driver.");
result = dns_sdlzregister("bdb", &dlz_bdb_methods, NULL,
DNS_SDLZFLAG_RELATIVEOWNER |
DNS_SDLZFLAG_RELATIVERDATA |
DNS_SDLZFLAG_THREADSAFE,
ns_g_mctx, &dlz_bdb);
if (result != ISC_R_SUCCESS) {
UNEXPECTED_ERROR(__FILE__, __LINE__,
"dns_sdlzregister() failed: %s",
isc_result_totext(result));
result = ISC_R_UNEXPECTED;
}
return result;
}
/*%
* Wrapper around dns_sdlzunregister().
*/
void
dlz_bdb_clear(void) {
/*
* Write debugging message to log
*/
isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2),
"Unregistering DLZ bdb driver.");
if (dlz_bdb != NULL)
dns_sdlzunregister(&dlz_bdb);
}
#endif
|
539301.c | //
// Created by Pascal Harris LC on 19/12/2019.
//
#include "gtk_wangers_liststore.h"
void traverse_list_store (GtkListStore *liststore) {
GtkTreeIter iter;
gboolean valid;
g_return_if_fail ( liststore != NULL );
/* Get first row in list store */
valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(liststore), &iter);
while (valid) {
/* ... do something with that row using the iter ... */
/* (Here column 0 of the list store is of type G_TYPE_STRING) */
//gtk_list_store_set(liststore, &iter, 0, "Joe", -1);
/* Make iter point to the next row in the list store */
valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(liststore), &iter);
}
}
|
779153.c | #include <sys/cdefs.h>
#include <stdlib.h>
#include <string.h>
#include "quicksortBSD.c"
#define BaseCompareNum(a, b) ( ( (a) > (b) ) - ( (a) < (b) ) )
#define BaseCompareChar(a, b) ( strcmp(a, b) )
int MultiCompareChar (const void *a, const void *b, void *thunk);
int MultiCompareChar (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
// return BaseCompareChar(*((char **)a + kstart), *((char **)b + kstart));
MixedUnion *aa = (MixedUnion *)a + kstart;
MixedUnion *bb = (MixedUnion *)b + kstart;
return BaseCompareChar(aa->cval, bb->cval);
}
int MultiCompareCharInvert (const void *a, const void *b, void *thunk);
int MultiCompareCharInvert (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
// return BaseCompareChar(*((char **)a + kstart), *((char **)b + kstart));
MixedUnion *aa = (MixedUnion *)a + kstart;
MixedUnion *bb = (MixedUnion *)b + kstart;
return BaseCompareChar(bb->cval, aa->cval);
}
int MultiCompareNum (const void *a, const void *b, void *thunk);
int MultiCompareNum (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
MixedUnion *aa = (MixedUnion *)a + kstart;
MixedUnion *bb = (MixedUnion *)b + kstart;
return BaseCompareNum(aa->dval, bb->dval);
// const double aa = *((double*)*((void **)a + kstart));
// const double bb = *((double*)*((void **)b + kstart));
// return BaseCompareNum(aa, bb);
}
int MultiCompareNumInvert (const void *a, const void *b, void *thunk);
int MultiCompareNumInvert (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
MixedUnion *aa = (MixedUnion *)a + kstart;
MixedUnion *bb = (MixedUnion *)b + kstart;
return BaseCompareNum(bb->dval, aa->dval);
// const double aa = *((double*)*((void **)a + kstart));
// const double bb = *((double*)*((void **)b + kstart));
// return BaseCompareNum(aa, bb);
}
void MultiQuicksort (
void *start,
size_t N,
size_t kstart,
size_t kend,
size_t elsize,
size_t *ltypes,
int *invert
);
void MultiQuicksort (
void *start,
size_t N,
size_t kstart,
size_t kend,
size_t elsize,
size_t *ltypes,
int *invert)
{
size_t j;
short ischar;
void *i, *end;
quicksortBSD (
start,
N,
elsize,
( (ischar = (ltypes[kstart] > 0)) )?
(invert[kstart]? MultiCompareCharInvert: MultiCompareChar):
(invert[kstart]? MultiCompareNumInvert: MultiCompareNum),
&kstart
);
if ( kstart >= kend )
return;
end = start + N * elsize;
loop:
j = 1;
if ( invert[kstart] ) {
if ( ischar ) {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareCharInvert(i - elsize, i, &kstart) ) break;
j++;
}
}
else {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareNumInvert(i - elsize, i, &kstart) ) break;
j++;
}
}
}
else {
if ( ischar ) {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareChar(i - elsize, i, &kstart) ) break;
j++;
}
}
else {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareNum(i - elsize, i, &kstart) ) break;
j++;
}
}
}
if ( j > 1 ) {
MultiQuicksort (
start,
j,
kstart + 1,
kend,
elsize,
ltypes,
invert
);
}
if ( (kstart < kend) ) {
start = i;
if ( start < end )
goto loop;
}
}
/*********************************************************************
* Testing *
*********************************************************************/
int MultiCompareNum2 (const void *a, const void *b, void *thunk);
int MultiCompareNum2 (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
double aa = *((double *)a + kstart);
double bb = *((double *)b + kstart);
return BaseCompareNum(aa, bb);
}
int MultiCompareNum2Invert (const void *a, const void *b, void *thunk);
int MultiCompareNum2Invert (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
double aa = *((double *)a + kstart);
double bb = *((double *)b + kstart);
return BaseCompareNum(bb, aa);
}
void MultiQuicksort2 (
void *start,
size_t N,
size_t kstart,
size_t kend,
size_t elsize,
size_t *ltypes,
int *invert
);
void MultiQuicksort2 (
void *start,
size_t N,
size_t kstart,
size_t kend,
size_t elsize,
size_t *ltypes,
int *invert)
{
size_t j;
void *i, *end;
quicksortBSD (
start,
N,
elsize,
invert[kstart]? MultiCompareNum2Invert: MultiCompareNum2,
&kstart
);
if ( kstart >= kend )
return;
end = start + N * elsize;
loop:
j = 1;
if ( invert[kstart] ) {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareNum2Invert(i - elsize, i, &kstart) ) break;
j++;
}
}
else {
for (i = start + elsize; i < end; i += elsize) {
if ( MultiCompareNum2(i - elsize, i, &kstart) ) break;
j++;
}
}
if ( j > 1 ) {
MultiQuicksort (
start,
j,
kstart + 1,
kend,
elsize,
ltypes,
invert
);
}
if ( (kstart < kend) ) {
start = i;
if ( start < end )
goto loop;
}
}
/*********************************************************************
* Testing *
*********************************************************************/
int AltCompareChar (const void *a, const void *b, void *thunk);
int AltCompareChar (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
char *aa = (char *)(a + kstart);
char *bb = (char *)(b + kstart);
// printf("%s vs %s\n", aa, bb);
return BaseCompareChar(aa, bb);
}
int AltCompareCharInvert (const void *a, const void *b, void *thunk);
int AltCompareCharInvert (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
char *aa = (char *)(a + kstart);
char *bb = (char *)(b + kstart);
// printf("%s vs %s\n", aa, bb);
return BaseCompareChar(bb, aa);
}
int AltCompareNum (const void *a, const void *b, void *thunk);
int AltCompareNum (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
double aa = *(double *)(a + kstart);
double bb = *(double *)(b + kstart);
return BaseCompareNum(aa, bb);
}
int AltCompareNumInvert (const void *a, const void *b, void *thunk);
int AltCompareNumInvert (const void *a, const void *b, void *thunk)
{
int kstart = *(size_t *)thunk;
double aa = *(double *)(a + kstart);
double bb = *(double *)(b + kstart);
return BaseCompareNum(bb, aa);
}
void MultiQuicksort3 (
void *start,
size_t N,
size_t kstart,
size_t kend,
size_t elsize,
size_t *ltypes,
int *invert,
size_t *positions)
{
size_t j;
short ischar;
void *i, *end;
quicksortBSD (
start,
N,
elsize,
( (ischar = (ltypes[kstart] > 0)) )?
(invert[kstart]? AltCompareCharInvert: AltCompareChar):
(invert[kstart]? AltCompareNumInvert: AltCompareNum),
&(positions[kstart])
);
if ( kstart >= kend )
return;
end = start + N * elsize;
loop:
j = 1;
if ( invert[kstart] ) {
if ( ischar ) {
for (i = start + elsize; i < end; i += elsize) {
if ( AltCompareCharInvert(i - elsize, i, &(positions[kstart])) ) break;
j++;
}
}
else {
for (i = start + elsize; i < end; i += elsize) {
if ( AltCompareNumInvert(i - elsize, i, &(positions[kstart])) ) break;
j++;
}
}
}
else {
if ( ischar ) {
for (i = start + elsize; i < end; i += elsize) {
if ( AltCompareChar(i - elsize, i, &(positions[kstart])) ) break;
j++;
}
}
else {
for (i = start + elsize; i < end; i += elsize) {
if ( AltCompareNum(i - elsize, i, &(positions[kstart])) ) break;
j++;
}
}
}
if ( j > 1 ) {
MultiQuicksort3 (
start,
j,
kstart + 1,
kend,
elsize,
ltypes,
invert,
positions
);
}
if ( (kstart < kend) ) {
start = i;
if ( start < end )
goto loop;
}
}
|
690460.c | /*
* dvb_ca.c: generic DVB functions for EN50221 CAM interfaces
*
* Copyright (C) 2004 Andrew de Quincey
*
* Parts of this file were based on sources as follows:
*
* Copyright (C) 2003 Ralph Metzler <[email protected]>
*
* based on code:
*
* Copyright (C) 1999-2002 Ralph Metzler
* & Marcus Metzler for convergence integrated media GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include "dvb_ca_en50221.h"
#include "dvb_ringbuffer.h"
static int dvb_ca_en50221_debug;
module_param_named(cam_debug, dvb_ca_en50221_debug, int, 0644);
MODULE_PARM_DESC(cam_debug, "enable verbose debug messages");
#define dprintk if (dvb_ca_en50221_debug) printk
#define INIT_TIMEOUT_SECS 10
#define HOST_LINK_BUF_SIZE 0x200
#define RX_BUFFER_SIZE 65535
#define MAX_RX_PACKETS_PER_ITERATION 10
#define CTRLIF_DATA 0
#define CTRLIF_COMMAND 1
#define CTRLIF_STATUS 1
#define CTRLIF_SIZE_LOW 2
#define CTRLIF_SIZE_HIGH 3
#define CMDREG_HC 1 /* Host control */
#define CMDREG_SW 2 /* Size write */
#define CMDREG_SR 4 /* Size read */
#define CMDREG_RS 8 /* Reset interface */
#define CMDREG_FRIE 0x40 /* Enable FR interrupt */
#define CMDREG_DAIE 0x80 /* Enable DA interrupt */
#define IRQEN (CMDREG_DAIE)
#define STATUSREG_RE 1 /* read error */
#define STATUSREG_WE 2 /* write error */
#define STATUSREG_FR 0x40 /* module free */
#define STATUSREG_DA 0x80 /* data available */
#define STATUSREG_TXERR (STATUSREG_RE|STATUSREG_WE) /* general transfer error */
#define DVB_CA_SLOTSTATE_NONE 0
#define DVB_CA_SLOTSTATE_UNINITIALISED 1
#define DVB_CA_SLOTSTATE_RUNNING 2
#define DVB_CA_SLOTSTATE_INVALID 3
#define DVB_CA_SLOTSTATE_WAITREADY 4
#define DVB_CA_SLOTSTATE_VALIDATE 5
#define DVB_CA_SLOTSTATE_WAITFR 6
#define DVB_CA_SLOTSTATE_LINKINIT 7
/* Information on a CA slot */
struct dvb_ca_slot {
/* current state of the CAM */
int slot_state;
/* mutex used for serializing access to one CI slot */
struct mutex slot_lock;
/* Number of CAMCHANGES that have occurred since last processing */
atomic_t camchange_count;
/* Type of last CAMCHANGE */
int camchange_type;
/* base address of CAM config */
u32 config_base;
/* value to write into Config Control register */
u8 config_option;
/* if 1, the CAM supports DA IRQs */
u8 da_irq_supported:1;
/* size of the buffer to use when talking to the CAM */
int link_buf_size;
/* buffer for incoming packets */
struct dvb_ringbuffer rx_buffer;
/* timer used during various states of the slot */
unsigned long timeout;
};
/* Private CA-interface information */
struct dvb_ca_private {
/* pointer back to the public data structure */
struct dvb_ca_en50221 *pub;
/* the DVB device */
struct dvb_device *dvbdev;
/* Flags describing the interface (DVB_CA_FLAG_*) */
u32 flags;
/* number of slots supported by this CA interface */
unsigned int slot_count;
/* information on each slot */
struct dvb_ca_slot *slot_info;
/* wait queues for read() and write() operations */
wait_queue_head_t wait_queue;
/* PID of the monitoring thread */
struct task_struct *thread;
/* Flag indicating if the CA device is open */
unsigned int open:1;
/* Flag indicating the thread should wake up now */
unsigned int wakeup:1;
/* Delay the main thread should use */
unsigned long delay;
/* Slot to start looking for data to read from in the next user-space read operation */
int next_read_slot;
};
static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca);
static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount);
static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount);
/**
* Safely find needle in haystack.
*
* @param haystack Buffer to look in.
* @param hlen Number of bytes in haystack.
* @param needle Buffer to find.
* @param nlen Number of bytes in needle.
* @return Pointer into haystack needle was found at, or NULL if not found.
*/
static char *findstr(char * haystack, int hlen, char * needle, int nlen)
{
int i;
if (hlen < nlen)
return NULL;
for (i = 0; i <= hlen - nlen; i++) {
if (!strncmp(haystack + i, needle, nlen))
return haystack + i;
}
return NULL;
}
/* ******************************************************************************** */
/* EN50221 physical interface functions */
/**
* Check CAM status.
*/
static int dvb_ca_en50221_check_camstatus(struct dvb_ca_private *ca, int slot)
{
int slot_status;
int cam_present_now;
int cam_changed;
/* IRQ mode */
if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE) {
return (atomic_read(&ca->slot_info[slot].camchange_count) != 0);
}
/* poll mode */
slot_status = ca->pub->poll_slot_status(ca->pub, slot, ca->open);
cam_present_now = (slot_status & DVB_CA_EN50221_POLL_CAM_PRESENT) ? 1 : 0;
cam_changed = (slot_status & DVB_CA_EN50221_POLL_CAM_CHANGED) ? 1 : 0;
if (!cam_changed) {
int cam_present_old = (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE);
cam_changed = (cam_present_now != cam_present_old);
}
if (cam_changed) {
if (!cam_present_now) {
ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
} else {
ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_INSERTED;
}
atomic_set(&ca->slot_info[slot].camchange_count, 1);
} else {
if ((ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) &&
(slot_status & DVB_CA_EN50221_POLL_CAM_READY)) {
// move to validate state if reset is completed
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
}
}
return cam_changed;
}
/**
* Wait for flags to become set on the STATUS register on a CAM interface,
* checking for errors and timeout.
*
* @param ca CA instance.
* @param slot Slot on interface.
* @param waitfor Flags to wait for.
* @param timeout_ms Timeout in milliseconds.
*
* @return 0 on success, nonzero on error.
*/
static int dvb_ca_en50221_wait_if_status(struct dvb_ca_private *ca, int slot,
u8 waitfor, int timeout_hz)
{
unsigned long timeout;
unsigned long start;
dprintk("%s\n", __func__);
/* loop until timeout elapsed */
start = jiffies;
timeout = jiffies + timeout_hz;
while (1) {
/* read the status and check for error */
int res = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
if (res < 0)
return -EIO;
/* if we got the flags, it was successful! */
if (res & waitfor) {
dprintk("%s succeeded timeout:%lu\n", __func__, jiffies - start);
return 0;
}
/* check for timeout */
if (time_after(jiffies, timeout)) {
break;
}
/* wait for a bit */
msleep(1);
}
dprintk("%s failed timeout:%lu\n", __func__, jiffies - start);
/* if we get here, we've timed out */
return -ETIMEDOUT;
}
/**
* Initialise the link layer connection to a CAM.
*
* @param ca CA instance.
* @param slot Slot id.
*
* @return 0 on success, nonzero on failure.
*/
static int dvb_ca_en50221_link_init(struct dvb_ca_private *ca, int slot)
{
int ret;
int buf_size;
u8 buf[2];
dprintk("%s\n", __func__);
/* we'll be determining these during this function */
ca->slot_info[slot].da_irq_supported = 0;
/* set the host link buffer size temporarily. it will be overwritten with the
* real negotiated size later. */
ca->slot_info[slot].link_buf_size = 2;
/* read the buffer size from the CAM */
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SR)) != 0)
return ret;
if ((ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_DA, HZ / 10)) != 0)
return ret;
if ((ret = dvb_ca_en50221_read_data(ca, slot, buf, 2)) != 2)
return -EIO;
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
return ret;
/* store it, and choose the minimum of our buffer and the CAM's buffer size */
buf_size = (buf[0] << 8) | buf[1];
if (buf_size > HOST_LINK_BUF_SIZE)
buf_size = HOST_LINK_BUF_SIZE;
ca->slot_info[slot].link_buf_size = buf_size;
buf[0] = buf_size >> 8;
buf[1] = buf_size & 0xff;
dprintk("Chosen link buffer size of %i\n", buf_size);
/* write the buffer size to the CAM */
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SW)) != 0)
return ret;
if ((ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_FR, HZ / 10)) != 0)
return ret;
if ((ret = dvb_ca_en50221_write_data(ca, slot, buf, 2)) != 2)
return -EIO;
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
return ret;
/* success */
return 0;
}
/**
* Read a tuple from attribute memory.
*
* @param ca CA instance.
* @param slot Slot id.
* @param address Address to read from. Updated.
* @param tupleType Tuple id byte. Updated.
* @param tupleLength Tuple length. Updated.
* @param tuple Dest buffer for tuple (must be 256 bytes). Updated.
*
* @return 0 on success, nonzero on error.
*/
static int dvb_ca_en50221_read_tuple(struct dvb_ca_private *ca, int slot,
int *address, int *tupleType, int *tupleLength, u8 * tuple)
{
int i;
int _tupleType;
int _tupleLength;
int _address = *address;
/* grab the next tuple length and type */
if ((_tupleType = ca->pub->read_attribute_mem(ca->pub, slot, _address)) < 0)
return _tupleType;
if (_tupleType == 0xff) {
dprintk("END OF CHAIN TUPLE type:0x%x\n", _tupleType);
*address += 2;
*tupleType = _tupleType;
*tupleLength = 0;
return 0;
}
if ((_tupleLength = ca->pub->read_attribute_mem(ca->pub, slot, _address + 2)) < 0)
return _tupleLength;
_address += 4;
dprintk("TUPLE type:0x%x length:%i\n", _tupleType, _tupleLength);
/* read in the whole tuple */
for (i = 0; i < _tupleLength; i++) {
tuple[i] = ca->pub->read_attribute_mem(ca->pub, slot, _address + (i * 2));
dprintk(" 0x%02x: 0x%02x %c\n",
i, tuple[i] & 0xff,
((tuple[i] > 31) && (tuple[i] < 127)) ? tuple[i] : '.');
}
_address += (_tupleLength * 2);
// success
*tupleType = _tupleType;
*tupleLength = _tupleLength;
*address = _address;
return 0;
}
/**
* Parse attribute memory of a CAM module, extracting Config register, and checking
* it is a DVB CAM module.
*
* @param ca CA instance.
* @param slot Slot id.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_parse_attributes(struct dvb_ca_private *ca, int slot)
{
int address = 0;
int tupleLength;
int tupleType;
u8 tuple[257];
char *dvb_str;
int rasz;
int status;
int got_cftableentry = 0;
int end_chain = 0;
int i;
u16 manfid = 0;
u16 devid = 0;
// CISTPL_DEVICE_0A
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1D)
return -EINVAL;
// CISTPL_DEVICE_0C
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1C)
return -EINVAL;
// CISTPL_VERS_1
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x15)
return -EINVAL;
// CISTPL_MANFID
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x20)
return -EINVAL;
if (tupleLength != 4)
return -EINVAL;
manfid = (tuple[1] << 8) | tuple[0];
devid = (tuple[3] << 8) | tuple[2];
// CISTPL_CONFIG
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1A)
return -EINVAL;
if (tupleLength < 3)
return -EINVAL;
/* extract the configbase */
rasz = tuple[0] & 3;
if (tupleLength < (3 + rasz + 14))
return -EINVAL;
ca->slot_info[slot].config_base = 0;
for (i = 0; i < rasz + 1; i++) {
ca->slot_info[slot].config_base |= (tuple[2 + i] << (8 * i));
}
/* check it contains the correct DVB string */
dvb_str = findstr((char *)tuple, tupleLength, "DVB_CI_V", 8);
if (dvb_str == NULL)
return -EINVAL;
if (tupleLength < ((dvb_str - (char *) tuple) + 12))
return -EINVAL;
/* is it a version we support? */
if (strncmp(dvb_str + 8, "1.00", 4)) {
printk("dvb_ca adapter %d: Unsupported DVB CAM module version %c%c%c%c\n",
ca->dvbdev->adapter->num, dvb_str[8], dvb_str[9], dvb_str[10], dvb_str[11]);
return -EINVAL;
}
/* process the CFTABLE_ENTRY tuples, and any after those */
while ((!end_chain) && (address < 0x1000)) {
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
switch (tupleType) {
case 0x1B: // CISTPL_CFTABLE_ENTRY
if (tupleLength < (2 + 11 + 17))
break;
/* if we've already parsed one, just use it */
if (got_cftableentry)
break;
/* get the config option */
ca->slot_info[slot].config_option = tuple[0] & 0x3f;
/* OK, check it contains the correct strings */
if ((findstr((char *)tuple, tupleLength, "DVB_HOST", 8) == NULL) ||
(findstr((char *)tuple, tupleLength, "DVB_CI_MODULE", 13) == NULL))
break;
got_cftableentry = 1;
break;
case 0x14: // CISTPL_NO_LINK
break;
case 0xFF: // CISTPL_END
end_chain = 1;
break;
default: /* Unknown tuple type - just skip this tuple and move to the next one */
dprintk("dvb_ca: Skipping unknown tuple type:0x%x length:0x%x\n", tupleType,
tupleLength);
break;
}
}
if ((address > 0x1000) || (!got_cftableentry))
return -EINVAL;
dprintk("Valid DVB CAM detected MANID:%x DEVID:%x CONFIGBASE:0x%x CONFIGOPTION:0x%x\n",
manfid, devid, ca->slot_info[slot].config_base, ca->slot_info[slot].config_option);
// success!
return 0;
}
/**
* Set CAM's configoption correctly.
*
* @param ca CA instance.
* @param slot Slot containing the CAM.
*/
static int dvb_ca_en50221_set_configoption(struct dvb_ca_private *ca, int slot)
{
int configoption;
dprintk("%s\n", __func__);
/* set the config option */
ca->pub->write_attribute_mem(ca->pub, slot,
ca->slot_info[slot].config_base,
ca->slot_info[slot].config_option);
/* check it */
configoption = ca->pub->read_attribute_mem(ca->pub, slot, ca->slot_info[slot].config_base);
dprintk("Set configoption 0x%x, read configoption 0x%x\n",
ca->slot_info[slot].config_option, configoption & 0x3f);
/* fine! */
return 0;
}
/**
* This function talks to an EN50221 CAM control interface. It reads a buffer of
* data from the CAM. The data can either be stored in a supplied buffer, or
* automatically be added to the slot's rx_buffer.
*
* @param ca CA instance.
* @param slot Slot to read from.
* @param ebuf If non-NULL, the data will be written to this buffer. If NULL,
* the data will be added into the buffering system as a normal fragment.
* @param ecount Size of ebuf. Ignored if ebuf is NULL.
*
* @return Number of bytes read, or < 0 on error
*/
static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount)
{
int bytes_read;
int status;
u8 buf[HOST_LINK_BUF_SIZE];
int i;
dprintk("%s\n", __func__);
/* check if we have space for a link buf in the rx_buffer */
if (ebuf == NULL) {
int buf_free;
if (ca->slot_info[slot].rx_buffer.data == NULL) {
status = -EIO;
goto exit;
}
buf_free = dvb_ringbuffer_free(&ca->slot_info[slot].rx_buffer);
if (buf_free < (ca->slot_info[slot].link_buf_size + DVB_RINGBUFFER_PKTHDRSIZE)) {
status = -EAGAIN;
goto exit;
}
}
/* check if there is data available */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (!(status & STATUSREG_DA)) {
/* no data */
status = 0;
goto exit;
}
/* read the amount of data */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH)) < 0)
goto exit;
bytes_read = status << 8;
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW)) < 0)
goto exit;
bytes_read |= status;
/* check it will fit */
if (ebuf == NULL) {
if (bytes_read > ca->slot_info[slot].link_buf_size) {
printk("dvb_ca adapter %d: CAM tried to send a buffer larger than the link buffer size (%i > %i)!\n",
ca->dvbdev->adapter->num, bytes_read, ca->slot_info[slot].link_buf_size);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
if (bytes_read < 2) {
printk("dvb_ca adapter %d: CAM sent a buffer that was less than 2 bytes!\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
} else {
if (bytes_read > ecount) {
printk("dvb_ca adapter %d: CAM tried to send a buffer larger than the ecount size!\n",
ca->dvbdev->adapter->num);
status = -EIO;
goto exit;
}
}
/* fill the buffer */
for (i = 0; i < bytes_read; i++) {
/* read byte and check */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_DATA)) < 0)
goto exit;
/* OK, store it in the buffer */
buf[i] = status;
}
/* check for read error (RE should now be 0) */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (status & STATUSREG_RE) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
/* OK, add it to the receive buffer, or copy into external buffer if supplied */
if (ebuf == NULL) {
if (ca->slot_info[slot].rx_buffer.data == NULL) {
status = -EIO;
goto exit;
}
dvb_ringbuffer_pkt_write(&ca->slot_info[slot].rx_buffer, buf, bytes_read);
} else {
memcpy(ebuf, buf, bytes_read);
}
dprintk("Received CA packet for slot %i connection id 0x%x last_frag:%i size:0x%x\n", slot,
buf[0], (buf[1] & 0x80) == 0, bytes_read);
/* wake up readers when a last_fragment is received */
if ((buf[1] & 0x80) == 0x00) {
wake_up_interruptible(&ca->wait_queue);
}
status = bytes_read;
exit:
return status;
}
/**
* This function talks to an EN50221 CAM control interface. It writes a buffer of data
* to a CAM.
*
* @param ca CA instance.
* @param slot Slot to write to.
* @param ebuf The data in this buffer is treated as a complete link-level packet to
* be written.
* @param count Size of ebuf.
*
* @return Number of bytes written, or < 0 on error.
*/
static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot, u8 * buf, int bytes_write)
{
int status;
int i;
dprintk("%s\n", __func__);
/* sanity check */
if (bytes_write > ca->slot_info[slot].link_buf_size)
return -EINVAL;
/* it is possible we are dealing with a single buffer implementation,
thus if there is data available for read or if there is even a read
already in progress, we do nothing but awake the kernel thread to
process the data if necessary. */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exitnowrite;
if (status & (STATUSREG_DA | STATUSREG_RE)) {
if (status & STATUSREG_DA)
dvb_ca_en50221_thread_wakeup(ca);
status = -EAGAIN;
goto exitnowrite;
}
/* OK, set HC bit */
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
IRQEN | CMDREG_HC)) != 0)
goto exit;
/* check if interface is still free */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (!(status & STATUSREG_FR)) {
/* it wasn't free => try again later */
status = -EAGAIN;
goto exit;
}
/* send the amount of data */
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH, bytes_write >> 8)) != 0)
goto exit;
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW,
bytes_write & 0xff)) != 0)
goto exit;
/* send the buffer */
for (i = 0; i < bytes_write; i++) {
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_DATA, buf[i])) != 0)
goto exit;
}
/* check for write error (WE should now be 0) */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (status & STATUSREG_WE) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
status = bytes_write;
dprintk("Wrote CA packet for slot %i, connection id 0x%x last_frag:%i size:0x%x\n", slot,
buf[0], (buf[1] & 0x80) == 0, bytes_write);
exit:
ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
exitnowrite:
return status;
}
EXPORT_SYMBOL(dvb_ca_en50221_camchange_irq);
/* ******************************************************************************** */
/* EN50221 higher level functions */
/**
* A CAM has been removed => shut it down.
*
* @param ca CA instance.
* @param slot Slot to shut down.
*/
static int dvb_ca_en50221_slot_shutdown(struct dvb_ca_private *ca, int slot)
{
dprintk("%s\n", __func__);
ca->pub->slot_shutdown(ca->pub, slot);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
/* need to wake up all processes to check if they're now
trying to write to a defunct CAM */
wake_up_interruptible(&ca->wait_queue);
dprintk("Slot %i shutdown\n", slot);
/* success */
return 0;
}
EXPORT_SYMBOL(dvb_ca_en50221_camready_irq);
/**
* A CAMCHANGE IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
* @param change_type One of the DVB_CA_CAMCHANGE_* values.
*/
void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot, int change_type)
{
struct dvb_ca_private *ca = pubca->private;
dprintk("CAMCHANGE IRQ slot:%i change_type:%i\n", slot, change_type);
switch (change_type) {
case DVB_CA_EN50221_CAMCHANGE_REMOVED:
case DVB_CA_EN50221_CAMCHANGE_INSERTED:
break;
default:
return;
}
ca->slot_info[slot].camchange_type = change_type;
atomic_inc(&ca->slot_info[slot].camchange_count);
dvb_ca_en50221_thread_wakeup(ca);
}
EXPORT_SYMBOL(dvb_ca_en50221_frda_irq);
/**
* A CAMREADY IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
*/
void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
{
struct dvb_ca_private *ca = pubca->private;
dprintk("CAMREADY IRQ slot:%i\n", slot);
if (ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
dvb_ca_en50221_thread_wakeup(ca);
}
}
/**
* An FR or DA IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
*/
void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *pubca, int slot)
{
struct dvb_ca_private *ca = pubca->private;
int flags;
dprintk("FR/DA IRQ slot:%i\n", slot);
switch (ca->slot_info[slot].slot_state) {
case DVB_CA_SLOTSTATE_LINKINIT:
flags = ca->pub->read_cam_control(pubca, slot, CTRLIF_STATUS);
if (flags & STATUSREG_DA) {
dprintk("CAM supports DA IRQ\n");
ca->slot_info[slot].da_irq_supported = 1;
}
break;
case DVB_CA_SLOTSTATE_RUNNING:
if (ca->open)
dvb_ca_en50221_thread_wakeup(ca);
break;
}
}
/* ******************************************************************************** */
/* EN50221 thread functions */
/**
* Wake up the DVB CA thread
*
* @param ca CA instance.
*/
static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca)
{
dprintk("%s\n", __func__);
ca->wakeup = 1;
mb();
wake_up_process(ca->thread);
}
/**
* Update the delay used by the thread.
*
* @param ca CA instance.
*/
static void dvb_ca_en50221_thread_update_delay(struct dvb_ca_private *ca)
{
int delay;
int curdelay = 100000000;
int slot;
/* Beware of too high polling frequency, because one polling
* call might take several hundred milliseconds until timeout!
*/
for (slot = 0; slot < ca->slot_count; slot++) {
switch (ca->slot_info[slot].slot_state) {
default:
case DVB_CA_SLOTSTATE_NONE:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ * 5; /* 5s */
break;
case DVB_CA_SLOTSTATE_INVALID:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ / 10; /* 100ms */
break;
case DVB_CA_SLOTSTATE_UNINITIALISED:
case DVB_CA_SLOTSTATE_WAITREADY:
case DVB_CA_SLOTSTATE_VALIDATE:
case DVB_CA_SLOTSTATE_WAITFR:
case DVB_CA_SLOTSTATE_LINKINIT:
delay = HZ / 10; /* 100ms */
break;
case DVB_CA_SLOTSTATE_RUNNING:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ / 10; /* 100ms */
if (ca->open) {
if ((!ca->slot_info[slot].da_irq_supported) ||
(!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_DA)))
delay = HZ / 10; /* 100ms */
}
break;
}
if (delay < curdelay)
curdelay = delay;
}
ca->delay = curdelay;
}
/**
* Kernel thread which monitors CA slots for CAM changes, and performs data transfers.
*/
static int dvb_ca_en50221_thread(void *data)
{
struct dvb_ca_private *ca = data;
int slot;
int flags;
int status;
int pktcount;
void *rxbuf;
dprintk("%s\n", __func__);
/* choose the correct initial delay */
dvb_ca_en50221_thread_update_delay(ca);
/* main loop */
while (!kthread_should_stop()) {
/* sleep for a bit */
if (!ca->wakeup) {
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(ca->delay);
if (kthread_should_stop())
return 0;
}
ca->wakeup = 0;
/* go through all the slots processing them */
for (slot = 0; slot < ca->slot_count; slot++) {
mutex_lock(&ca->slot_info[slot].slot_lock);
// check the cam status + deal with CAMCHANGEs
while (dvb_ca_en50221_check_camstatus(ca, slot)) {
/* clear down an old CI slot if necessary */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE)
dvb_ca_en50221_slot_shutdown(ca, slot);
/* if a CAM is NOW present, initialise it */
if (ca->slot_info[slot].camchange_type == DVB_CA_EN50221_CAMCHANGE_INSERTED) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_UNINITIALISED;
}
/* we've handled one CAMCHANGE */
dvb_ca_en50221_thread_update_delay(ca);
atomic_dec(&ca->slot_info[slot].camchange_count);
}
// CAM state machine
switch (ca->slot_info[slot].slot_state) {
case DVB_CA_SLOTSTATE_NONE:
case DVB_CA_SLOTSTATE_INVALID:
// no action needed
break;
case DVB_CA_SLOTSTATE_UNINITIALISED:
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITREADY;
ca->pub->slot_reset(ca->pub, slot);
ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
break;
case DVB_CA_SLOTSTATE_WAITREADY:
if (time_after(jiffies, ca->slot_info[slot].timeout)) {
printk("dvb_ca adaptor %d: PC card did not respond :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
// no other action needed; will automatically change state when ready
break;
case DVB_CA_SLOTSTATE_VALIDATE:
if (dvb_ca_en50221_parse_attributes(ca, slot) != 0) {
/* we need this extra check for annoying interfaces like the budget-av */
if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
(ca->pub->poll_slot_status)) {
status = ca->pub->poll_slot_status(ca->pub, slot, 0);
if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
}
printk("dvb_ca adapter %d: Invalid PC card inserted :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (dvb_ca_en50221_set_configoption(ca, slot) != 0) {
printk("dvb_ca adapter %d: Unable to initialise CAM :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (ca->pub->write_cam_control(ca->pub, slot,
CTRLIF_COMMAND, CMDREG_RS) != 0) {
printk("dvb_ca adapter %d: Unable to reset CAM IF\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
dprintk("DVB CAM validated successfully\n");
ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITFR;
ca->wakeup = 1;
break;
case DVB_CA_SLOTSTATE_WAITFR:
if (time_after(jiffies, ca->slot_info[slot].timeout)) {
printk("dvb_ca adapter %d: DVB CAM did not respond :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
flags = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
if (flags & STATUSREG_FR) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
ca->wakeup = 1;
}
break;
case DVB_CA_SLOTSTATE_LINKINIT:
if (dvb_ca_en50221_link_init(ca, slot) != 0) {
/* we need this extra check for annoying interfaces like the budget-av */
if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
(ca->pub->poll_slot_status)) {
status = ca->pub->poll_slot_status(ca->pub, slot, 0);
if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
}
printk("dvb_ca adapter %d: DVB CAM link initialisation failed :(\n", ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (ca->slot_info[slot].rx_buffer.data == NULL) {
rxbuf = vmalloc(RX_BUFFER_SIZE);
if (rxbuf == NULL) {
printk("dvb_ca adapter %d: Unable to allocate CAM rx buffer :(\n", ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
dvb_ringbuffer_init(&ca->slot_info[slot].rx_buffer, rxbuf, RX_BUFFER_SIZE);
}
ca->pub->slot_ts_enable(ca->pub, slot);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_RUNNING;
dvb_ca_en50221_thread_update_delay(ca);
printk("dvb_ca adapter %d: DVB CAM detected and initialised successfully\n", ca->dvbdev->adapter->num);
break;
case DVB_CA_SLOTSTATE_RUNNING:
if (!ca->open)
break;
// poll slots for data
pktcount = 0;
while ((status = dvb_ca_en50221_read_data(ca, slot, NULL, 0)) > 0) {
if (!ca->open)
break;
/* if a CAMCHANGE occurred at some point, do not do any more processing of this slot */
if (dvb_ca_en50221_check_camstatus(ca, slot)) {
// we dont want to sleep on the next iteration so we can handle the cam change
ca->wakeup = 1;
break;
}
/* check if we've hit our limit this time */
if (++pktcount >= MAX_RX_PACKETS_PER_ITERATION) {
// dont sleep; there is likely to be more data to read
ca->wakeup = 1;
break;
}
}
break;
}
mutex_unlock(&ca->slot_info[slot].slot_lock);
}
}
return 0;
}
/* ******************************************************************************** */
/* EN50221 IO interface functions */
/**
* Real ioctl implementation.
* NOTE: CA_SEND_MSG/CA_GET_MSG ioctls have userspace buffers passed to them.
*
* @param inode Inode concerned.
* @param file File concerned.
* @param cmd IOCTL command.
* @param arg Associated argument.
*
* @return 0 on success, <0 on error.
*/
static int dvb_ca_en50221_io_do_ioctl(struct file *file,
unsigned int cmd, void *parg)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err = 0;
int slot;
dprintk("%s\n", __func__);
switch (cmd) {
case CA_RESET:
for (slot = 0; slot < ca->slot_count; slot++) {
mutex_lock(&ca->slot_info[slot].slot_lock);
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE) {
dvb_ca_en50221_slot_shutdown(ca, slot);
if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)
dvb_ca_en50221_camchange_irq(ca->pub,
slot,
DVB_CA_EN50221_CAMCHANGE_INSERTED);
}
mutex_unlock(&ca->slot_info[slot].slot_lock);
}
ca->next_read_slot = 0;
dvb_ca_en50221_thread_wakeup(ca);
break;
case CA_GET_CAP: {
struct ca_caps *caps = parg;
caps->slot_num = ca->slot_count;
caps->slot_type = CA_CI_LINK;
caps->descr_num = 0;
caps->descr_type = 0;
break;
}
case CA_GET_SLOT_INFO: {
struct ca_slot_info *info = parg;
if ((info->num > ca->slot_count) || (info->num < 0))
return -EINVAL;
info->type = CA_CI_LINK;
info->flags = 0;
if ((ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_NONE)
&& (ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_INVALID)) {
info->flags = CA_CI_MODULE_PRESENT;
}
if (ca->slot_info[info->num].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
info->flags |= CA_CI_MODULE_READY;
}
break;
}
default:
err = -EINVAL;
break;
}
return err;
}
/**
* Wrapper for ioctl implementation.
*
* @param inode Inode concerned.
* @param file File concerned.
* @param cmd IOCTL command.
* @param arg Associated argument.
*
* @return 0 on success, <0 on error.
*/
static long dvb_ca_en50221_io_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return dvb_usercopy(file, cmd, arg, dvb_ca_en50221_io_do_ioctl);
}
/**
* Implementation of write() syscall.
*
* @param file File structure.
* @param buf Source buffer.
* @param count Size of source buffer.
* @param ppos Position in file (ignored).
*
* @return Number of bytes read, or <0 on error.
*/
static ssize_t dvb_ca_en50221_io_write(struct file *file,
const char __user * buf, size_t count, loff_t * ppos)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
u8 slot, connection_id;
int status;
u8 fragbuf[HOST_LINK_BUF_SIZE];
int fragpos = 0;
int fraglen;
unsigned long timeout;
int written;
dprintk("%s\n", __func__);
/* Incoming packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
if (count < 2)
return -EINVAL;
/* extract slot & connection id */
if (copy_from_user(&slot, buf, 1))
return -EFAULT;
if (copy_from_user(&connection_id, buf + 1, 1))
return -EFAULT;
buf += 2;
count -= 2;
/* check if the slot is actually running */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
return -EINVAL;
/* fragment the packets & store in the buffer */
while (fragpos < count) {
fraglen = ca->slot_info[slot].link_buf_size - 2;
if (fraglen < 0)
break;
if (fraglen > HOST_LINK_BUF_SIZE - 2)
fraglen = HOST_LINK_BUF_SIZE - 2;
if ((count - fragpos) < fraglen)
fraglen = count - fragpos;
fragbuf[0] = connection_id;
fragbuf[1] = ((fragpos + fraglen) < count) ? 0x80 : 0x00;
status = copy_from_user(fragbuf + 2, buf + fragpos, fraglen);
if (status) {
status = -EFAULT;
goto exit;
}
timeout = jiffies + HZ / 2;
written = 0;
while (!time_after(jiffies, timeout)) {
/* check the CAM hasn't been removed/reset in the meantime */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING) {
status = -EIO;
goto exit;
}
mutex_lock(&ca->slot_info[slot].slot_lock);
status = dvb_ca_en50221_write_data(ca, slot, fragbuf, fraglen + 2);
mutex_unlock(&ca->slot_info[slot].slot_lock);
if (status == (fraglen + 2)) {
written = 1;
break;
}
if (status != -EAGAIN)
goto exit;
msleep(1);
}
if (!written) {
status = -EIO;
goto exit;
}
fragpos += fraglen;
}
status = count + 2;
exit:
return status;
}
/**
* Condition for waking up in dvb_ca_en50221_io_read_condition
*/
static int dvb_ca_en50221_io_read_condition(struct dvb_ca_private *ca,
int *result, int *_slot)
{
int slot;
int slot_count = 0;
int idx;
size_t fraglen;
int connection_id = -1;
int found = 0;
u8 hdr[2];
slot = ca->next_read_slot;
while ((slot_count < ca->slot_count) && (!found)) {
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
goto nextslot;
if (ca->slot_info[slot].rx_buffer.data == NULL) {
return 0;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
while (idx != -1) {
dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
if (connection_id == -1)
connection_id = hdr[0];
if ((hdr[0] == connection_id) && ((hdr[1] & 0x80) == 0)) {
*_slot = slot;
found = 1;
break;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
}
nextslot:
slot = (slot + 1) % ca->slot_count;
slot_count++;
}
ca->next_read_slot = slot;
return found;
}
/**
* Implementation of read() syscall.
*
* @param file File structure.
* @param buf Destination buffer.
* @param count Size of destination buffer.
* @param ppos Position in file (ignored).
*
* @return Number of bytes read, or <0 on error.
*/
static ssize_t dvb_ca_en50221_io_read(struct file *file, char __user * buf,
size_t count, loff_t * ppos)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int status;
int result = 0;
u8 hdr[2];
int slot;
int connection_id = -1;
size_t idx, idx2;
int last_fragment = 0;
size_t fraglen;
int pktlen;
int dispose = 0;
dprintk("%s\n", __func__);
/* Outgoing packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
if (count < 2)
return -EINVAL;
/* wait for some data */
if ((status = dvb_ca_en50221_io_read_condition(ca, &result, &slot)) == 0) {
/* if we're in nonblocking mode, exit immediately */
if (file->f_flags & O_NONBLOCK)
return -EWOULDBLOCK;
/* wait for some data */
status = wait_event_interruptible(ca->wait_queue,
dvb_ca_en50221_io_read_condition
(ca, &result, &slot));
}
if ((status < 0) || (result < 0)) {
if (result)
return result;
return status;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
pktlen = 2;
do {
if (idx == -1) {
printk("dvb_ca adapter %d: BUG: read packet ended before last_fragment encountered\n", ca->dvbdev->adapter->num);
status = -EIO;
goto exit;
}
dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
if (connection_id == -1)
connection_id = hdr[0];
if (hdr[0] == connection_id) {
if (pktlen < count) {
if ((pktlen + fraglen - 2) > count) {
fraglen = count - pktlen;
} else {
fraglen -= 2;
}
if ((status = dvb_ringbuffer_pkt_read_user(&ca->slot_info[slot].rx_buffer, idx, 2,
buf + pktlen, fraglen)) < 0) {
goto exit;
}
pktlen += fraglen;
}
if ((hdr[1] & 0x80) == 0)
last_fragment = 1;
dispose = 1;
}
idx2 = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
if (dispose)
dvb_ringbuffer_pkt_dispose(&ca->slot_info[slot].rx_buffer, idx);
idx = idx2;
dispose = 0;
} while (!last_fragment);
hdr[0] = slot;
hdr[1] = connection_id;
status = copy_to_user(buf, hdr, 2);
if (status) {
status = -EFAULT;
goto exit;
}
status = pktlen;
exit:
return status;
}
/**
* Implementation of file open syscall.
*
* @param inode Inode concerned.
* @param file File concerned.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_io_open(struct inode *inode, struct file *file)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err;
int i;
dprintk("%s\n", __func__);
if (!try_module_get(ca->pub->owner))
return -EIO;
err = dvb_generic_open(inode, file);
if (err < 0) {
module_put(ca->pub->owner);
return err;
}
for (i = 0; i < ca->slot_count; i++) {
if (ca->slot_info[i].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
if (ca->slot_info[i].rx_buffer.data != NULL) {
/* it is safe to call this here without locks because
* ca->open == 0. Data is not read in this case */
dvb_ringbuffer_flush(&ca->slot_info[i].rx_buffer);
}
}
}
ca->open = 1;
dvb_ca_en50221_thread_update_delay(ca);
dvb_ca_en50221_thread_wakeup(ca);
return 0;
}
/**
* Implementation of file close syscall.
*
* @param inode Inode concerned.
* @param file File concerned.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_io_release(struct inode *inode, struct file *file)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err;
dprintk("%s\n", __func__);
/* mark the CA device as closed */
ca->open = 0;
dvb_ca_en50221_thread_update_delay(ca);
err = dvb_generic_release(inode, file);
module_put(ca->pub->owner);
return err;
}
/**
* Implementation of poll() syscall.
*
* @param file File concerned.
* @param wait poll wait table.
*
* @return Standard poll mask.
*/
static unsigned int dvb_ca_en50221_io_poll(struct file *file, poll_table * wait)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
unsigned int mask = 0;
int slot;
int result = 0;
dprintk("%s\n", __func__);
if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
mask |= POLLIN;
}
/* if there is something, return now */
if (mask)
return mask;
/* wait for something to happen */
poll_wait(file, &ca->wait_queue, wait);
if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
mask |= POLLIN;
}
return mask;
}
EXPORT_SYMBOL(dvb_ca_en50221_init);
static const struct file_operations dvb_ca_fops = {
.owner = THIS_MODULE,
.read = dvb_ca_en50221_io_read,
.write = dvb_ca_en50221_io_write,
.unlocked_ioctl = dvb_ca_en50221_io_ioctl,
.open = dvb_ca_en50221_io_open,
.release = dvb_ca_en50221_io_release,
.poll = dvb_ca_en50221_io_poll,
.llseek = noop_llseek,
};
static struct dvb_device dvbdev_ca = {
.priv = NULL,
.users = 1,
.readers = 1,
.writers = 1,
.fops = &dvb_ca_fops,
};
/* ******************************************************************************** */
/* Initialisation/shutdown functions */
/**
* Initialise a new DVB CA EN50221 interface device.
*
* @param dvb_adapter DVB adapter to attach the new CA device to.
* @param ca The dvb_ca instance.
* @param flags Flags describing the CA device (DVB_CA_FLAG_*).
* @param slot_count Number of slots supported.
*
* @return 0 on success, nonzero on failure
*/
int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter,
struct dvb_ca_en50221 *pubca, int flags, int slot_count)
{
int ret;
struct dvb_ca_private *ca = NULL;
int i;
dprintk("%s\n", __func__);
if (slot_count < 1)
return -EINVAL;
/* initialise the system data */
if ((ca = kzalloc(sizeof(struct dvb_ca_private), GFP_KERNEL)) == NULL) {
ret = -ENOMEM;
goto error;
}
ca->pub = pubca;
ca->flags = flags;
ca->slot_count = slot_count;
if ((ca->slot_info = kcalloc(slot_count, sizeof(struct dvb_ca_slot), GFP_KERNEL)) == NULL) {
ret = -ENOMEM;
goto error;
}
init_waitqueue_head(&ca->wait_queue);
ca->open = 0;
ca->wakeup = 0;
ca->next_read_slot = 0;
pubca->private = ca;
/* register the DVB device */
ret = dvb_register_device(dvb_adapter, &ca->dvbdev, &dvbdev_ca, ca, DVB_DEVICE_CA);
if (ret)
goto error;
/* now initialise each slot */
for (i = 0; i < slot_count; i++) {
memset(&ca->slot_info[i], 0, sizeof(struct dvb_ca_slot));
ca->slot_info[i].slot_state = DVB_CA_SLOTSTATE_NONE;
atomic_set(&ca->slot_info[i].camchange_count, 0);
ca->slot_info[i].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
mutex_init(&ca->slot_info[i].slot_lock);
}
if (signal_pending(current)) {
ret = -EINTR;
goto error;
}
mb();
/* create a kthread for monitoring this CA device */
ca->thread = kthread_run(dvb_ca_en50221_thread, ca, "kdvb-ca-%i:%i",
ca->dvbdev->adapter->num, ca->dvbdev->id);
if (IS_ERR(ca->thread)) {
ret = PTR_ERR(ca->thread);
printk("dvb_ca_init: failed to start kernel_thread (%d)\n",
ret);
goto error;
}
return 0;
error:
if (ca != NULL) {
if (ca->dvbdev != NULL)
dvb_unregister_device(ca->dvbdev);
kfree(ca->slot_info);
kfree(ca);
}
pubca->private = NULL;
return ret;
}
EXPORT_SYMBOL(dvb_ca_en50221_release);
/**
* Release a DVB CA EN50221 interface device.
*
* @param ca_dev The dvb_device_t instance for the CA device.
* @param ca The associated dvb_ca instance.
*/
void dvb_ca_en50221_release(struct dvb_ca_en50221 *pubca)
{
struct dvb_ca_private *ca = pubca->private;
int i;
dprintk("%s\n", __func__);
/* shutdown the thread if there was one */
kthread_stop(ca->thread);
for (i = 0; i < ca->slot_count; i++) {
dvb_ca_en50221_slot_shutdown(ca, i);
vfree(ca->slot_info[i].rx_buffer.data);
}
kfree(ca->slot_info);
dvb_unregister_device(ca->dvbdev);
kfree(ca);
pubca->private = NULL;
}
|
458936.c | // zhengqi_book.c 正气吟
#include <ansi.h>
inherit ITEM;
void create()
{
set_name(HIR "正气吟" NOR, ({"zhengqi_book", "book"}));
set_weight(600);
if (clonep())
set_default_object(__FILE__);
else
{
set("unit", "本");
set("long",
"这是一本薄薄的册页。\n");
set("value", 1000);
set("material", "paper");
set("skill", ([
"name":"zhengqijue", // name of the skill
"exp_required":10000, // minimum combat experience required
// to learn this skill.
"jing_cost":30,
"difficulty":30, // the base int to learn this skill
// modify is gin_cost's (difficulty - int)*5%
"max_skill":99, // the maximum level you can learn
"min_skill":0 // the maximum level you can learn
// from this object.
]));
}
}
|
89171.c | #include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 912880374
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(4, 6, 4, 4);
assert( board != NULL );
assert( gamma_move(board, 1, 3, 2) == 1 );
assert( gamma_move(board, 1, 0, 3) == 1 );
assert( gamma_move(board, 2, 2, 1) == 1 );
assert( gamma_move(board, 2, 2, 5) == 1 );
assert( gamma_move(board, 3, 3, 2) == 0 );
assert( gamma_move(board, 3, 2, 3) == 1 );
assert( gamma_move(board, 4, 0, 1) == 1 );
assert( gamma_move(board, 1, 5, 3) == 0 );
assert( gamma_move(board, 1, 0, 5) == 1 );
assert( gamma_move(board, 2, 3, 1) == 1 );
assert( gamma_move(board, 3, 0, 3) == 0 );
assert( gamma_move(board, 4, 0, 3) == 0 );
assert( gamma_move(board, 1, 1, 1) == 1 );
assert( gamma_move(board, 2, 2, 4) == 1 );
assert( gamma_move(board, 2, 2, 1) == 0 );
assert( gamma_free_fields(board, 2) == 14 );
assert( gamma_move(board, 3, 4, 0) == 0 );
assert( gamma_move(board, 3, 2, 3) == 0 );
assert( gamma_move(board, 4, 5, 3) == 0 );
assert( gamma_move(board, 1, 3, 2) == 0 );
assert( gamma_move(board, 2, 2, 1) == 0 );
assert( gamma_move(board, 2, 1, 4) == 1 );
assert( gamma_move(board, 3, 3, 3) == 1 );
assert( gamma_golden_possible(board, 3) == 1 );
assert( gamma_move(board, 4, 0, 1) == 0 );
assert( gamma_move(board, 4, 3, 3) == 0 );
assert( gamma_move(board, 1, 5, 3) == 0 );
assert( gamma_move(board, 2, 0, 3) == 0 );
assert( gamma_move(board, 3, 1, 0) == 1 );
assert( gamma_move(board, 3, 0, 4) == 1 );
assert( gamma_move(board, 4, 5, 1) == 0 );
assert( gamma_move(board, 2, 1, 1) == 0 );
assert( gamma_move(board, 2, 3, 4) == 1 );
assert( gamma_free_fields(board, 2) == 9 );
assert( gamma_golden_move(board, 2, 1, 1) == 1 );
assert( gamma_move(board, 3, 0, 4) == 0 );
assert( gamma_golden_move(board, 3, 5, 2) == 0 );
assert( gamma_move(board, 4, 2, 2) == 1 );
assert( gamma_move(board, 4, 3, 0) == 1 );
assert( gamma_busy_fields(board, 1) == 3 );
assert( gamma_move(board, 2, 1, 2) == 1 );
assert( gamma_move(board, 2, 1, 1) == 0 );
assert( gamma_move(board, 3, 5, 3) == 0 );
assert( gamma_move(board, 1, 5, 1) == 0 );
assert( gamma_move(board, 1, 1, 2) == 0 );
assert( gamma_move(board, 2, 3, 1) == 0 );
assert( gamma_move(board, 3, 5, 1) == 0 );
assert( gamma_golden_move(board, 3, 4, 1) == 0 );
assert( gamma_move(board, 4, 0, 0) == 1 );
char* board430089401 = gamma_board(board);
assert( board430089401 != NULL );
assert( strcmp(board430089401,
"1.2.\n"
"3222\n"
"1.33\n"
".241\n"
"4222\n"
"43.4\n") == 0);
free(board430089401);
board430089401 = NULL;
assert( gamma_move(board, 1, 3, 1) == 0 );
assert( gamma_move(board, 2, 5, 3) == 0 );
assert( gamma_move(board, 2, 1, 3) == 1 );
char* board584080243 = gamma_board(board);
assert( board584080243 != NULL );
assert( strcmp(board584080243,
"1.2.\n"
"3222\n"
"1233\n"
".241\n"
"4222\n"
"43.4\n") == 0);
free(board584080243);
board584080243 = NULL;
assert( gamma_move(board, 3, 0, 2) == 1 );
assert( gamma_move(board, 3, 2, 1) == 0 );
assert( gamma_free_fields(board, 3) == 1 );
assert( gamma_move(board, 4, 5, 1) == 0 );
assert( gamma_move(board, 4, 1, 0) == 0 );
assert( gamma_move(board, 1, 0, 5) == 0 );
assert( gamma_move(board, 1, 3, 3) == 0 );
assert( gamma_golden_possible(board, 1) == 1 );
assert( gamma_move(board, 2, 0, 5) == 0 );
assert( gamma_move(board, 2, 2, 0) == 1 );
assert( gamma_free_fields(board, 2) == 2 );
assert( gamma_golden_move(board, 2, 0, 3) == 0 );
assert( gamma_move(board, 3, 1, 2) == 0 );
assert( gamma_move(board, 4, 0, 3) == 0 );
assert( gamma_move(board, 1, 2, 3) == 0 );
assert( gamma_move(board, 1, 1, 4) == 0 );
assert( gamma_move(board, 2, 3, 4) == 0 );
assert( gamma_golden_move(board, 2, 2, 2) == 0 );
assert( gamma_move(board, 3, 5, 3) == 0 );
assert( gamma_move(board, 4, 5, 3) == 0 );
assert( gamma_move(board, 4, 2, 0) == 0 );
assert( gamma_busy_fields(board, 4) == 4 );
assert( gamma_move(board, 1, 5, 3) == 0 );
assert( gamma_move(board, 1, 3, 1) == 0 );
assert( gamma_move(board, 2, 3, 2) == 0 );
assert( gamma_move(board, 3, 5, 1) == 0 );
assert( gamma_move(board, 3, 0, 4) == 0 );
assert( gamma_move(board, 4, 1, 5) == 1 );
gamma_delete(board);
return 0;
}
|
551943.c | /* Mac Driver Vulkan implementation
*
* Copyright 2017 Roderick Colenbrander
* Copyright 2018 Andrew Eikum for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
/* NOTE: If making changes here, consider whether they should be reflected in
* the other drivers. */
#include "config.h"
#include <stdarg.h>
#include <stdio.h>
#include <dlfcn.h>
#include "macdrv.h"
#include "wine/debug.h"
#include "wine/heap.h"
#define VK_NO_PROTOTYPES
#define WINE_VK_HOST
#include "wine/vulkan.h"
#include "wine/vulkan_driver.h"
WINE_DEFAULT_DEBUG_CHANNEL(vulkan);
#ifdef SONAME_LIBMOLTENVK
WINE_DECLARE_DEBUG_CHANNEL(fps);
typedef VkFlags VkMacOSSurfaceCreateFlagsMVK;
#define VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK 1000123000
typedef VkFlags VkMetalSurfaceCreateFlagsEXT;
#define VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT 1000217000
struct wine_vk_surface
{
macdrv_metal_device device;
macdrv_metal_view view;
VkSurfaceKHR surface; /* native surface */
};
typedef struct VkMacOSSurfaceCreateInfoMVK
{
VkStructureType sType;
const void *pNext;
VkMacOSSurfaceCreateFlagsMVK flags;
const void *pView; /* NSView */
} VkMacOSSurfaceCreateInfoMVK;
typedef struct VkMetalSurfaceCreateInfoEXT
{
VkStructureType sType;
const void *pNext;
VkMetalSurfaceCreateFlagsEXT flags;
const void *pLayer; /* CAMetalLayer */
} VkMetalSurfaceCreateInfoEXT;
static VkResult (*pvkCreateInstance)(const VkInstanceCreateInfo *, const VkAllocationCallbacks *, VkInstance *);
static VkResult (*pvkCreateSwapchainKHR)(VkDevice, const VkSwapchainCreateInfoKHR *, const VkAllocationCallbacks *, VkSwapchainKHR *);
static VkResult (*pvkCreateMacOSSurfaceMVK)(VkInstance, const VkMacOSSurfaceCreateInfoMVK*, const VkAllocationCallbacks *, VkSurfaceKHR *);
static VkResult (*pvkCreateMetalSurfaceEXT)(VkInstance, const VkMetalSurfaceCreateInfoEXT*, const VkAllocationCallbacks *, VkSurfaceKHR *);
static void (*pvkDestroyInstance)(VkInstance, const VkAllocationCallbacks *);
static void (*pvkDestroySurfaceKHR)(VkInstance, VkSurfaceKHR, const VkAllocationCallbacks *);
static void (*pvkDestroySwapchainKHR)(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks *);
static VkResult (*pvkEnumerateInstanceExtensionProperties)(const char *, uint32_t *, VkExtensionProperties *);
static void * (*pvkGetDeviceProcAddr)(VkDevice, const char *);
static void * (*pvkGetInstanceProcAddr)(VkInstance, const char *);
static VkResult (*pvkGetPhysicalDeviceSurfaceCapabilities2KHR)(VkPhysicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR *, VkSurfaceCapabilities2KHR *);
static VkResult (*pvkGetPhysicalDeviceSurfaceCapabilitiesKHR)(VkPhysicalDevice, VkSurfaceKHR, VkSurfaceCapabilitiesKHR *);
static VkResult (*pvkGetPhysicalDeviceSurfaceFormats2KHR)(VkPhysicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR *, uint32_t *, VkSurfaceFormat2KHR *);
static VkResult (*pvkGetPhysicalDeviceSurfaceFormatsKHR)(VkPhysicalDevice, VkSurfaceKHR, uint32_t *, VkSurfaceFormatKHR *);
static VkResult (*pvkGetPhysicalDeviceSurfacePresentModesKHR)(VkPhysicalDevice, VkSurfaceKHR, uint32_t *, VkPresentModeKHR *);
static VkResult (*pvkGetPhysicalDeviceSurfaceSupportKHR)(VkPhysicalDevice, uint32_t, VkSurfaceKHR, VkBool32 *);
static VkResult (*pvkGetSwapchainImagesKHR)(VkDevice, VkSwapchainKHR, uint32_t *, VkImage *);
static VkResult (*pvkQueuePresentKHR)(VkQueue, const VkPresentInfoKHR *);
static void *macdrv_get_vk_device_proc_addr(const char *name);
static void *macdrv_get_vk_instance_proc_addr(VkInstance instance, const char *name);
static inline struct wine_vk_surface *surface_from_handle(VkSurfaceKHR handle)
{
return (struct wine_vk_surface *)(uintptr_t)handle;
}
static void *vulkan_handle;
static BOOL WINAPI wine_vk_init(INIT_ONCE *once, void *param, void **context)
{
if (!(vulkan_handle = dlopen(SONAME_LIBMOLTENVK, RTLD_NOW)))
{
ERR("Failed to load %s\n", SONAME_LIBMOLTENVK);
return TRUE;
}
#define LOAD_FUNCPTR(f) if ((p##f = dlsym(vulkan_handle, #f)) == NULL) goto fail;
LOAD_FUNCPTR(vkCreateInstance)
LOAD_FUNCPTR(vkCreateSwapchainKHR)
LOAD_FUNCPTR(vkCreateMacOSSurfaceMVK)
LOAD_FUNCPTR(vkCreateMetalSurfaceEXT)
LOAD_FUNCPTR(vkDestroyInstance)
LOAD_FUNCPTR(vkDestroySurfaceKHR)
LOAD_FUNCPTR(vkDestroySwapchainKHR)
LOAD_FUNCPTR(vkEnumerateInstanceExtensionProperties)
LOAD_FUNCPTR(vkGetDeviceProcAddr)
LOAD_FUNCPTR(vkGetInstanceProcAddr)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfaceCapabilities2KHR)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfaceFormats2KHR)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfaceFormatsKHR)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfacePresentModesKHR)
LOAD_FUNCPTR(vkGetPhysicalDeviceSurfaceSupportKHR)
LOAD_FUNCPTR(vkGetSwapchainImagesKHR)
LOAD_FUNCPTR(vkQueuePresentKHR)
#undef LOAD_FUNCPTR
return TRUE;
fail:
dlclose(vulkan_handle);
vulkan_handle = NULL;
return TRUE;
}
/* Helper function for converting between win32 and MoltenVK compatible VkInstanceCreateInfo.
* Caller is responsible for allocation and cleanup of 'dst'.
*/
static VkResult wine_vk_instance_convert_create_info(const VkInstanceCreateInfo *src,
VkInstanceCreateInfo *dst)
{
unsigned int i;
const char **enabled_extensions = NULL;
dst->sType = src->sType;
dst->flags = src->flags;
dst->pApplicationInfo = src->pApplicationInfo;
dst->pNext = src->pNext;
dst->enabledLayerCount = 0;
dst->ppEnabledLayerNames = NULL;
dst->enabledExtensionCount = 0;
dst->ppEnabledExtensionNames = NULL;
if (src->enabledExtensionCount > 0)
{
enabled_extensions = heap_calloc(src->enabledExtensionCount, sizeof(*src->ppEnabledExtensionNames));
if (!enabled_extensions)
{
ERR("Failed to allocate memory for enabled extensions\n");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
for (i = 0; i < src->enabledExtensionCount; i++)
{
/* Substitute extension with MoltenVK ones else copy. Long-term, when we
* support more extensions, we should store these in a list.
*/
if (!strcmp(src->ppEnabledExtensionNames[i], "VK_KHR_win32_surface"))
{
enabled_extensions[i] = pvkCreateMetalSurfaceEXT ? "VK_EXT_metal_surface" : "VK_MVK_macos_surface";
}
else
{
enabled_extensions[i] = src->ppEnabledExtensionNames[i];
}
}
dst->ppEnabledExtensionNames = enabled_extensions;
dst->enabledExtensionCount = src->enabledExtensionCount;
}
return VK_SUCCESS;
}
static void wine_vk_surface_destroy(VkInstance instance, struct wine_vk_surface *surface)
{
/* vkDestroySurfaceKHR must handle VK_NULL_HANDLE (0) for surface. */
if (!surface)
return;
pvkDestroySurfaceKHR(instance, surface->surface, NULL /* allocator */);
if (surface->view)
macdrv_view_release_metal_view(surface->view);
if (surface->device)
macdrv_release_metal_device(surface->device);
heap_free(surface);
}
static VkResult macdrv_vkCreateInstance(const VkInstanceCreateInfo *create_info,
const VkAllocationCallbacks *allocator, VkInstance *instance)
{
VkInstanceCreateInfo create_info_host;
VkResult res;
TRACE("create_info %p, allocator %p, instance %p\n", create_info, allocator, instance);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
/* Perform a second pass on converting VkInstanceCreateInfo. Winevulkan
* performed a first pass in which it handles everything except for WSI
* functionality such as VK_KHR_win32_surface. Handle this now.
*/
res = wine_vk_instance_convert_create_info(create_info, &create_info_host);
if (res != VK_SUCCESS)
{
ERR("Failed to convert instance create info, res=%d\n", res);
return res;
}
res = pvkCreateInstance(&create_info_host, NULL /* allocator */, instance);
heap_free((void *)create_info_host.ppEnabledExtensionNames);
return res;
}
static VkResult macdrv_vkCreateSwapchainKHR(VkDevice device,
const VkSwapchainCreateInfoKHR *create_info,
const VkAllocationCallbacks *allocator, VkSwapchainKHR *swapchain)
{
VkSwapchainCreateInfoKHR create_info_host;
TRACE("%p %p %p %p\n", device, create_info, allocator, swapchain);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
create_info_host = *create_info;
create_info_host.surface = surface_from_handle(create_info->surface)->surface;
return pvkCreateSwapchainKHR(device, &create_info_host, NULL /* allocator */,
swapchain);
}
static VkResult macdrv_vkCreateWin32SurfaceKHR(VkInstance instance,
const VkWin32SurfaceCreateInfoKHR *create_info,
const VkAllocationCallbacks *allocator, VkSurfaceKHR *surface)
{
VkResult res;
struct wine_vk_surface *mac_surface;
struct macdrv_win_data *data;
TRACE("%p %p %p %p\n", instance, create_info, allocator, surface);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
if (!(data = get_win_data(create_info->hwnd)))
{
FIXME("DC for window %p of other process: not implemented\n", create_info->hwnd);
return VK_ERROR_INCOMPATIBLE_DRIVER;
}
mac_surface = heap_alloc_zero(sizeof(*mac_surface));
if (!mac_surface)
{
release_win_data(data);
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
mac_surface->device = macdrv_create_metal_device();
if (!mac_surface->device)
{
ERR("Failed to allocate Metal device for hwnd=%p\n", create_info->hwnd);
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto err;
}
mac_surface->view = macdrv_view_create_metal_view(data->client_cocoa_view, mac_surface->device);
if (!mac_surface->view)
{
ERR("Failed to allocate Metal view for hwnd=%p\n", create_info->hwnd);
/* VK_KHR_win32_surface only allows out of host and device memory as errors. */
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto err;
}
if (pvkCreateMetalSurfaceEXT)
{
VkMetalSurfaceCreateInfoEXT create_info_host;
create_info_host.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
create_info_host.pNext = NULL;
create_info_host.flags = 0; /* reserved */
create_info_host.pLayer = macdrv_view_get_metal_layer(mac_surface->view);
res = pvkCreateMetalSurfaceEXT(instance, &create_info_host, NULL /* allocator */, &mac_surface->surface);
}
else
{
VkMacOSSurfaceCreateInfoMVK create_info_host;
create_info_host.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
create_info_host.pNext = NULL;
create_info_host.flags = 0; /* reserved */
create_info_host.pView = macdrv_view_get_metal_layer(mac_surface->view);
res = pvkCreateMacOSSurfaceMVK(instance, &create_info_host, NULL /* allocator */, &mac_surface->surface);
}
if (res != VK_SUCCESS)
{
ERR("Failed to create MoltenVK surface, res=%d\n", res);
goto err;
}
*surface = (uintptr_t)mac_surface;
release_win_data(data);
TRACE("Created surface=0x%s\n", wine_dbgstr_longlong(*surface));
return VK_SUCCESS;
err:
wine_vk_surface_destroy(instance, mac_surface);
release_win_data(data);
return res;
}
static void macdrv_vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *allocator)
{
TRACE("%p %p\n", instance, allocator);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
pvkDestroyInstance(instance, NULL /* allocator */);
}
static void macdrv_vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface,
const VkAllocationCallbacks *allocator)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("%p 0x%s %p\n", instance, wine_dbgstr_longlong(surface), allocator);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
wine_vk_surface_destroy(instance, mac_surface);
}
static void macdrv_vkDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
const VkAllocationCallbacks *allocator)
{
TRACE("%p, 0x%s %p\n", device, wine_dbgstr_longlong(swapchain), allocator);
if (allocator)
FIXME("Support for allocation callbacks not implemented yet\n");
pvkDestroySwapchainKHR(device, swapchain, NULL /* allocator */);
}
static VkResult macdrv_vkEnumerateInstanceExtensionProperties(const char *layer_name,
uint32_t *count, VkExtensionProperties* properties)
{
unsigned int i;
BOOL seen_surface = FALSE;
VkResult res;
TRACE("layer_name %s, count %p, properties %p\n", debugstr_a(layer_name), count, properties);
/* This shouldn't get called with layer_name set, the ICD loader prevents it. */
if (layer_name)
{
ERR("Layer enumeration not supported from ICD.\n");
return VK_ERROR_LAYER_NOT_PRESENT;
}
/* We will return at most the same number of instance extensions reported by the host back to
* winevulkan. Along the way we may replace MoltenVK extensions with their win32 equivalents,
* or remove redundant extensions outright.
* Winevulkan will perform more detailed filtering as it knows whether it has thunks
* for a particular extension.
*/
res = pvkEnumerateInstanceExtensionProperties(layer_name, count, properties);
if (!properties || res < 0)
return res;
for (i = 0; i < *count; i++)
{
/* For now the only MoltenVK extensions we need to fixup. Long-term we may need an array. */
if (!strcmp(properties[i].extensionName, "VK_MVK_macos_surface") ||
!strcmp(properties[i].extensionName, "VK_EXT_metal_surface"))
{
if (seen_surface)
{
/* If we've already seen a surface extension, just hide this one. */
memmove(properties + i, properties + i + 1, (*count - i - 1) * sizeof(*properties));
--*count;
--i;
continue;
}
TRACE("Substituting %s for VK_KHR_win32_surface\n", properties[i].extensionName);
snprintf(properties[i].extensionName, sizeof(properties[i].extensionName),
VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
properties[i].specVersion = VK_KHR_WIN32_SURFACE_SPEC_VERSION;
seen_surface = TRUE;
}
}
TRACE("Returning %u extensions.\n", *count);
return res;
}
static const char *wine_vk_native_fn_name(const char *name)
{
const char *create_surface_name =
pvkCreateMetalSurfaceEXT ? "vkCreateMetalSurfaceEXT" : "vkCreateMacOSSurfaceMVK";
if (!strcmp(name, "vkCreateWin32SurfaceKHR"))
return create_surface_name;
/* We just need something where non-NULL is returned if the correct extension is enabled.
* So since there is no native equivalent of this function check for the create
* surface function.
*/
if (!strcmp(name, "vkGetPhysicalDeviceWin32PresentationSupportKHR"))
return create_surface_name;
return name;
}
static void *macdrv_vkGetDeviceProcAddr(VkDevice device, const char *name)
{
void *proc_addr;
TRACE("%p, %s\n", device, debugstr_a(name));
if (!pvkGetDeviceProcAddr(device, wine_vk_native_fn_name(name)))
return NULL;
if ((proc_addr = macdrv_get_vk_device_proc_addr(name)))
return proc_addr;
return pvkGetDeviceProcAddr(device, name);
}
static void *macdrv_vkGetInstanceProcAddr(VkInstance instance, const char *name)
{
void *proc_addr;
TRACE("%p, %s\n", instance, debugstr_a(name));
if (!pvkGetInstanceProcAddr(instance, wine_vk_native_fn_name(name)))
return NULL;
if ((proc_addr = macdrv_get_vk_instance_proc_addr(instance, name)))
return proc_addr;
return pvkGetInstanceProcAddr(instance, name);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice phys_dev,
const VkPhysicalDeviceSurfaceInfo2KHR *surface_info, VkSurfaceCapabilities2KHR *capabilities)
{
VkPhysicalDeviceSurfaceInfo2KHR surface_info_host;
TRACE("%p, %p, %p\n", phys_dev, surface_info, capabilities);
surface_info_host = *surface_info;
surface_info_host.surface = surface_from_handle(surface_info->surface)->surface;
return pvkGetPhysicalDeviceSurfaceCapabilities2KHR(phys_dev, &surface_info_host, capabilities);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice phys_dev,
VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR *capabilities)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("%p, 0x%s, %p\n", phys_dev, wine_dbgstr_longlong(surface), capabilities);
return pvkGetPhysicalDeviceSurfaceCapabilitiesKHR(phys_dev, mac_surface->surface,
capabilities);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice phys_dev,
const VkPhysicalDeviceSurfaceInfo2KHR *surface_info, uint32_t *count, VkSurfaceFormat2KHR *formats)
{
VkPhysicalDeviceSurfaceInfo2KHR surface_info_host;
TRACE("%p, %p, %p, %p\n", phys_dev, surface_info, count, formats);
surface_info_host = *surface_info;
surface_info_host.surface = surface_from_handle(surface_info->surface)->surface;
return pvkGetPhysicalDeviceSurfaceFormats2KHR(phys_dev, &surface_info_host, count, formats);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice phys_dev,
VkSurfaceKHR surface, uint32_t *count, VkSurfaceFormatKHR *formats)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("%p, 0x%s, %p, %p\n", phys_dev, wine_dbgstr_longlong(surface), count, formats);
return pvkGetPhysicalDeviceSurfaceFormatsKHR(phys_dev, mac_surface->surface,
count, formats);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice phys_dev,
VkSurfaceKHR surface, uint32_t *count, VkPresentModeKHR *modes)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("%p, 0x%s, %p, %p\n", phys_dev, wine_dbgstr_longlong(surface), count, modes);
return pvkGetPhysicalDeviceSurfacePresentModesKHR(phys_dev, mac_surface->surface, count,
modes);
}
static VkResult macdrv_vkGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice phys_dev,
uint32_t index, VkSurfaceKHR surface, VkBool32 *supported)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("%p, %u, 0x%s, %p\n", phys_dev, index, wine_dbgstr_longlong(surface), supported);
return pvkGetPhysicalDeviceSurfaceSupportKHR(phys_dev, index, mac_surface->surface,
supported);
}
static VkBool32 macdrv_vkGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice phys_dev,
uint32_t index)
{
TRACE("%p %u\n", phys_dev, index);
return VK_TRUE;
}
static VkResult macdrv_vkGetSwapchainImagesKHR(VkDevice device,
VkSwapchainKHR swapchain, uint32_t *count, VkImage *images)
{
TRACE("%p, 0x%s %p %p\n", device, wine_dbgstr_longlong(swapchain), count, images);
return pvkGetSwapchainImagesKHR(device, swapchain, count, images);
}
static VkResult macdrv_vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *present_info)
{
TRACE("%p, %p\n", queue, present_info);
VkResult res = pvkQueuePresentKHR(queue, present_info);
if (TRACE_ON(fps))
{
static unsigned long frames, frames_total;
static long prev_time, start_time;
DWORD time;
time = GetTickCount();
frames++;
frames_total++;
if (time - prev_time > 1500)
{
TRACE_(fps)("%p @ approx %.2ffps, total %.2ffps\n",
queue, 1000.0 * frames / (time - prev_time),
1000.0 * frames_total / (time - start_time));
prev_time = time;
frames = 0;
if (!start_time)
start_time = time;
}
}
return res;
}
static VkSurfaceKHR macdrv_wine_get_native_surface(VkSurfaceKHR surface)
{
struct wine_vk_surface *mac_surface = surface_from_handle(surface);
TRACE("0x%s\n", wine_dbgstr_longlong(surface));
return mac_surface->surface;
}
static const struct vulkan_funcs vulkan_funcs =
{
macdrv_vkCreateInstance,
macdrv_vkCreateSwapchainKHR,
macdrv_vkCreateWin32SurfaceKHR,
macdrv_vkDestroyInstance,
macdrv_vkDestroySurfaceKHR,
macdrv_vkDestroySwapchainKHR,
macdrv_vkEnumerateInstanceExtensionProperties,
NULL,
macdrv_vkGetDeviceProcAddr,
macdrv_vkGetInstanceProcAddr,
NULL,
macdrv_vkGetPhysicalDeviceSurfaceCapabilities2KHR,
macdrv_vkGetPhysicalDeviceSurfaceCapabilitiesKHR,
macdrv_vkGetPhysicalDeviceSurfaceFormats2KHR,
macdrv_vkGetPhysicalDeviceSurfaceFormatsKHR,
macdrv_vkGetPhysicalDeviceSurfacePresentModesKHR,
macdrv_vkGetPhysicalDeviceSurfaceSupportKHR,
macdrv_vkGetPhysicalDeviceWin32PresentationSupportKHR,
macdrv_vkGetSwapchainImagesKHR,
macdrv_vkQueuePresentKHR,
macdrv_wine_get_native_surface,
};
static void *macdrv_get_vk_device_proc_addr(const char *name)
{
return get_vulkan_driver_device_proc_addr(&vulkan_funcs, name);
}
static void *macdrv_get_vk_instance_proc_addr(VkInstance instance, const char *name)
{
return get_vulkan_driver_instance_proc_addr(&vulkan_funcs, instance, name);
}
static const struct vulkan_funcs *get_vulkan_driver(UINT version)
{
static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
if (version != WINE_VULKAN_DRIVER_VERSION)
{
ERR("version mismatch, vulkan wants %u but driver has %u\n", version, WINE_VULKAN_DRIVER_VERSION);
return NULL;
}
InitOnceExecuteOnce(&init_once, wine_vk_init, NULL, NULL);
if (vulkan_handle)
return &vulkan_funcs;
return NULL;
}
#else /* No vulkan */
static const struct vulkan_funcs *get_vulkan_driver(UINT version)
{
ERR("Wine was built without Vulkan support.\n");
return NULL;
}
#endif /* SONAME_LIBMOLTENVK */
const struct vulkan_funcs * CDECL macdrv_wine_get_vulkan_driver(PHYSDEV dev, UINT version)
{
const struct vulkan_funcs *ret;
if (!(ret = get_vulkan_driver( version )))
{
dev = GET_NEXT_PHYSDEV( dev, wine_get_vulkan_driver );
ret = dev->funcs->wine_get_vulkan_driver( dev, version );
}
return ret;
}
|
26933.c | /*
* OpenRISC translation
*
* Copyright (c) 2011-2012 Jia Liu <[email protected]>
* Feng Gao <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "cpu.h"
#include "exec/exec-all.h"
#include "disas/disas.h"
#include "tcg-op.h"
#include "qemu-common.h"
#include "qemu/log.h"
#include "qemu/bitops.h"
#include "exec/cpu_ldst.h"
#include "exec/helper-proto.h"
#include "exec/helper-gen.h"
#include "trace-tcg.h"
#include "exec/log.h"
#define LOG_DIS(str, ...) \
qemu_log_mask(CPU_LOG_TB_IN_ASM, "%08x: " str, dc->pc, ## __VA_ARGS__)
typedef struct DisasContext {
TranslationBlock *tb;
target_ulong pc;
uint32_t is_jmp;
uint32_t mem_idx;
uint32_t tb_flags;
uint32_t delayed_branch;
bool singlestep_enabled;
} DisasContext;
static TCGv_env cpu_env;
static TCGv cpu_sr;
static TCGv cpu_R[32];
static TCGv cpu_R0;
static TCGv cpu_pc;
static TCGv jmp_pc; /* l.jr/l.jalr temp pc */
static TCGv cpu_ppc;
static TCGv cpu_sr_f; /* bf/bnf, F flag taken */
static TCGv cpu_sr_cy; /* carry (unsigned overflow) */
static TCGv cpu_sr_ov; /* signed overflow */
static TCGv cpu_lock_addr;
static TCGv cpu_lock_value;
static TCGv_i32 fpcsr;
static TCGv_i64 cpu_mac; /* MACHI:MACLO */
static TCGv_i32 cpu_dflag;
#include "exec/gen-icount.h"
void openrisc_translate_init(void)
{
static const char * const regnames[] = {
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
};
int i;
cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
tcg_ctx.tcg_env = cpu_env;
cpu_sr = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, sr), "sr");
cpu_dflag = tcg_global_mem_new_i32(cpu_env,
offsetof(CPUOpenRISCState, dflag),
"dflag");
cpu_pc = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, pc), "pc");
cpu_ppc = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, ppc), "ppc");
jmp_pc = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, jmp_pc), "jmp_pc");
cpu_sr_f = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, sr_f), "sr_f");
cpu_sr_cy = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, sr_cy), "sr_cy");
cpu_sr_ov = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, sr_ov), "sr_ov");
cpu_lock_addr = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, lock_addr),
"lock_addr");
cpu_lock_value = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState, lock_value),
"lock_value");
fpcsr = tcg_global_mem_new_i32(cpu_env,
offsetof(CPUOpenRISCState, fpcsr),
"fpcsr");
cpu_mac = tcg_global_mem_new_i64(cpu_env,
offsetof(CPUOpenRISCState, mac),
"mac");
for (i = 0; i < 32; i++) {
cpu_R[i] = tcg_global_mem_new(cpu_env,
offsetof(CPUOpenRISCState,
shadow_gpr[0][i]),
regnames[i]);
}
cpu_R0 = cpu_R[0];
}
static void gen_exception(DisasContext *dc, unsigned int excp)
{
TCGv_i32 tmp = tcg_const_i32(excp);
gen_helper_exception(cpu_env, tmp);
tcg_temp_free_i32(tmp);
}
static void gen_illegal_exception(DisasContext *dc)
{
tcg_gen_movi_tl(cpu_pc, dc->pc);
gen_exception(dc, EXCP_ILLEGAL);
dc->is_jmp = DISAS_UPDATE;
}
/* not used yet, open it when we need or64. */
/*#ifdef TARGET_OPENRISC64
static void check_ob64s(DisasContext *dc)
{
if (!(dc->flags & CPUCFGR_OB64S)) {
gen_illegal_exception(dc);
}
}
static void check_of64s(DisasContext *dc)
{
if (!(dc->flags & CPUCFGR_OF64S)) {
gen_illegal_exception(dc);
}
}
static void check_ov64s(DisasContext *dc)
{
if (!(dc->flags & CPUCFGR_OV64S)) {
gen_illegal_exception(dc);
}
}
#endif*/
/* We're about to write to REG. On the off-chance that the user is
writing to R0, re-instate the architectural register. */
#define check_r0_write(reg) \
do { \
if (unlikely(reg == 0)) { \
cpu_R[0] = cpu_R0; \
} \
} while (0)
static inline bool use_goto_tb(DisasContext *dc, target_ulong dest)
{
if (unlikely(dc->singlestep_enabled)) {
return false;
}
#ifndef CONFIG_USER_ONLY
return (dc->tb->pc & TARGET_PAGE_MASK) == (dest & TARGET_PAGE_MASK);
#else
return true;
#endif
}
static void gen_goto_tb(DisasContext *dc, int n, target_ulong dest)
{
if (use_goto_tb(dc, dest)) {
tcg_gen_movi_tl(cpu_pc, dest);
tcg_gen_goto_tb(n);
tcg_gen_exit_tb((uintptr_t)dc->tb + n);
} else {
tcg_gen_movi_tl(cpu_pc, dest);
if (dc->singlestep_enabled) {
gen_exception(dc, EXCP_DEBUG);
}
tcg_gen_exit_tb(0);
}
}
static void gen_jump(DisasContext *dc, int32_t n26, uint32_t reg, uint32_t op0)
{
target_ulong tmp_pc = dc->pc + n26 * 4;
switch (op0) {
case 0x00: /* l.j */
tcg_gen_movi_tl(jmp_pc, tmp_pc);
break;
case 0x01: /* l.jal */
tcg_gen_movi_tl(cpu_R[9], dc->pc + 8);
/* Optimize jal being used to load the PC for PIC. */
if (tmp_pc == dc->pc + 8) {
return;
}
tcg_gen_movi_tl(jmp_pc, tmp_pc);
break;
case 0x03: /* l.bnf */
case 0x04: /* l.bf */
{
TCGv t_next = tcg_const_tl(dc->pc + 8);
TCGv t_true = tcg_const_tl(tmp_pc);
TCGv t_zero = tcg_const_tl(0);
tcg_gen_movcond_tl(op0 == 0x03 ? TCG_COND_EQ : TCG_COND_NE,
jmp_pc, cpu_sr_f, t_zero, t_true, t_next);
tcg_temp_free(t_next);
tcg_temp_free(t_true);
tcg_temp_free(t_zero);
}
break;
case 0x11: /* l.jr */
tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);
break;
case 0x12: /* l.jalr */
tcg_gen_movi_tl(cpu_R[9], (dc->pc + 8));
tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);
break;
default:
gen_illegal_exception(dc);
break;
}
dc->delayed_branch = 2;
}
static void gen_ove_cy(DisasContext *dc)
{
if (dc->tb_flags & SR_OVE) {
gen_helper_ove_cy(cpu_env);
}
}
static void gen_ove_ov(DisasContext *dc)
{
if (dc->tb_flags & SR_OVE) {
gen_helper_ove_ov(cpu_env);
}
}
static void gen_ove_cyov(DisasContext *dc)
{
if (dc->tb_flags & SR_OVE) {
gen_helper_ove_cyov(cpu_env);
}
}
static void gen_add(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv t0 = tcg_const_tl(0);
TCGv res = tcg_temp_new();
tcg_gen_add2_tl(res, cpu_sr_cy, srca, t0, srcb, t0);
tcg_gen_xor_tl(cpu_sr_ov, srca, srcb);
tcg_gen_xor_tl(t0, res, srcb);
tcg_gen_andc_tl(cpu_sr_ov, t0, cpu_sr_ov);
tcg_temp_free(t0);
tcg_gen_mov_tl(dest, res);
tcg_temp_free(res);
gen_ove_cyov(dc);
}
static void gen_addc(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv t0 = tcg_const_tl(0);
TCGv res = tcg_temp_new();
tcg_gen_add2_tl(res, cpu_sr_cy, srca, t0, cpu_sr_cy, t0);
tcg_gen_add2_tl(res, cpu_sr_cy, res, cpu_sr_cy, srcb, t0);
tcg_gen_xor_tl(cpu_sr_ov, srca, srcb);
tcg_gen_xor_tl(t0, res, srcb);
tcg_gen_andc_tl(cpu_sr_ov, t0, cpu_sr_ov);
tcg_temp_free(t0);
tcg_gen_mov_tl(dest, res);
tcg_temp_free(res);
gen_ove_cyov(dc);
}
static void gen_sub(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv res = tcg_temp_new();
tcg_gen_sub_tl(res, srca, srcb);
tcg_gen_xor_tl(cpu_sr_cy, srca, srcb);
tcg_gen_xor_tl(cpu_sr_ov, res, srcb);
tcg_gen_and_tl(cpu_sr_ov, cpu_sr_ov, cpu_sr_cy);
tcg_gen_setcond_tl(TCG_COND_LTU, cpu_sr_cy, srca, srcb);
tcg_gen_mov_tl(dest, res);
tcg_temp_free(res);
gen_ove_cyov(dc);
}
static void gen_mul(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv t0 = tcg_temp_new();
tcg_gen_muls2_tl(dest, cpu_sr_ov, srca, srcb);
tcg_gen_sari_tl(t0, dest, TARGET_LONG_BITS - 1);
tcg_gen_setcond_tl(TCG_COND_NE, cpu_sr_ov, cpu_sr_ov, t0);
tcg_temp_free(t0);
tcg_gen_neg_tl(cpu_sr_ov, cpu_sr_ov);
gen_ove_ov(dc);
}
static void gen_mulu(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
tcg_gen_muls2_tl(dest, cpu_sr_cy, srca, srcb);
tcg_gen_setcondi_tl(TCG_COND_NE, cpu_sr_cy, cpu_sr_cy, 0);
gen_ove_cy(dc);
}
static void gen_div(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv t0 = tcg_temp_new();
tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_sr_ov, srcb, 0);
/* The result of divide-by-zero is undefined.
Supress the host-side exception by dividing by 1. */
tcg_gen_or_tl(t0, srcb, cpu_sr_ov);
tcg_gen_div_tl(dest, srca, t0);
tcg_temp_free(t0);
tcg_gen_neg_tl(cpu_sr_ov, cpu_sr_ov);
gen_ove_ov(dc);
}
static void gen_divu(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)
{
TCGv t0 = tcg_temp_new();
tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_sr_cy, srcb, 0);
/* The result of divide-by-zero is undefined.
Supress the host-side exception by dividing by 1. */
tcg_gen_or_tl(t0, srcb, cpu_sr_cy);
tcg_gen_divu_tl(dest, srca, t0);
tcg_temp_free(t0);
gen_ove_cy(dc);
}
static void gen_muld(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_ext_tl_i64(t1, srca);
tcg_gen_ext_tl_i64(t2, srcb);
if (TARGET_LONG_BITS == 32) {
tcg_gen_mul_i64(cpu_mac, t1, t2);
tcg_gen_movi_tl(cpu_sr_ov, 0);
} else {
TCGv_i64 high = tcg_temp_new_i64();
tcg_gen_muls2_i64(cpu_mac, high, t1, t2);
tcg_gen_sari_i64(t1, cpu_mac, 63);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t1, high);
tcg_temp_free_i64(high);
tcg_gen_trunc_i64_tl(cpu_sr_ov, t1);
tcg_gen_neg_tl(cpu_sr_ov, cpu_sr_ov);
gen_ove_ov(dc);
}
tcg_temp_free_i64(t1);
tcg_temp_free_i64(t2);
}
static void gen_muldu(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_extu_tl_i64(t1, srca);
tcg_gen_extu_tl_i64(t2, srcb);
if (TARGET_LONG_BITS == 32) {
tcg_gen_mul_i64(cpu_mac, t1, t2);
tcg_gen_movi_tl(cpu_sr_cy, 0);
} else {
TCGv_i64 high = tcg_temp_new_i64();
tcg_gen_mulu2_i64(cpu_mac, high, t1, t2);
tcg_gen_setcondi_i64(TCG_COND_NE, high, high, 0);
tcg_gen_trunc_i64_tl(cpu_sr_cy, high);
tcg_temp_free_i64(high);
gen_ove_cy(dc);
}
tcg_temp_free_i64(t1);
tcg_temp_free_i64(t2);
}
static void gen_mac(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_ext_tl_i64(t1, srca);
tcg_gen_ext_tl_i64(t2, srcb);
tcg_gen_mul_i64(t1, t1, t2);
/* Note that overflow is only computed during addition stage. */
tcg_gen_xor_i64(t2, cpu_mac, t1);
tcg_gen_add_i64(cpu_mac, cpu_mac, t1);
tcg_gen_xor_i64(t1, t1, cpu_mac);
tcg_gen_andc_i64(t1, t1, t2);
tcg_temp_free_i64(t2);
#if TARGET_LONG_BITS == 32
tcg_gen_extrh_i64_i32(cpu_sr_ov, t1);
#else
tcg_gen_mov_i64(cpu_sr_ov, t1);
#endif
tcg_temp_free_i64(t1);
gen_ove_ov(dc);
}
static void gen_macu(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_extu_tl_i64(t1, srca);
tcg_gen_extu_tl_i64(t2, srcb);
tcg_gen_mul_i64(t1, t1, t2);
tcg_temp_free_i64(t2);
/* Note that overflow is only computed during addition stage. */
tcg_gen_add_i64(cpu_mac, cpu_mac, t1);
tcg_gen_setcond_i64(TCG_COND_LTU, t1, cpu_mac, t1);
tcg_gen_trunc_i64_tl(cpu_sr_cy, t1);
tcg_temp_free_i64(t1);
gen_ove_cy(dc);
}
static void gen_msb(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_ext_tl_i64(t1, srca);
tcg_gen_ext_tl_i64(t2, srcb);
tcg_gen_mul_i64(t1, t1, t2);
/* Note that overflow is only computed during subtraction stage. */
tcg_gen_xor_i64(t2, cpu_mac, t1);
tcg_gen_sub_i64(cpu_mac, cpu_mac, t1);
tcg_gen_xor_i64(t1, t1, cpu_mac);
tcg_gen_and_i64(t1, t1, t2);
tcg_temp_free_i64(t2);
#if TARGET_LONG_BITS == 32
tcg_gen_extrh_i64_i32(cpu_sr_ov, t1);
#else
tcg_gen_mov_i64(cpu_sr_ov, t1);
#endif
tcg_temp_free_i64(t1);
gen_ove_ov(dc);
}
static void gen_msbu(DisasContext *dc, TCGv srca, TCGv srcb)
{
TCGv_i64 t1 = tcg_temp_new_i64();
TCGv_i64 t2 = tcg_temp_new_i64();
tcg_gen_extu_tl_i64(t1, srca);
tcg_gen_extu_tl_i64(t2, srcb);
tcg_gen_mul_i64(t1, t1, t2);
/* Note that overflow is only computed during subtraction stage. */
tcg_gen_setcond_i64(TCG_COND_LTU, t2, cpu_mac, t1);
tcg_gen_sub_i64(cpu_mac, cpu_mac, t1);
tcg_gen_trunc_i64_tl(cpu_sr_cy, t2);
tcg_temp_free_i64(t2);
tcg_temp_free_i64(t1);
gen_ove_cy(dc);
}
static void gen_lwa(DisasContext *dc, TCGv rd, TCGv ra, int32_t ofs)
{
TCGv ea = tcg_temp_new();
tcg_gen_addi_tl(ea, ra, ofs);
tcg_gen_qemu_ld_tl(rd, ea, dc->mem_idx, MO_TEUL);
tcg_gen_mov_tl(cpu_lock_addr, ea);
tcg_gen_mov_tl(cpu_lock_value, rd);
tcg_temp_free(ea);
}
static void gen_swa(DisasContext *dc, int b, TCGv ra, int32_t ofs)
{
TCGv ea, val;
TCGLabel *lab_fail, *lab_done;
ea = tcg_temp_new();
tcg_gen_addi_tl(ea, ra, ofs);
/* For TB_FLAGS_R0_0, the branch below invalidates the temporary assigned
to cpu_R[0]. Since l.swa is quite often immediately followed by a
branch, don't bother reallocating; finish the TB using the "real" R0.
This also takes care of RB input across the branch. */
cpu_R[0] = cpu_R0;
lab_fail = gen_new_label();
lab_done = gen_new_label();
tcg_gen_brcond_tl(TCG_COND_NE, ea, cpu_lock_addr, lab_fail);
tcg_temp_free(ea);
val = tcg_temp_new();
tcg_gen_atomic_cmpxchg_tl(val, cpu_lock_addr, cpu_lock_value,
cpu_R[b], dc->mem_idx, MO_TEUL);
tcg_gen_setcond_tl(TCG_COND_EQ, cpu_sr_f, val, cpu_lock_value);
tcg_temp_free(val);
tcg_gen_br(lab_done);
gen_set_label(lab_fail);
tcg_gen_movi_tl(cpu_sr_f, 0);
gen_set_label(lab_done);
tcg_gen_movi_tl(cpu_lock_addr, -1);
}
static void dec_calc(DisasContext *dc, uint32_t insn)
{
uint32_t op0, op1, op2;
uint32_t ra, rb, rd;
op0 = extract32(insn, 0, 4);
op1 = extract32(insn, 8, 2);
op2 = extract32(insn, 6, 2);
ra = extract32(insn, 16, 5);
rb = extract32(insn, 11, 5);
rd = extract32(insn, 21, 5);
switch (op1) {
case 0:
switch (op0) {
case 0x0: /* l.add */
LOG_DIS("l.add r%d, r%d, r%d\n", rd, ra, rb);
gen_add(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x1: /* l.addc */
LOG_DIS("l.addc r%d, r%d, r%d\n", rd, ra, rb);
gen_addc(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x2: /* l.sub */
LOG_DIS("l.sub r%d, r%d, r%d\n", rd, ra, rb);
gen_sub(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x3: /* l.and */
LOG_DIS("l.and r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_and_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x4: /* l.or */
LOG_DIS("l.or r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_or_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x5: /* l.xor */
LOG_DIS("l.xor r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_xor_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x8:
switch (op2) {
case 0: /* l.sll */
LOG_DIS("l.sll r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_shl_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 1: /* l.srl */
LOG_DIS("l.srl r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_shr_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 2: /* l.sra */
LOG_DIS("l.sra r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_sar_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 3: /* l.ror */
LOG_DIS("l.ror r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_rotr_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
}
break;
case 0xc:
switch (op2) {
case 0: /* l.exths */
LOG_DIS("l.exths r%d, r%d\n", rd, ra);
tcg_gen_ext16s_tl(cpu_R[rd], cpu_R[ra]);
return;
case 1: /* l.extbs */
LOG_DIS("l.extbs r%d, r%d\n", rd, ra);
tcg_gen_ext8s_tl(cpu_R[rd], cpu_R[ra]);
return;
case 2: /* l.exthz */
LOG_DIS("l.exthz r%d, r%d\n", rd, ra);
tcg_gen_ext16u_tl(cpu_R[rd], cpu_R[ra]);
return;
case 3: /* l.extbz */
LOG_DIS("l.extbz r%d, r%d\n", rd, ra);
tcg_gen_ext8u_tl(cpu_R[rd], cpu_R[ra]);
return;
}
break;
case 0xd:
switch (op2) {
case 0: /* l.extws */
LOG_DIS("l.extws r%d, r%d\n", rd, ra);
tcg_gen_ext32s_tl(cpu_R[rd], cpu_R[ra]);
return;
case 1: /* l.extwz */
LOG_DIS("l.extwz r%d, r%d\n", rd, ra);
tcg_gen_ext32u_tl(cpu_R[rd], cpu_R[ra]);
return;
}
break;
case 0xe: /* l.cmov */
LOG_DIS("l.cmov r%d, r%d, r%d\n", rd, ra, rb);
{
TCGv zero = tcg_const_tl(0);
tcg_gen_movcond_tl(TCG_COND_NE, cpu_R[rd], cpu_sr_f, zero,
cpu_R[ra], cpu_R[rb]);
tcg_temp_free(zero);
}
return;
case 0xf: /* l.ff1 */
LOG_DIS("l.ff1 r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_ctzi_tl(cpu_R[rd], cpu_R[ra], -1);
tcg_gen_addi_tl(cpu_R[rd], cpu_R[rd], 1);
return;
}
break;
case 1:
switch (op0) {
case 0xf: /* l.fl1 */
LOG_DIS("l.fl1 r%d, r%d, r%d\n", rd, ra, rb);
tcg_gen_clzi_tl(cpu_R[rd], cpu_R[ra], TARGET_LONG_BITS);
tcg_gen_subfi_tl(cpu_R[rd], TARGET_LONG_BITS, cpu_R[rd]);
return;
}
break;
case 2:
break;
case 3:
switch (op0) {
case 0x6: /* l.mul */
LOG_DIS("l.mul r%d, r%d, r%d\n", rd, ra, rb);
gen_mul(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0x7: /* l.muld */
LOG_DIS("l.muld r%d, r%d\n", ra, rb);
gen_muld(dc, cpu_R[ra], cpu_R[rb]);
break;
case 0x9: /* l.div */
LOG_DIS("l.div r%d, r%d, r%d\n", rd, ra, rb);
gen_div(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0xa: /* l.divu */
LOG_DIS("l.divu r%d, r%d, r%d\n", rd, ra, rb);
gen_divu(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0xb: /* l.mulu */
LOG_DIS("l.mulu r%d, r%d, r%d\n", rd, ra, rb);
gen_mulu(dc, cpu_R[rd], cpu_R[ra], cpu_R[rb]);
return;
case 0xc: /* l.muldu */
LOG_DIS("l.muldu r%d, r%d\n", ra, rb);
gen_muldu(dc, cpu_R[ra], cpu_R[rb]);
return;
}
break;
}
gen_illegal_exception(dc);
}
static void dec_misc(DisasContext *dc, uint32_t insn)
{
uint32_t op0, op1;
uint32_t ra, rb, rd;
uint32_t L6, K5, K16, K5_11;
int32_t I16, I5_11, N26;
TCGMemOp mop;
TCGv t0;
op0 = extract32(insn, 26, 6);
op1 = extract32(insn, 24, 2);
ra = extract32(insn, 16, 5);
rb = extract32(insn, 11, 5);
rd = extract32(insn, 21, 5);
L6 = extract32(insn, 5, 6);
K5 = extract32(insn, 0, 5);
K16 = extract32(insn, 0, 16);
I16 = (int16_t)K16;
N26 = sextract32(insn, 0, 26);
K5_11 = (extract32(insn, 21, 5) << 11) | extract32(insn, 0, 11);
I5_11 = (int16_t)K5_11;
switch (op0) {
case 0x00: /* l.j */
LOG_DIS("l.j %d\n", N26);
gen_jump(dc, N26, 0, op0);
break;
case 0x01: /* l.jal */
LOG_DIS("l.jal %d\n", N26);
gen_jump(dc, N26, 0, op0);
break;
case 0x03: /* l.bnf */
LOG_DIS("l.bnf %d\n", N26);
gen_jump(dc, N26, 0, op0);
break;
case 0x04: /* l.bf */
LOG_DIS("l.bf %d\n", N26);
gen_jump(dc, N26, 0, op0);
break;
case 0x05:
switch (op1) {
case 0x01: /* l.nop */
LOG_DIS("l.nop %d\n", I16);
break;
default:
gen_illegal_exception(dc);
break;
}
break;
case 0x11: /* l.jr */
LOG_DIS("l.jr r%d\n", rb);
gen_jump(dc, 0, rb, op0);
break;
case 0x12: /* l.jalr */
LOG_DIS("l.jalr r%d\n", rb);
gen_jump(dc, 0, rb, op0);
break;
case 0x13: /* l.maci */
LOG_DIS("l.maci r%d, %d\n", ra, I16);
t0 = tcg_const_tl(I16);
gen_mac(dc, cpu_R[ra], t0);
tcg_temp_free(t0);
break;
case 0x09: /* l.rfe */
LOG_DIS("l.rfe\n");
{
#if defined(CONFIG_USER_ONLY)
return;
#else
if (dc->mem_idx == MMU_USER_IDX) {
gen_illegal_exception(dc);
return;
}
gen_helper_rfe(cpu_env);
dc->is_jmp = DISAS_UPDATE;
#endif
}
break;
case 0x1b: /* l.lwa */
LOG_DIS("l.lwa r%d, r%d, %d\n", rd, ra, I16);
check_r0_write(rd);
gen_lwa(dc, cpu_R[rd], cpu_R[ra], I16);
break;
case 0x1c: /* l.cust1 */
LOG_DIS("l.cust1\n");
break;
case 0x1d: /* l.cust2 */
LOG_DIS("l.cust2\n");
break;
case 0x1e: /* l.cust3 */
LOG_DIS("l.cust3\n");
break;
case 0x1f: /* l.cust4 */
LOG_DIS("l.cust4\n");
break;
case 0x3c: /* l.cust5 */
LOG_DIS("l.cust5 r%d, r%d, r%d, %d, %d\n", rd, ra, rb, L6, K5);
break;
case 0x3d: /* l.cust6 */
LOG_DIS("l.cust6\n");
break;
case 0x3e: /* l.cust7 */
LOG_DIS("l.cust7\n");
break;
case 0x3f: /* l.cust8 */
LOG_DIS("l.cust8\n");
break;
/* not used yet, open it when we need or64. */
/*#ifdef TARGET_OPENRISC64
case 0x20: l.ld
LOG_DIS("l.ld r%d, r%d, %d\n", rd, ra, I16);
check_ob64s(dc);
mop = MO_TEQ;
goto do_load;
#endif*/
case 0x21: /* l.lwz */
LOG_DIS("l.lwz r%d, r%d, %d\n", rd, ra, I16);
mop = MO_TEUL;
goto do_load;
case 0x22: /* l.lws */
LOG_DIS("l.lws r%d, r%d, %d\n", rd, ra, I16);
mop = MO_TESL;
goto do_load;
case 0x23: /* l.lbz */
LOG_DIS("l.lbz r%d, r%d, %d\n", rd, ra, I16);
mop = MO_UB;
goto do_load;
case 0x24: /* l.lbs */
LOG_DIS("l.lbs r%d, r%d, %d\n", rd, ra, I16);
mop = MO_SB;
goto do_load;
case 0x25: /* l.lhz */
LOG_DIS("l.lhz r%d, r%d, %d\n", rd, ra, I16);
mop = MO_TEUW;
goto do_load;
case 0x26: /* l.lhs */
LOG_DIS("l.lhs r%d, r%d, %d\n", rd, ra, I16);
mop = MO_TESW;
goto do_load;
do_load:
check_r0_write(rd);
t0 = tcg_temp_new();
tcg_gen_addi_tl(t0, cpu_R[ra], I16);
tcg_gen_qemu_ld_tl(cpu_R[rd], t0, dc->mem_idx, mop);
tcg_temp_free(t0);
break;
case 0x27: /* l.addi */
LOG_DIS("l.addi r%d, r%d, %d\n", rd, ra, I16);
check_r0_write(rd);
t0 = tcg_const_tl(I16);
gen_add(dc, cpu_R[rd], cpu_R[ra], t0);
tcg_temp_free(t0);
break;
case 0x28: /* l.addic */
LOG_DIS("l.addic r%d, r%d, %d\n", rd, ra, I16);
check_r0_write(rd);
t0 = tcg_const_tl(I16);
gen_addc(dc, cpu_R[rd], cpu_R[ra], t0);
tcg_temp_free(t0);
break;
case 0x29: /* l.andi */
LOG_DIS("l.andi r%d, r%d, %d\n", rd, ra, K16);
check_r0_write(rd);
tcg_gen_andi_tl(cpu_R[rd], cpu_R[ra], K16);
break;
case 0x2a: /* l.ori */
LOG_DIS("l.ori r%d, r%d, %d\n", rd, ra, K16);
check_r0_write(rd);
tcg_gen_ori_tl(cpu_R[rd], cpu_R[ra], K16);
break;
case 0x2b: /* l.xori */
LOG_DIS("l.xori r%d, r%d, %d\n", rd, ra, I16);
check_r0_write(rd);
tcg_gen_xori_tl(cpu_R[rd], cpu_R[ra], I16);
break;
case 0x2c: /* l.muli */
LOG_DIS("l.muli r%d, r%d, %d\n", rd, ra, I16);
check_r0_write(rd);
t0 = tcg_const_tl(I16);
gen_mul(dc, cpu_R[rd], cpu_R[ra], t0);
tcg_temp_free(t0);
break;
case 0x2d: /* l.mfspr */
LOG_DIS("l.mfspr r%d, r%d, %d\n", rd, ra, K16);
check_r0_write(rd);
{
#if defined(CONFIG_USER_ONLY)
return;
#else
TCGv_i32 ti = tcg_const_i32(K16);
if (dc->mem_idx == MMU_USER_IDX) {
gen_illegal_exception(dc);
return;
}
gen_helper_mfspr(cpu_R[rd], cpu_env, cpu_R[rd], cpu_R[ra], ti);
tcg_temp_free_i32(ti);
#endif
}
break;
case 0x30: /* l.mtspr */
LOG_DIS("l.mtspr r%d, r%d, %d\n", ra, rb, K5_11);
{
#if defined(CONFIG_USER_ONLY)
return;
#else
TCGv_i32 im = tcg_const_i32(K5_11);
if (dc->mem_idx == MMU_USER_IDX) {
gen_illegal_exception(dc);
return;
}
gen_helper_mtspr(cpu_env, cpu_R[ra], cpu_R[rb], im);
tcg_temp_free_i32(im);
#endif
}
break;
case 0x33: /* l.swa */
LOG_DIS("l.swa r%d, r%d, %d\n", ra, rb, I5_11);
gen_swa(dc, rb, cpu_R[ra], I5_11);
break;
/* not used yet, open it when we need or64. */
/*#ifdef TARGET_OPENRISC64
case 0x34: l.sd
LOG_DIS("l.sd r%d, r%d, %d\n", ra, rb, I5_11);
check_ob64s(dc);
mop = MO_TEQ;
goto do_store;
#endif*/
case 0x35: /* l.sw */
LOG_DIS("l.sw r%d, r%d, %d\n", ra, rb, I5_11);
mop = MO_TEUL;
goto do_store;
case 0x36: /* l.sb */
LOG_DIS("l.sb r%d, r%d, %d\n", ra, rb, I5_11);
mop = MO_UB;
goto do_store;
case 0x37: /* l.sh */
LOG_DIS("l.sh r%d, r%d, %d\n", ra, rb, I5_11);
mop = MO_TEUW;
goto do_store;
do_store:
{
TCGv t0 = tcg_temp_new();
tcg_gen_addi_tl(t0, cpu_R[ra], I5_11);
tcg_gen_qemu_st_tl(cpu_R[rb], t0, dc->mem_idx, mop);
tcg_temp_free(t0);
}
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_mac(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t ra, rb;
op0 = extract32(insn, 0, 4);
ra = extract32(insn, 16, 5);
rb = extract32(insn, 11, 5);
switch (op0) {
case 0x0001: /* l.mac */
LOG_DIS("l.mac r%d, r%d\n", ra, rb);
gen_mac(dc, cpu_R[ra], cpu_R[rb]);
break;
case 0x0002: /* l.msb */
LOG_DIS("l.msb r%d, r%d\n", ra, rb);
gen_msb(dc, cpu_R[ra], cpu_R[rb]);
break;
case 0x0003: /* l.macu */
LOG_DIS("l.macu r%d, r%d\n", ra, rb);
gen_macu(dc, cpu_R[ra], cpu_R[rb]);
break;
case 0x0004: /* l.msbu */
LOG_DIS("l.msbu r%d, r%d\n", ra, rb);
gen_msbu(dc, cpu_R[ra], cpu_R[rb]);
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_logic(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t rd, ra, L6, S6;
op0 = extract32(insn, 6, 2);
rd = extract32(insn, 21, 5);
ra = extract32(insn, 16, 5);
L6 = extract32(insn, 0, 6);
S6 = L6 & (TARGET_LONG_BITS - 1);
check_r0_write(rd);
switch (op0) {
case 0x00: /* l.slli */
LOG_DIS("l.slli r%d, r%d, %d\n", rd, ra, L6);
tcg_gen_shli_tl(cpu_R[rd], cpu_R[ra], S6);
break;
case 0x01: /* l.srli */
LOG_DIS("l.srli r%d, r%d, %d\n", rd, ra, L6);
tcg_gen_shri_tl(cpu_R[rd], cpu_R[ra], S6);
break;
case 0x02: /* l.srai */
LOG_DIS("l.srai r%d, r%d, %d\n", rd, ra, L6);
tcg_gen_sari_tl(cpu_R[rd], cpu_R[ra], S6);
break;
case 0x03: /* l.rori */
LOG_DIS("l.rori r%d, r%d, %d\n", rd, ra, L6);
tcg_gen_rotri_tl(cpu_R[rd], cpu_R[ra], S6);
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_M(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t rd;
uint32_t K16;
op0 = extract32(insn, 16, 1);
rd = extract32(insn, 21, 5);
K16 = extract32(insn, 0, 16);
check_r0_write(rd);
switch (op0) {
case 0x0: /* l.movhi */
LOG_DIS("l.movhi r%d, %d\n", rd, K16);
tcg_gen_movi_tl(cpu_R[rd], (K16 << 16));
break;
case 0x1: /* l.macrc */
LOG_DIS("l.macrc r%d\n", rd);
tcg_gen_trunc_i64_tl(cpu_R[rd], cpu_mac);
tcg_gen_movi_i64(cpu_mac, 0);
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_comp(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t ra, rb;
op0 = extract32(insn, 21, 5);
ra = extract32(insn, 16, 5);
rb = extract32(insn, 11, 5);
/* unsigned integers */
tcg_gen_ext32u_tl(cpu_R[ra], cpu_R[ra]);
tcg_gen_ext32u_tl(cpu_R[rb], cpu_R[rb]);
switch (op0) {
case 0x0: /* l.sfeq */
LOG_DIS("l.sfeq r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_EQ, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0x1: /* l.sfne */
LOG_DIS("l.sfne r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_NE, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0x2: /* l.sfgtu */
LOG_DIS("l.sfgtu r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_GTU, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0x3: /* l.sfgeu */
LOG_DIS("l.sfgeu r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_GEU, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0x4: /* l.sfltu */
LOG_DIS("l.sfltu r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_LTU, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0x5: /* l.sfleu */
LOG_DIS("l.sfleu r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_LEU, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0xa: /* l.sfgts */
LOG_DIS("l.sfgts r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_GT, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0xb: /* l.sfges */
LOG_DIS("l.sfges r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_GE, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0xc: /* l.sflts */
LOG_DIS("l.sflts r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_LT, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
case 0xd: /* l.sfles */
LOG_DIS("l.sfles r%d, r%d\n", ra, rb);
tcg_gen_setcond_tl(TCG_COND_LE, cpu_sr_f, cpu_R[ra], cpu_R[rb]);
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_compi(DisasContext *dc, uint32_t insn)
{
uint32_t op0, ra;
int32_t I16;
op0 = extract32(insn, 21, 5);
ra = extract32(insn, 16, 5);
I16 = sextract32(insn, 0, 16);
switch (op0) {
case 0x0: /* l.sfeqi */
LOG_DIS("l.sfeqi r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_sr_f, cpu_R[ra], I16);
break;
case 0x1: /* l.sfnei */
LOG_DIS("l.sfnei r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_NE, cpu_sr_f, cpu_R[ra], I16);
break;
case 0x2: /* l.sfgtui */
LOG_DIS("l.sfgtui r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_GTU, cpu_sr_f, cpu_R[ra], I16);
break;
case 0x3: /* l.sfgeui */
LOG_DIS("l.sfgeui r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_GEU, cpu_sr_f, cpu_R[ra], I16);
break;
case 0x4: /* l.sfltui */
LOG_DIS("l.sfltui r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_LTU, cpu_sr_f, cpu_R[ra], I16);
break;
case 0x5: /* l.sfleui */
LOG_DIS("l.sfleui r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_LEU, cpu_sr_f, cpu_R[ra], I16);
break;
case 0xa: /* l.sfgtsi */
LOG_DIS("l.sfgtsi r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_GT, cpu_sr_f, cpu_R[ra], I16);
break;
case 0xb: /* l.sfgesi */
LOG_DIS("l.sfgesi r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_GE, cpu_sr_f, cpu_R[ra], I16);
break;
case 0xc: /* l.sfltsi */
LOG_DIS("l.sfltsi r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_LT, cpu_sr_f, cpu_R[ra], I16);
break;
case 0xd: /* l.sflesi */
LOG_DIS("l.sflesi r%d, %d\n", ra, I16);
tcg_gen_setcondi_tl(TCG_COND_LE, cpu_sr_f, cpu_R[ra], I16);
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_sys(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t K16;
op0 = extract32(insn, 16, 10);
K16 = extract32(insn, 0, 16);
switch (op0) {
case 0x000: /* l.sys */
LOG_DIS("l.sys %d\n", K16);
tcg_gen_movi_tl(cpu_pc, dc->pc);
gen_exception(dc, EXCP_SYSCALL);
dc->is_jmp = DISAS_UPDATE;
break;
case 0x100: /* l.trap */
LOG_DIS("l.trap %d\n", K16);
tcg_gen_movi_tl(cpu_pc, dc->pc);
gen_exception(dc, EXCP_TRAP);
break;
case 0x300: /* l.csync */
LOG_DIS("l.csync\n");
break;
case 0x200: /* l.msync */
LOG_DIS("l.msync\n");
tcg_gen_mb(TCG_MO_ALL);
break;
case 0x270: /* l.psync */
LOG_DIS("l.psync\n");
break;
default:
gen_illegal_exception(dc);
break;
}
}
static void dec_float(DisasContext *dc, uint32_t insn)
{
uint32_t op0;
uint32_t ra, rb, rd;
op0 = extract32(insn, 0, 8);
ra = extract32(insn, 16, 5);
rb = extract32(insn, 11, 5);
rd = extract32(insn, 21, 5);
switch (op0) {
case 0x00: /* lf.add.s */
LOG_DIS("lf.add.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_add_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x01: /* lf.sub.s */
LOG_DIS("lf.sub.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_sub_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x02: /* lf.mul.s */
LOG_DIS("lf.mul.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_mul_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x03: /* lf.div.s */
LOG_DIS("lf.div.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_div_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x04: /* lf.itof.s */
LOG_DIS("lf.itof r%d, r%d\n", rd, ra);
check_r0_write(rd);
gen_helper_itofs(cpu_R[rd], cpu_env, cpu_R[ra]);
break;
case 0x05: /* lf.ftoi.s */
LOG_DIS("lf.ftoi r%d, r%d\n", rd, ra);
check_r0_write(rd);
gen_helper_ftois(cpu_R[rd], cpu_env, cpu_R[ra]);
break;
case 0x06: /* lf.rem.s */
LOG_DIS("lf.rem.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_rem_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x07: /* lf.madd.s */
LOG_DIS("lf.madd.s r%d, r%d, r%d\n", rd, ra, rb);
check_r0_write(rd);
gen_helper_float_madd_s(cpu_R[rd], cpu_env, cpu_R[rd],
cpu_R[ra], cpu_R[rb]);
break;
case 0x08: /* lf.sfeq.s */
LOG_DIS("lf.sfeq.s r%d, r%d\n", ra, rb);
gen_helper_float_eq_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x09: /* lf.sfne.s */
LOG_DIS("lf.sfne.s r%d, r%d\n", ra, rb);
gen_helper_float_ne_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x0a: /* lf.sfgt.s */
LOG_DIS("lf.sfgt.s r%d, r%d\n", ra, rb);
gen_helper_float_gt_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x0b: /* lf.sfge.s */
LOG_DIS("lf.sfge.s r%d, r%d\n", ra, rb);
gen_helper_float_ge_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x0c: /* lf.sflt.s */
LOG_DIS("lf.sflt.s r%d, r%d\n", ra, rb);
gen_helper_float_lt_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x0d: /* lf.sfle.s */
LOG_DIS("lf.sfle.s r%d, r%d\n", ra, rb);
gen_helper_float_le_s(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
/* not used yet, open it when we need or64. */
/*#ifdef TARGET_OPENRISC64
case 0x10: lf.add.d
LOG_DIS("lf.add.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_add_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x11: lf.sub.d
LOG_DIS("lf.sub.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_sub_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x12: lf.mul.d
LOG_DIS("lf.mul.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_mul_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x13: lf.div.d
LOG_DIS("lf.div.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_div_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x14: lf.itof.d
LOG_DIS("lf.itof r%d, r%d\n", rd, ra);
check_of64s(dc);
check_r0_write(rd);
gen_helper_itofd(cpu_R[rd], cpu_env, cpu_R[ra]);
break;
case 0x15: lf.ftoi.d
LOG_DIS("lf.ftoi r%d, r%d\n", rd, ra);
check_of64s(dc);
check_r0_write(rd);
gen_helper_ftoid(cpu_R[rd], cpu_env, cpu_R[ra]);
break;
case 0x16: lf.rem.d
LOG_DIS("lf.rem.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_rem_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x17: lf.madd.d
LOG_DIS("lf.madd.d r%d, r%d, r%d\n", rd, ra, rb);
check_of64s(dc);
check_r0_write(rd);
gen_helper_float_madd_d(cpu_R[rd], cpu_env, cpu_R[rd],
cpu_R[ra], cpu_R[rb]);
break;
case 0x18: lf.sfeq.d
LOG_DIS("lf.sfeq.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_eq_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x1a: lf.sfgt.d
LOG_DIS("lf.sfgt.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_gt_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x1b: lf.sfge.d
LOG_DIS("lf.sfge.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_ge_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x19: lf.sfne.d
LOG_DIS("lf.sfne.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_ne_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x1c: lf.sflt.d
LOG_DIS("lf.sflt.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_lt_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
case 0x1d: lf.sfle.d
LOG_DIS("lf.sfle.d r%d, r%d\n", ra, rb);
check_of64s(dc);
gen_helper_float_le_d(cpu_sr_f, cpu_env, cpu_R[ra], cpu_R[rb]);
break;
#endif*/
default:
gen_illegal_exception(dc);
break;
}
}
static void disas_openrisc_insn(DisasContext *dc, OpenRISCCPU *cpu)
{
uint32_t op0;
uint32_t insn;
insn = cpu_ldl_code(&cpu->env, dc->pc);
op0 = extract32(insn, 26, 6);
switch (op0) {
case 0x06:
dec_M(dc, insn);
break;
case 0x08:
dec_sys(dc, insn);
break;
case 0x2e:
dec_logic(dc, insn);
break;
case 0x2f:
dec_compi(dc, insn);
break;
case 0x31:
dec_mac(dc, insn);
break;
case 0x32:
dec_float(dc, insn);
break;
case 0x38:
dec_calc(dc, insn);
break;
case 0x39:
dec_comp(dc, insn);
break;
default:
dec_misc(dc, insn);
break;
}
}
void gen_intermediate_code(CPUState *cs, struct TranslationBlock *tb)
{
CPUOpenRISCState *env = cs->env_ptr;
OpenRISCCPU *cpu = openrisc_env_get_cpu(env);
struct DisasContext ctx, *dc = &ctx;
uint32_t pc_start;
uint32_t next_page_start;
int num_insns;
int max_insns;
pc_start = tb->pc;
dc->tb = tb;
dc->is_jmp = DISAS_NEXT;
dc->pc = pc_start;
dc->mem_idx = cpu_mmu_index(&cpu->env, false);
dc->tb_flags = tb->flags;
dc->delayed_branch = (dc->tb_flags & TB_FLAGS_DFLAG) != 0;
dc->singlestep_enabled = cs->singlestep_enabled;
next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
num_insns = 0;
max_insns = tb->cflags & CF_COUNT_MASK;
if (max_insns == 0) {
max_insns = CF_COUNT_MASK;
}
if (max_insns > TCG_MAX_INSNS) {
max_insns = TCG_MAX_INSNS;
}
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
&& qemu_log_in_addr_range(pc_start)) {
qemu_log_lock();
qemu_log("----------------\n");
qemu_log("IN: %s\n", lookup_symbol(pc_start));
}
gen_tb_start(tb);
/* Allow the TCG optimizer to see that R0 == 0,
when it's true, which is the common case. */
if (dc->tb_flags & TB_FLAGS_R0_0) {
cpu_R[0] = tcg_const_tl(0);
} else {
cpu_R[0] = cpu_R0;
}
do {
tcg_gen_insn_start(dc->pc, (dc->delayed_branch ? 1 : 0)
| (num_insns ? 2 : 0));
num_insns++;
if (unlikely(cpu_breakpoint_test(cs, dc->pc, BP_ANY))) {
tcg_gen_movi_tl(cpu_pc, dc->pc);
gen_exception(dc, EXCP_DEBUG);
dc->is_jmp = DISAS_UPDATE;
/* The address covered by the breakpoint must be included in
[tb->pc, tb->pc + tb->size) in order to for it to be
properly cleared -- thus we increment the PC here so that
the logic setting tb->size below does the right thing. */
dc->pc += 4;
break;
}
if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {
gen_io_start();
}
disas_openrisc_insn(dc, cpu);
dc->pc = dc->pc + 4;
/* delay slot */
if (dc->delayed_branch) {
dc->delayed_branch--;
if (!dc->delayed_branch) {
tcg_gen_mov_tl(cpu_pc, jmp_pc);
tcg_gen_discard_tl(jmp_pc);
dc->is_jmp = DISAS_UPDATE;
break;
}
}
} while (!dc->is_jmp
&& !tcg_op_buf_full()
&& !cs->singlestep_enabled
&& !singlestep
&& (dc->pc < next_page_start)
&& num_insns < max_insns);
if (tb->cflags & CF_LAST_IO) {
gen_io_end();
}
if ((dc->tb_flags & TB_FLAGS_DFLAG ? 1 : 0) != (dc->delayed_branch != 0)) {
tcg_gen_movi_i32(cpu_dflag, dc->delayed_branch != 0);
}
tcg_gen_movi_tl(cpu_ppc, dc->pc - 4);
if (dc->is_jmp == DISAS_NEXT) {
dc->is_jmp = DISAS_UPDATE;
tcg_gen_movi_tl(cpu_pc, dc->pc);
}
if (unlikely(cs->singlestep_enabled)) {
gen_exception(dc, EXCP_DEBUG);
} else {
switch (dc->is_jmp) {
case DISAS_NEXT:
gen_goto_tb(dc, 0, dc->pc);
break;
default:
case DISAS_JUMP:
break;
case DISAS_UPDATE:
/* indicate that the hash table must be used
to find the next TB */
tcg_gen_exit_tb(0);
break;
case DISAS_TB_JUMP:
/* nothing more to generate */
break;
}
}
gen_tb_end(tb, num_insns);
tb->size = dc->pc - pc_start;
tb->icount = num_insns;
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
&& qemu_log_in_addr_range(pc_start)) {
log_target_disas(cs, pc_start, tb->size, 0);
qemu_log("\n");
qemu_log_unlock();
}
}
void openrisc_cpu_dump_state(CPUState *cs, FILE *f,
fprintf_function cpu_fprintf,
int flags)
{
OpenRISCCPU *cpu = OPENRISC_CPU(cs);
CPUOpenRISCState *env = &cpu->env;
int i;
cpu_fprintf(f, "PC=%08x\n", env->pc);
for (i = 0; i < 32; ++i) {
cpu_fprintf(f, "R%02d=%08x%c", i, cpu_get_gpr(env, i),
(i % 4) == 3 ? '\n' : ' ');
}
}
void restore_state_to_opc(CPUOpenRISCState *env, TranslationBlock *tb,
target_ulong *data)
{
env->pc = data[0];
env->dflag = data[1] & 1;
if (data[1] & 2) {
env->ppc = env->pc - 4;
}
}
|
538089.c | /*
* Copyright (c) 2012-2020 MIRACL UK Ltd.
*
* This file is part of MIRACL Core
* (see https://github.com/miracl/core).
*
* 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 "arch.h"
#include "fp_SECP160R1.h"
/* Curve SECP160R1 */
#if CHUNK==16
// Base Bits= 13
const BIG_160_13 Modulus_SECP160R1= {0x1FFF,0x1FFF,0x1FDF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0xF};
const BIG_160_13 R2modp_SECP160R1= {0x0,0x20,0x0,0x800,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0};
const BIG_160_13 ROI_SECP160R1= {0x1FFE,0x1FFF,0x1FDF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0x1FFF,0xF};
const chunk MConst_SECP160R1= 0x1;
#endif
#if CHUNK==32
// Base Bits= 29
const BIG_160_29 Modulus_SECP160R1= {0x1FFFFFFF,0x1FFFFFFB,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFF};
const BIG_160_29 R2modp_SECP160R1= {0x10000000,0x0,0x4,0x8,0x0,0x0};
const BIG_160_29 ROI_SECP160R1= {0x1FFFFFFE,0x1FFFFFFB,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFF};
const chunk MConst_SECP160R1= 0x1;
#endif
#if CHUNK==64
// Base Bits= 56
const BIG_160_56 Modulus_SECP160R1= {0xFFFFFF7FFFFFFFL,0xFFFFFFFFFFFFFFL,0xFFFFFFFFFFFFL};
const BIG_160_56 R2modp_SECP160R1= {0x1000000010000L,0x400000L,0x0L};
const BIG_160_56 ROI_SECP160R1= {0xFFFFFF7FFFFFFEL,0xFFFFFFFFFFFFFFL,0xFFFFFFFFFFFFL};
const chunk MConst_SECP160R1= 0xFFFFFF80000001L;
#endif
|
237782.c | #include <semaphore.h>
#include <mem.h>
#include <process.h>
void destroySemaphore(Semaphore *semaphore);
//Creates a semaphore
Semaphore *startSemaphore(unsigned int value){
Semaphore *semaphore = malloc(sizeof(Semaphore));
semaphore->value = value;
semaphore->firstPID = 0;
semaphore->lastPID = 0;
return semaphore;
}
//Sends a semaphore to its death. Cannot be used after this.
void stopSemaphore(Semaphore *semaphore){
semaphore->dead = 1;
if(semaphore->firstPID == 0)
destroySemaphore(semaphore);
}
//Destroys a semaphore
void destroySemaphore(Semaphore *semaphore){
// freePIDQueue(semaphore); //TODO: FREE PIDQUEUE
// free(semaphore); //TODO: FREE SEMAPHORE
}
//Sleep until semaphore lets me (Could be immediate).
//If semaphore is dead returns 0.
int waitSemaphore(Semaphore *semaphore){
while(1){
if(semaphore->dead == 1)
return 0;
if(semaphore->value > 0){
semaphore->value--;
return 1;
}
pNode * node = malloc(sizeof(pNode));
process * p = getCurrent();
node->pid = p->pid;
node->next = 0;
if(semaphore->firstPID == 0){
semaphore->firstPID = node;
semaphore->lastPID = node;
}
else{
semaphore->lastPID->next = node;
semaphore->lastPID = node;
}
sleepProcess(node->pid);
}
return 0;
}
//Wakes up next task or semaphoreValue++;
void signalSemaphore(Semaphore *semaphore){
if ( semaphore->firstPID == 0 ){
if(semaphore->dead == 1)
destroySemaphore(semaphore);
else
semaphore->value++;
return;
}
//pNode *node = semaphore->firstPID;
// free(node); //TODO: FREE NODE
semaphore->firstPID = semaphore->firstPID->next;
if(semaphore->firstPID != 0)
wakePrecess(semaphore->firstPID);
} |
799415.c | /*!
* \file main.c
*
* \brief LoRaMac classB device implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*
* \author Andreas Pella (IMST GmbH)
*/
/*! \file classB/SKiM881AXL/main.c */
#include <stdio.h>
#include "utilities.h"
#include "board.h"
#include "gpio.h"
#include "LoRaMac.h"
#include "Commissioning.h"
#include "NvmCtxMgmt.h"
#ifndef ACTIVE_REGION
#warning "No active region defined, LORAMAC_REGION_EU868 will be used as default."
#define ACTIVE_REGION LORAMAC_REGION_EU868
#endif
/*!
* Uncomment to use the deprecated BeaconTiming MAC command
*/
//#define USE_BEACON_TIMING
/*!
* Defines the application data transmission duty cycle. 30s, value in [ms].
*/
#define APP_TX_DUTYCYCLE 30000
/*!
* Defines a random delay for application data transmission duty cycle. 5s,
* value in [ms].
*/
#define APP_TX_DUTYCYCLE_RND 5000
/*!
* Default datarate
*/
#define LORAWAN_DEFAULT_DATARATE DR_0
/*!
* Default ping slots periodicity
*
* \remark periodicity is equal to 2^LORAWAN_DEFAULT_PING_SLOT_PERIODICITY seconds
* example: 2^3 = 8 seconds. The end-device will open an Rx slot every 8 seconds.
*/
#define LORAWAN_DEFAULT_PING_SLOT_PERIODICITY 0
/*!
* LoRaWAN confirmed messages
*/
#define LORAWAN_CONFIRMED_MSG_ON false
/*!
* LoRaWAN Adaptive Data Rate
*
* \remark Please note that when ADR is enabled the end-device should be static
*/
#define LORAWAN_ADR_ON 1
#if defined( REGION_EU868 ) || defined( REGION_RU864 ) || defined( REGION_CN779 ) || defined( REGION_EU433 )
#include "LoRaMacTest.h"
/*!
* LoRaWAN ETSI duty cycle control enable/disable
*
* \remark Please note that ETSI mandates duty cycled transmissions. Use only for test purposes
*/
#define LORAWAN_DUTYCYCLE_ON true
#endif
/*!
* LoRaWAN application port
*/
#define LORAWAN_APP_PORT 3
#if( ABP_ACTIVATION_LRWAN_VERSION == ABP_ACTIVATION_LRWAN_VERSION_V10x )
static uint8_t GenAppKey[] = LORAWAN_GEN_APP_KEY;
#else
static uint8_t AppKey[] = LORAWAN_APP_KEY;
#endif
static uint8_t NwkKey[] = LORAWAN_NWK_KEY;
#if( OVER_THE_AIR_ACTIVATION == 0 )
static uint8_t FNwkSIntKey[] = LORAWAN_F_NWK_S_INT_KEY;
static uint8_t SNwkSIntKey[] = LORAWAN_S_NWK_S_INT_KEY;
static uint8_t NwkSEncKey[] = LORAWAN_NWK_S_ENC_KEY;
static uint8_t AppSKey[] = LORAWAN_APP_S_KEY;
/*!
* Device address
*/
static uint32_t DevAddr = LORAWAN_DEVICE_ADDRESS;
#endif
/*!
* Application port
*/
static uint8_t AppPort = LORAWAN_APP_PORT;
/*!
* User application data size
*/
static uint8_t AppDataSize = 4;
static uint8_t AppDataSizeBackup = 4;
/*!
* User application data buffer size
*/
#define LORAWAN_APP_DATA_MAX_SIZE 242
/*!
* User application data
*/
static uint8_t AppDataBuffer[LORAWAN_APP_DATA_MAX_SIZE];
/*!
* Indicates if the node is sending confirmed or unconfirmed messages
*/
static uint8_t IsTxConfirmed = LORAWAN_CONFIRMED_MSG_ON;
/*!
* Defines the application data transmission duty cycle
*/
static uint32_t TxDutyCycleTime;
/*!
* Timer to handle the application data transmission duty cycle
*/
static TimerEvent_t TxNextPacketTimer;
/*!
* Specifies the state of the application LED
*/
static bool AppLedStateOn = false;
/*!
* Timer to handle the state of LED4
*/
static TimerEvent_t Led4Timer;
/*!
* Timer to handle the state of LED2
*/
static TimerEvent_t Led2Timer;
/*!
* Timer to handle the state of LED beacon indicator
*/
static TimerEvent_t LedBeaconTimer;
/*!
* Indicates if a new packet can be sent
*/
static bool NextTx = true;
/*!
* Indicates if LoRaMacProcess call is pending.
*
* \warning If variable is equal to 0 then the MCU can be set in low power mode
*/
static uint8_t IsMacProcessPending = 0;
/*!
* Device states
*/
static enum eDeviceState
{
DEVICE_STATE_RESTORE,
DEVICE_STATE_START,
DEVICE_STATE_JOIN,
DEVICE_STATE_SEND,
DEVICE_STATE_REQ_DEVICE_TIME,
DEVICE_STATE_REQ_PINGSLOT_ACK,
DEVICE_STATE_REQ_BEACON_TIMING,
DEVICE_STATE_BEACON_ACQUISITION,
DEVICE_STATE_SWITCH_CLASS,
DEVICE_STATE_CYCLE,
DEVICE_STATE_SLEEP
}DeviceState, WakeUpState;
/*!
* LoRaWAN compliance tests support data
*/
struct ComplianceTest_s
{
bool Running;
uint8_t State;
bool IsTxConfirmed;
uint8_t AppPort;
uint8_t AppDataSize;
uint8_t *AppDataBuffer;
uint16_t DownLinkCounter;
bool LinkCheck;
uint8_t DemodMargin;
uint8_t NbGateways;
}ComplianceTest;
/*!
*
*/
typedef enum
{
LORAMAC_HANDLER_UNCONFIRMED_MSG = 0,
LORAMAC_HANDLER_CONFIRMED_MSG = !LORAMAC_HANDLER_UNCONFIRMED_MSG
}LoRaMacHandlerMsgTypes_t;
/*!
* Application data structure
*/
typedef struct LoRaMacHandlerAppData_s
{
LoRaMacHandlerMsgTypes_t MsgType;
uint8_t Port;
uint8_t BufferSize;
uint8_t *Buffer;
}LoRaMacHandlerAppData_t;
LoRaMacHandlerAppData_t AppData =
{
.MsgType = LORAMAC_HANDLER_UNCONFIRMED_MSG,
.Buffer = NULL,
.BufferSize = 0,
.Port = 0
};
/*!
* LED GPIO pins objects
*/
extern Gpio_t Led4; // Tx
extern Gpio_t Led2; // Rx and blinks every 5 seconds when beacon is acquired
extern Gpio_t Led3; // App
/*!
* MAC status strings
*/
const char* MacStatusStrings[] =
{
"OK", // LORAMAC_STATUS_OK
"Busy", // LORAMAC_STATUS_BUSY
"Service unknown", // LORAMAC_STATUS_SERVICE_UNKNOWN
"Parameter invalid", // LORAMAC_STATUS_PARAMETER_INVALID
"Frequency invalid", // LORAMAC_STATUS_FREQUENCY_INVALID
"Datarate invalid", // LORAMAC_STATUS_DATARATE_INVALID
"Frequency or datarate invalid", // LORAMAC_STATUS_FREQ_AND_DR_INVALID
"No network joined", // LORAMAC_STATUS_NO_NETWORK_JOINED
"Length error", // LORAMAC_STATUS_LENGTH_ERROR
"Region not supported", // LORAMAC_STATUS_REGION_NOT_SUPPORTED
"Skipped APP data", // LORAMAC_STATUS_SKIPPED_APP_DATA
"Duty-cycle restricted", // LORAMAC_STATUS_DUTYCYCLE_RESTRICTED
"No channel found", // LORAMAC_STATUS_NO_CHANNEL_FOUND
"No free channel found", // LORAMAC_STATUS_NO_FREE_CHANNEL_FOUND
"Busy beacon reserved time", // LORAMAC_STATUS_BUSY_BEACON_RESERVED_TIME
"Busy ping-slot window time", // LORAMAC_STATUS_BUSY_PING_SLOT_WINDOW_TIME
"Busy uplink collision", // LORAMAC_STATUS_BUSY_UPLINK_COLLISION
"Crypto error", // LORAMAC_STATUS_CRYPTO_ERROR
"FCnt handler error", // LORAMAC_STATUS_FCNT_HANDLER_ERROR
"MAC command error", // LORAMAC_STATUS_MAC_COMMAD_ERROR
"ClassB error", // LORAMAC_STATUS_CLASS_B_ERROR
"Confirm queue error", // LORAMAC_STATUS_CONFIRM_QUEUE_ERROR
"Multicast group undefined", // LORAMAC_STATUS_MC_GROUP_UNDEFINED
"Unknown error", // LORAMAC_STATUS_ERROR
};
/*!
* MAC event info status strings.
*/
const char* EventInfoStatusStrings[] =
{
"OK", // LORAMAC_EVENT_INFO_STATUS_OK
"Error", // LORAMAC_EVENT_INFO_STATUS_ERROR
"Tx timeout", // LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT
"Rx 1 timeout", // LORAMAC_EVENT_INFO_STATUS_RX1_TIMEOUT
"Rx 2 timeout", // LORAMAC_EVENT_INFO_STATUS_RX2_TIMEOUT
"Rx1 error", // LORAMAC_EVENT_INFO_STATUS_RX1_ERROR
"Rx2 error", // LORAMAC_EVENT_INFO_STATUS_RX2_ERROR
"Join failed", // LORAMAC_EVENT_INFO_STATUS_JOIN_FAIL
"Downlink repeated", // LORAMAC_EVENT_INFO_STATUS_DOWNLINK_REPEATED
"Tx DR payload size error", // LORAMAC_EVENT_INFO_STATUS_TX_DR_PAYLOAD_SIZE_ERROR
"Downlink too many frames loss", // LORAMAC_EVENT_INFO_STATUS_DOWNLINK_TOO_MANY_FRAMES_LOSS
"Address fail", // LORAMAC_EVENT_INFO_STATUS_ADDRESS_FAIL
"MIC fail", // LORAMAC_EVENT_INFO_STATUS_MIC_FAIL
"Multicast fail", // LORAMAC_EVENT_INFO_STATUS_MULTICAST_FAIL
"Beacon locked", // LORAMAC_EVENT_INFO_STATUS_BEACON_LOCKED
"Beacon lost", // LORAMAC_EVENT_INFO_STATUS_BEACON_LOST
"Beacon not found" // LORAMAC_EVENT_INFO_STATUS_BEACON_NOT_FOUND
};
/*!
* Prints the provided buffer in HEX
*
* \param buffer Buffer to be printed
* \param size Buffer size to be printed
*/
void PrintHexBuffer( uint8_t *buffer, uint8_t size )
{
uint8_t newline = 0;
for( uint8_t i = 0; i < size; i++ )
{
if( newline != 0 )
{
printf( "\r\n" );
newline = 0;
}
printf( "%02X ", buffer[i] );
if( ( ( i + 1 ) % 16 ) == 0 )
{
newline = 1;
}
}
printf( "\r\n" );
}
/*!
* Executes the network Join request
*/
static void JoinNetwork( void )
{
LoRaMacStatus_t status;
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_JOIN;
mlmeReq.Req.Join.Datarate = LORAWAN_DEFAULT_DATARATE;
// Starts the join procedure
status = LoRaMacMlmeRequest( &mlmeReq );
printf( "\r\n###### ===== MLME-Request - MLME_JOIN ==== ######\r\n" );
printf( "STATUS : %s\r\n", MacStatusStrings[status] );
if( status == LORAMAC_STATUS_OK )
{
printf( "###### ===== JOINING ==== ######\r\n" );
DeviceState = DEVICE_STATE_SLEEP;
}
else
{
DeviceState = DEVICE_STATE_CYCLE;
}
}
/*!
* \brief Prepares the payload of the frame
*/
static void PrepareTxFrame( uint8_t port )
{
switch( port )
{
case 3:
{
uint8_t potiPercentage = 0;
uint16_t vdd = 0;
// Read the current potentiometer setting in percent
potiPercentage = BoardGetPotiLevel( );
// Read the current voltage level
BoardGetBatteryLevel( ); // Updates the value returned by BoardGetBatteryVoltage( ) function.
vdd = BoardGetBatteryVoltage( );
AppDataSizeBackup = AppDataSize = 4;
AppDataBuffer[0] = AppLedStateOn;
AppDataBuffer[1] = potiPercentage;
AppDataBuffer[2] = ( vdd >> 8 ) & 0xFF;
AppDataBuffer[3] = vdd & 0xFF;
}
break;
case 224:
if( ComplianceTest.LinkCheck == true )
{
ComplianceTest.LinkCheck = false;
AppDataSize = 3;
AppDataBuffer[0] = 5;
AppDataBuffer[1] = ComplianceTest.DemodMargin;
AppDataBuffer[2] = ComplianceTest.NbGateways;
ComplianceTest.State = 1;
}
else
{
switch( ComplianceTest.State )
{
case 4:
ComplianceTest.State = 1;
break;
case 1:
AppDataSize = 2;
AppDataBuffer[0] = ComplianceTest.DownLinkCounter >> 8;
AppDataBuffer[1] = ComplianceTest.DownLinkCounter;
break;
}
}
break;
default:
break;
}
}
/*!
* \brief Prepares the payload of the frame
*
* \retval [0: frame could be send, 1: error]
*/
static bool SendFrame( void )
{
McpsReq_t mcpsReq;
LoRaMacTxInfo_t txInfo;
if( LoRaMacQueryTxPossible( AppDataSize, &txInfo ) != LORAMAC_STATUS_OK )
{
// Send empty frame in order to flush MAC commands
mcpsReq.Type = MCPS_UNCONFIRMED;
mcpsReq.Req.Unconfirmed.fBuffer = NULL;
mcpsReq.Req.Unconfirmed.fBufferSize = 0;
mcpsReq.Req.Unconfirmed.Datarate = LORAWAN_DEFAULT_DATARATE;
}
else
{
if( IsTxConfirmed == false )
{
mcpsReq.Type = MCPS_UNCONFIRMED;
mcpsReq.Req.Unconfirmed.fPort = AppPort;
mcpsReq.Req.Unconfirmed.fBuffer = AppDataBuffer;
mcpsReq.Req.Unconfirmed.fBufferSize = AppDataSize;
mcpsReq.Req.Unconfirmed.Datarate = LORAWAN_DEFAULT_DATARATE;
}
else
{
mcpsReq.Type = MCPS_CONFIRMED;
mcpsReq.Req.Confirmed.fPort = AppPort;
mcpsReq.Req.Confirmed.fBuffer = AppDataBuffer;
mcpsReq.Req.Confirmed.fBufferSize = AppDataSize;
mcpsReq.Req.Confirmed.NbTrials = 8;
mcpsReq.Req.Confirmed.Datarate = LORAWAN_DEFAULT_DATARATE;
}
}
// Update global variable
AppData.MsgType = ( mcpsReq.Type == MCPS_CONFIRMED ) ? LORAMAC_HANDLER_CONFIRMED_MSG : LORAMAC_HANDLER_UNCONFIRMED_MSG;
AppData.Port = mcpsReq.Req.Unconfirmed.fPort;
AppData.Buffer = mcpsReq.Req.Unconfirmed.fBuffer;
AppData.BufferSize = mcpsReq.Req.Unconfirmed.fBufferSize;
LoRaMacStatus_t status;
status = LoRaMacMcpsRequest( &mcpsReq );
printf( "\r\n###### ===== MCPS-Request ==== ######\r\n" );
printf( "STATUS : %s\r\n", MacStatusStrings[status] );
if( status == LORAMAC_STATUS_OK )
{
return false;
}
return true;
}
/*!
* \brief Function executed on TxNextPacket Timeout event
*/
static void OnTxNextPacketTimerEvent( void* context )
{
MibRequestConfirm_t mibReq;
LoRaMacStatus_t status;
TimerStop( &TxNextPacketTimer );
mibReq.Type = MIB_NETWORK_ACTIVATION;
status = LoRaMacMibGetRequestConfirm( &mibReq );
if( status == LORAMAC_STATUS_OK )
{
if( mibReq.Param.NetworkActivation == ACTIVATION_TYPE_NONE )
{
// Network not joined yet. Try to join again
JoinNetwork( );
}
else
{
DeviceState = WakeUpState;
NextTx = true;
}
}
}
/*!
* \brief Function executed on Led 4 Timeout event
*/
static void OnLed4TimerEvent( void* context )
{
TimerStop( &Led4Timer );
// Switch LED 4 OFF
GpioWrite( &Led4, 0 );
}
/*!
* \brief Function executed on Led 2 Timeout event
*/
static void OnLed2TimerEvent( void* context )
{
TimerStop( &Led2Timer );
// Switch LED 2 OFF
GpioWrite( &Led2, 0 );
}
/*!
* \brief Function executed on Beacon timer Timeout event
*/
static void OnLedBeaconTimerEvent( void* context )
{
GpioWrite( &Led2, 1 );
TimerStart( &Led2Timer );
TimerStart( &LedBeaconTimer );
}
/*!
* \brief MCPS-Confirm event function
*
* \param [IN] mcpsConfirm - Pointer to the confirm structure,
* containing confirm attributes.
*/
static void McpsConfirm( McpsConfirm_t *mcpsConfirm )
{
printf( "\r\n###### ===== MCPS-Confirm ==== ######\r\n" );
printf( "STATUS : %s\r\n", EventInfoStatusStrings[mcpsConfirm->Status] );
if( mcpsConfirm->Status != LORAMAC_EVENT_INFO_STATUS_OK )
{
}
else
{
switch( mcpsConfirm->McpsRequest )
{
case MCPS_UNCONFIRMED:
{
// Check Datarate
// Check TxPower
break;
}
case MCPS_CONFIRMED:
{
// Check Datarate
// Check TxPower
// Check AckReceived
// Check NbTrials
break;
}
case MCPS_PROPRIETARY:
{
break;
}
default:
break;
}
// Switch LED 4 ON
GpioWrite( &Led4, 1 );
TimerStart( &Led4Timer );
}
MibRequestConfirm_t mibGet;
MibRequestConfirm_t mibReq;
mibReq.Type = MIB_DEVICE_CLASS;
LoRaMacMibGetRequestConfirm( &mibReq );
printf( "\r\n###### ===== UPLINK FRAME %lu ==== ######\r\n", mcpsConfirm->UpLinkCounter );
printf( "\r\n" );
printf( "CLASS : %c\r\n", "ABC"[mibReq.Param.Class] );
printf( "\r\n" );
printf( "TX PORT : %d\r\n", AppData.Port );
if( AppData.BufferSize != 0 )
{
printf( "TX DATA : " );
if( AppData.MsgType == LORAMAC_HANDLER_CONFIRMED_MSG )
{
printf( "CONFIRMED - %s\r\n", ( mcpsConfirm->AckReceived != 0 ) ? "ACK" : "NACK" );
}
else
{
printf( "UNCONFIRMED\r\n" );
}
PrintHexBuffer( AppData.Buffer, AppData.BufferSize );
}
printf( "\r\n" );
printf( "DATA RATE : DR_%d\r\n", mcpsConfirm->Datarate );
mibGet.Type = MIB_CHANNELS;
if( LoRaMacMibGetRequestConfirm( &mibGet ) == LORAMAC_STATUS_OK )
{
printf( "U/L FREQ : %lu\r\n", mibGet.Param.ChannelList[mcpsConfirm->Channel].Frequency );
}
printf( "TX POWER : %d\r\n", mcpsConfirm->TxPower );
mibGet.Type = MIB_CHANNELS_MASK;
if( LoRaMacMibGetRequestConfirm( &mibGet ) == LORAMAC_STATUS_OK )
{
printf("CHANNEL MASK: ");
#if defined( REGION_AS923 ) || defined( REGION_CN779 ) || \
defined( REGION_EU868 ) || defined( REGION_IN865 ) || \
defined( REGION_KR920 ) || defined( REGION_RU864 )
for( uint8_t i = 0; i < 1; i++)
#elif defined( REGION_AU915 ) || defined( REGION_US915 )
for( uint8_t i = 0; i < 5; i++)
#else
#error "Please define a region in the compiler options."
#endif
{
printf("%04X ", mibGet.Param.ChannelsMask[i] );
}
printf("\r\n");
}
printf( "\r\n" );
}
/*!
* \brief MCPS-Indication event function
*
* \param [IN] mcpsIndication - Pointer to the indication structure,
* containing indication attributes.
*/
static void McpsIndication( McpsIndication_t *mcpsIndication )
{
printf( "\r\n###### ===== MCPS-Indication ==== ######\r\n" );
printf( "STATUS : %s\r\n", EventInfoStatusStrings[mcpsIndication->Status] );
if( mcpsIndication->Status != LORAMAC_EVENT_INFO_STATUS_OK )
{
return;
}
switch( mcpsIndication->McpsIndication )
{
case MCPS_UNCONFIRMED:
{
break;
}
case MCPS_CONFIRMED:
{
break;
}
case MCPS_PROPRIETARY:
{
break;
}
case MCPS_MULTICAST:
{
break;
}
default:
break;
}
// Check Multicast
// Check Port
// Check Datarate
// Check FramePending
if( mcpsIndication->FramePending == true )
{
// The server signals that it has pending data to be sent.
// We schedule an uplink as soon as possible to flush the server.
OnTxNextPacketTimerEvent( NULL );
}
// Check Buffer
// Check BufferSize
// Check Rssi
// Check Snr
// Check RxSlot
if( ComplianceTest.Running == true )
{
ComplianceTest.DownLinkCounter++;
}
if( mcpsIndication->RxData == true )
{
switch( mcpsIndication->Port )
{
case 1: // The application LED can be controlled on port 1 or 2
case 2:
if( mcpsIndication->BufferSize == 1 )
{
AppLedStateOn = mcpsIndication->Buffer[0] & 0x01;
GpioWrite( &Led3, ( ( AppLedStateOn & 0x01 ) != 0 ) ? 1 : 0 );
}
break;
case 224:
if( ComplianceTest.Running == false )
{
// Check compliance test enable command (i)
if( ( mcpsIndication->BufferSize == 4 ) &&
( mcpsIndication->Buffer[0] == 0x01 ) &&
( mcpsIndication->Buffer[1] == 0x01 ) &&
( mcpsIndication->Buffer[2] == 0x01 ) &&
( mcpsIndication->Buffer[3] == 0x01 ) )
{
IsTxConfirmed = false;
AppPort = 224;
AppDataSizeBackup = AppDataSize;
AppDataSize = 2;
ComplianceTest.DownLinkCounter = 0;
ComplianceTest.LinkCheck = false;
ComplianceTest.DemodMargin = 0;
ComplianceTest.NbGateways = 0;
ComplianceTest.Running = true;
ComplianceTest.State = 1;
MibRequestConfirm_t mibReq;
mibReq.Type = MIB_ADR;
mibReq.Param.AdrEnable = true;
LoRaMacMibSetRequestConfirm( &mibReq );
#if defined( REGION_EU868 ) || defined( REGION_RU864 ) || defined( REGION_CN779 ) || defined( REGION_EU433 )
LoRaMacTestSetDutyCycleOn( false );
#endif
}
}
else
{
ComplianceTest.State = mcpsIndication->Buffer[0];
switch( ComplianceTest.State )
{
case 0: // Check compliance test disable command (ii)
IsTxConfirmed = LORAWAN_CONFIRMED_MSG_ON;
AppPort = LORAWAN_APP_PORT;
AppDataSize = AppDataSizeBackup;
ComplianceTest.DownLinkCounter = 0;
ComplianceTest.Running = false;
MibRequestConfirm_t mibReq;
mibReq.Type = MIB_ADR;
mibReq.Param.AdrEnable = LORAWAN_ADR_ON;
LoRaMacMibSetRequestConfirm( &mibReq );
#if defined( REGION_EU868 ) || defined( REGION_RU864 ) || defined( REGION_CN779 ) || defined( REGION_EU433 )
LoRaMacTestSetDutyCycleOn( LORAWAN_DUTYCYCLE_ON );
#endif
break;
case 1: // (iii, iv)
AppDataSize = 2;
break;
case 2: // Enable confirmed messages (v)
IsTxConfirmed = true;
ComplianceTest.State = 1;
break;
case 3: // Disable confirmed messages (vi)
IsTxConfirmed = false;
ComplianceTest.State = 1;
break;
case 4: // (vii)
AppDataSize = mcpsIndication->BufferSize;
AppDataBuffer[0] = 4;
for( uint8_t i = 1; i < MIN( AppDataSize, LORAWAN_APP_DATA_MAX_SIZE ); i++ )
{
AppDataBuffer[i] = mcpsIndication->Buffer[i] + 1;
}
break;
case 5: // (viii)
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_LINK_CHECK;
LoRaMacStatus_t status = LoRaMacMlmeRequest( &mlmeReq );
printf( "\r\n###### ===== MLME-Request - MLME_LINK_CHECK ==== ######\r\n" );
printf( "STATUS : %s\r\n", MacStatusStrings[status] );
}
break;
case 6: // (ix)
{
// Disable TestMode and revert back to normal operation
IsTxConfirmed = LORAWAN_CONFIRMED_MSG_ON;
AppPort = LORAWAN_APP_PORT;
AppDataSize = AppDataSizeBackup;
ComplianceTest.DownLinkCounter = 0;
ComplianceTest.Running = false;
MibRequestConfirm_t mibReq;
mibReq.Type = MIB_ADR;
mibReq.Param.AdrEnable = LORAWAN_ADR_ON;
LoRaMacMibSetRequestConfirm( &mibReq );
#if defined( REGION_EU868 ) || defined( REGION_RU864 ) || defined( REGION_CN779 ) || defined( REGION_EU433 )
LoRaMacTestSetDutyCycleOn( LORAWAN_DUTYCYCLE_ON );
#endif
JoinNetwork( );
}
break;
case 7: // (x)
{
if( mcpsIndication->BufferSize == 3 )
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_TXCW;
mlmeReq.Req.TxCw.Timeout = ( uint16_t )( ( mcpsIndication->Buffer[1] << 8 ) | mcpsIndication->Buffer[2] );
LoRaMacStatus_t status = LoRaMacMlmeRequest( &mlmeReq );
printf( "\r\n###### ===== MLME-Request - MLME_TXCW ==== ######\r\n" );
printf( "STATUS : %s\r\n", MacStatusStrings[status] );
}
else if( mcpsIndication->BufferSize == 7 )
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_TXCW_1;
mlmeReq.Req.TxCw.Timeout = ( uint16_t )( ( mcpsIndication->Buffer[1] << 8 ) | mcpsIndication->Buffer[2] );
mlmeReq.Req.TxCw.Frequency = ( uint32_t )( ( mcpsIndication->Buffer[3] << 16 ) | ( mcpsIndication->Buffer[4] << 8 ) | mcpsIndication->Buffer[5] ) * 100;
mlmeReq.Req.TxCw.Power = mcpsIndication->Buffer[6];
LoRaMacStatus_t status = LoRaMacMlmeRequest( &mlmeReq );
printf( "\r\n###### ===== MLME-Request - MLME_TXCW1 ==== ######\r\n" );
printf( "STATUS : %s\r\n", MacStatusStrings[status] );
}
ComplianceTest.State = 1;
}
break;
case 8: // Send DeviceTimeReq
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_DEVICE_TIME;
LoRaMacMlmeRequest( &mlmeReq );
WakeUpState = DEVICE_STATE_SEND;
DeviceState = DEVICE_STATE_SEND;
}
break;
case 9: // Switch end device Class
{
MibRequestConfirm_t mibReq;
mibReq.Type = MIB_DEVICE_CLASS;
// CLASS_A = 0, CLASS_B = 1, CLASS_C = 2
mibReq.Param.Class = ( DeviceClass_t )mcpsIndication->Buffer[1];;
LoRaMacMibSetRequestConfirm( &mibReq );
DeviceState = DEVICE_STATE_SEND;
}
break;
case 10: // Send PingSlotInfoReq
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_PING_SLOT_INFO;
mlmeReq.Req.PingSlotInfo.PingSlot.Value = mcpsIndication->Buffer[1];
LoRaMacMlmeRequest( &mlmeReq );
WakeUpState = DEVICE_STATE_SEND;
DeviceState = DEVICE_STATE_SEND;
}
break;
case 11: // Send BeaconTimingReq
{
MlmeReq_t mlmeReq;
mlmeReq.Type = MLME_BEACON_TIMING;
LoRaMacMlmeRequest( &mlmeReq );
WakeUpState = DEVICE_STATE_SEND;
DeviceState = DEVICE_STATE_SEND;
}
break;
default:
break;
}
}
break;
default:
break;
}
}
// Switch LED 2 ON for each received downlink
GpioWrite( &Led2, 1 );
TimerStart( &Led2Timer );
const char *slotStrings[] = { "1", "2", "C", "C Multicast", "B Ping-Slot", "B Multicast Ping-Slot" };
printf( "\r\n###### ===== DOWNLINK FRAME %lu ==== ######\r\n", mcpsIndication->DownLinkCounter );
printf( "RX WINDOW : %s\r\n", slotStrings[mcpsIndication->RxSlot] );
printf( "RX PORT : %d\r\n", mcpsIndication->Port );
if( mcpsIndication->BufferSize != 0 )
{
printf( "RX DATA : \r\n" );
PrintHexBuffer( mcpsIndication->Buffer, mcpsIndication->BufferSize );
}
printf( "\r\n" );
printf( "DATA RATE : DR_%d\r\n", mcpsIndication->RxDatarate );
printf( "RX RSSI : %d\r\n", mcpsIndication->Rssi );
printf( "RX SNR : %d\r\n", mcpsIndication->Snr );
printf( "\r\n" );
}
/*!
* \brief MLME-Confirm event function
*
* \param [IN] mlmeConfirm - Pointer to the confirm structure,
* containing confirm attributes.
*/
static void MlmeConfirm( MlmeConfirm_t *mlmeConfirm )
{
MibRequestConfirm_t mibReq;
printf( "\r\n###### ===== MLME-Confirm ==== ######\r\n" );
printf( "STATUS : %s\r\n", EventInfoStatusStrings[mlmeConfirm->Status] );
if( mlmeConfirm->Status != LORAMAC_EVENT_INFO_STATUS_OK )
{
}
switch( mlmeConfirm->MlmeRequest )
{
case MLME_JOIN:
{
if( mlmeConfirm->Status == LORAMAC_EVENT_INFO_STATUS_OK )
{
MibRequestConfirm_t mibGet;
printf( "###### ===== JOINED ==== ######\r\n" );
printf( "\r\nOTAA\r\n\r\n" );
mibGet.Type = MIB_DEV_ADDR;
LoRaMacMibGetRequestConfirm( &mibGet );
printf( "DevAddr : %08lX\r\n", mibGet.Param.DevAddr );
printf( "\n\r\n" );
mibGet.Type = MIB_CHANNELS_DATARATE;
LoRaMacMibGetRequestConfirm( &mibGet );
printf( "DATA RATE : DR_%d\r\n", mibGet.Param.ChannelsDatarate );
printf( "\r\n" );
// Status is OK, node has joined the network
#if defined( USE_BEACON_TIMING )
DeviceState = DEVICE_STATE_REQ_BEACON_TIMING;
#else
DeviceState = DEVICE_STATE_REQ_DEVICE_TIME;
#endif
}
else
{
// Join was not successful. Try to join again
JoinNetwork( );
}
break;
}
case MLME_LINK_CHECK:
{
if( mlmeConfirm->Status == LORAMAC_EVENT_INFO_STATUS_OK )
{
// Check DemodMargin
// Check NbGateways
if( ComplianceTest.Running == true )
{
ComplianceTest.LinkCheck = true;
ComplianceTest.DemodMargin = mlmeConfirm->DemodMargin;
ComplianceTest.NbGateways = mlmeConfirm->NbGateways;
}
}
break;
}
case MLME_DEVICE_TIME:
{
// Setup the WakeUpState to DEVICE_STATE_SEND. This allows the
// application to initiate MCPS requests during a beacon acquisition
WakeUpState = DEVICE_STATE_SEND;
// Switch to the next state immediately
DeviceState = DEVICE_STATE_BEACON_ACQUISITION;
NextTx = true;
break;
}
case MLME_BEACON_TIMING:
{
// Setup the WakeUpState to DEVICE_STATE_SEND. This allows the
// application to initiate MCPS requests during a beacon acquisition
WakeUpState = DEVICE_STATE_SEND;
// Switch to the next state immediately
DeviceState = DEVICE_STATE_BEACON_ACQUISITION;
NextTx = true;
break;
}
case MLME_BEACON_ACQUISITION:
{
if( mlmeConfirm->Status == LORAMAC_EVENT_INFO_STATUS_OK )
{
WakeUpState = DEVICE_STATE_REQ_PINGSLOT_ACK;
}
else
{
#if defined( USE_BEACON_TIMING )
WakeUpState = DEVICE_STATE_REQ_BEACON_TIMING;
#else
WakeUpState = DEVICE_STATE_REQ_DEVICE_TIME;
#endif
}
break;
}
case MLME_PING_SLOT_INFO:
{
if( mlmeConfirm->Status == LORAMAC_EVENT_INFO_STATUS_OK )
{
mibReq.Type = MIB_DEVICE_CLASS;
mibReq.Param.Class = CLASS_B;
LoRaMacMibSetRequestConfirm( &mibReq );
printf( "\r\n\r\n###### ===== Switch to Class B done. ==== ######\r\n\r\n" );
WakeUpState = DEVICE_STATE_SEND;
DeviceState = WakeUpState;
NextTx = true;
}
else
{
WakeUpState = DEVICE_STATE_REQ_PINGSLOT_ACK;
}
break;
}
default:
break;
}
}
/*!
* \brief MLME-Indication event function
*
* \param [IN] mlmeIndication - Pointer to the indication structure.
*/
static void MlmeIndication( MlmeIndication_t *mlmeIndication )
{
MibRequestConfirm_t mibReq;
if( mlmeIndication->Status != LORAMAC_EVENT_INFO_STATUS_BEACON_LOCKED )
{
printf( "\r\n###### ===== MLME-Indication ==== ######\r\n" );
printf( "STATUS : %s\r\n", EventInfoStatusStrings[mlmeIndication->Status] );
}
if( mlmeIndication->Status != LORAMAC_EVENT_INFO_STATUS_OK )
{
}
switch( mlmeIndication->MlmeIndication )
{
case MLME_SCHEDULE_UPLINK:
{// The MAC signals that we shall provide an uplink as soon as possible
OnTxNextPacketTimerEvent( NULL );
break;
}
case MLME_BEACON_LOST:
{
mibReq.Type = MIB_DEVICE_CLASS;
mibReq.Param.Class = CLASS_A;
LoRaMacMibSetRequestConfirm( &mibReq );
printf( "\r\n\r\n###### ===== Switch to Class A done. ==== ######\r\n\r\n" );
// Switch to class A again
#if defined( USE_BEACON_TIMING )
WakeUpState = DEVICE_STATE_REQ_BEACON_TIMING;
#else
WakeUpState = DEVICE_STATE_REQ_DEVICE_TIME;
#endif
TimerStop( &LedBeaconTimer );
printf( "\r\n###### ===== BEACON LOST ==== ######\r\n" );
break;
}
case MLME_BEACON:
{
if( mlmeIndication->Status == LORAMAC_EVENT_INFO_STATUS_BEACON_LOCKED )
{
TimerStart( &LedBeaconTimer );
printf( "\r\n###### ===== BEACON %lu ==== ######\r\n", mlmeIndication->BeaconInfo.Time.Seconds );
printf( "GW DESC : %d\r\n", mlmeIndication->BeaconInfo.GwSpecific.InfoDesc );
printf( "GW INFO : " );
PrintHexBuffer( mlmeIndication->BeaconInfo.GwSpecific.Info, 6 );
printf( "\r\n" );
printf( "FREQ : %lu\r\n", mlmeIndication->BeaconInfo.Frequency );
printf( "DATA RATE : DR_%d\r\n", mlmeIndication->BeaconInfo.Datarate );
printf( "RX RSSI : %d\r\n", mlmeIndication->BeaconInfo.Rssi );
printf( "RX SNR : %d\r\n", mlmeIndication->BeaconInfo.Snr );
printf( "\r\n" );
}
else
{
TimerStop( &LedBeaconTimer );
printf( "\r\n###### ===== BEACON NOT RECEIVED ==== ######\r\n" );
}
break;
}
default:
break;
}
}
void OnMacProcessNotify( void )
{
IsMacProcessPending = 1;
}
/**
* Main application entry point.
*/
int main( void )
{
LoRaMacPrimitives_t macPrimitives;
LoRaMacCallback_t macCallbacks;
MibRequestConfirm_t mibReq;
LoRaMacStatus_t status;
uint8_t devEui[] = LORAWAN_DEVICE_EUI;
uint8_t joinEui[] = LORAWAN_JOIN_EUI;
BoardInitMcu( );
BoardInitPeriph( );
macPrimitives.MacMcpsConfirm = McpsConfirm;
macPrimitives.MacMcpsIndication = McpsIndication;
macPrimitives.MacMlmeConfirm = MlmeConfirm;
macPrimitives.MacMlmeIndication = MlmeIndication;
macCallbacks.GetBatteryLevel = BoardGetBatteryLevel;
macCallbacks.GetTemperatureLevel = NULL;
macCallbacks.NvmContextChange = NvmCtxMgmtEvent;
macCallbacks.MacProcessNotify = OnMacProcessNotify;
status = LoRaMacInitialization( &macPrimitives, &macCallbacks, ACTIVE_REGION );
if ( status != LORAMAC_STATUS_OK )
{
printf( "LoRaMac wasn't properly initialized, error: %s", MacStatusStrings[status] );
// Fatal error, endless loop.
while ( 1 )
{
}
}
DeviceState = DEVICE_STATE_RESTORE;
WakeUpState = DEVICE_STATE_START;
printf( "###### ===== ClassB demo application v1.0.0 ==== ######\r\n\r\n" );
while( 1 )
{
// Process Radio IRQ
if( Radio.IrqProcess != NULL )
{
Radio.IrqProcess( );
}
// Processes the LoRaMac events
LoRaMacProcess( );
switch( DeviceState )
{
case DEVICE_STATE_RESTORE:
{
// Try to restore from NVM and query the mac if possible.
if( NvmCtxMgmtRestore( ) == NVMCTXMGMT_STATUS_SUCCESS )
{
printf( "\r\n###### ===== CTXS RESTORED ==== ######\r\n\r\n" );
}
else
{
#if( OVER_THE_AIR_ACTIVATION == 0 )
// Tell the MAC layer which network server version are we connecting too.
mibReq.Type = MIB_ABP_LORAWAN_VERSION;
mibReq.Param.AbpLrWanVersion.Value = ABP_ACTIVATION_LRWAN_VERSION;
LoRaMacMibSetRequestConfirm( &mibReq );
#endif
#if( ABP_ACTIVATION_LRWAN_VERSION == ABP_ACTIVATION_LRWAN_VERSION_V10x )
mibReq.Type = MIB_GEN_APP_KEY;
mibReq.Param.GenAppKey = GenAppKey;
LoRaMacMibSetRequestConfirm( &mibReq );
#else
mibReq.Type = MIB_APP_KEY;
mibReq.Param.AppKey = AppKey;
LoRaMacMibSetRequestConfirm( &mibReq );
#endif
mibReq.Type = MIB_NWK_KEY;
mibReq.Param.NwkKey = NwkKey;
LoRaMacMibSetRequestConfirm( &mibReq );
// Initialize LoRaMac device unique ID if not already defined in Commissioning.h
if( ( devEui[0] == 0 ) && ( devEui[1] == 0 ) &&
( devEui[2] == 0 ) && ( devEui[3] == 0 ) &&
( devEui[4] == 0 ) && ( devEui[5] == 0 ) &&
( devEui[6] == 0 ) && ( devEui[7] == 0 ) )
{
BoardGetUniqueId( devEui );
}
mibReq.Type = MIB_DEV_EUI;
mibReq.Param.DevEui = devEui;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_JOIN_EUI;
mibReq.Param.JoinEui = joinEui;
LoRaMacMibSetRequestConfirm( &mibReq );
#if( OVER_THE_AIR_ACTIVATION == 0 )
// Choose a random device address if not already defined in Commissioning.h
if( DevAddr == 0 )
{
// Random seed initialization
srand1( BoardGetRandomSeed( ) );
// Choose a random device address
DevAddr = randr( 0, 0x01FFFFFF );
}
mibReq.Type = MIB_NET_ID;
mibReq.Param.NetID = LORAWAN_NETWORK_ID;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_DEV_ADDR;
mibReq.Param.DevAddr = DevAddr;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_F_NWK_S_INT_KEY;
mibReq.Param.FNwkSIntKey = FNwkSIntKey;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_S_NWK_S_INT_KEY;
mibReq.Param.SNwkSIntKey = SNwkSIntKey;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_NWK_S_ENC_KEY;
mibReq.Param.NwkSEncKey = NwkSEncKey;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_APP_S_KEY;
mibReq.Param.AppSKey = AppSKey;
LoRaMacMibSetRequestConfirm( &mibReq );
#endif
}
DeviceState = DEVICE_STATE_START;
break;
}
case DEVICE_STATE_START:
{
TimerInit( &TxNextPacketTimer, OnTxNextPacketTimerEvent );
TimerInit( &Led4Timer, OnLed4TimerEvent );
TimerSetValue( &Led4Timer, 25 );
TimerInit( &Led2Timer, OnLed2TimerEvent );
TimerSetValue( &Led2Timer, 25 );
TimerInit( &LedBeaconTimer, OnLedBeaconTimerEvent );
TimerSetValue( &LedBeaconTimer, 5000 );
mibReq.Type = MIB_PUBLIC_NETWORK;
mibReq.Param.EnablePublicNetwork = LORAWAN_PUBLIC_NETWORK;
LoRaMacMibSetRequestConfirm( &mibReq );
mibReq.Type = MIB_ADR;
mibReq.Param.AdrEnable = LORAWAN_ADR_ON;
LoRaMacMibSetRequestConfirm( &mibReq );
#if defined( REGION_EU868 ) || defined( REGION_RU864 ) || defined( REGION_CN779 ) || defined( REGION_EU433 )
LoRaMacTestSetDutyCycleOn( LORAWAN_DUTYCYCLE_ON );
#endif
mibReq.Type = MIB_SYSTEM_MAX_RX_ERROR;
mibReq.Param.SystemMaxRxError = 20;
LoRaMacMibSetRequestConfirm( &mibReq );
LoRaMacStart( );
mibReq.Type = MIB_NETWORK_ACTIVATION;
status = LoRaMacMibGetRequestConfirm( &mibReq );
if( status == LORAMAC_STATUS_OK )
{
if( mibReq.Param.NetworkActivation == ACTIVATION_TYPE_NONE )
{
DeviceState = DEVICE_STATE_JOIN;
}
else
{
DeviceState = DEVICE_STATE_SEND;
NextTx = true;
}
}
break;
}
case DEVICE_STATE_JOIN:
{
mibReq.Type = MIB_DEV_EUI;
LoRaMacMibGetRequestConfirm( &mibReq );
printf( "DevEui : %02X", mibReq.Param.DevEui[0] );
for( int i = 1; i < 8; i++ )
{
printf( "-%02X", mibReq.Param.DevEui[i] );
}
printf( "\r\n" );
mibReq.Type = MIB_JOIN_EUI;
LoRaMacMibGetRequestConfirm( &mibReq );
printf( "AppEui : %02X", mibReq.Param.JoinEui[0] );
for( int i = 1; i < 8; i++ )
{
printf( "-%02X", mibReq.Param.JoinEui[i] );
}
printf( "\r\n" );
printf( "AppKey : %02X", NwkKey[0] );
for( int i = 1; i < 16; i++ )
{
printf( " %02X", NwkKey[i] );
}
printf( "\n\r\n" );
#if( OVER_THE_AIR_ACTIVATION == 0 )
printf( "###### ===== JOINED ==== ######\r\n" );
printf( "\r\nABP\r\n\r\n" );
printf( "DevAddr : %08lX\r\n", DevAddr );
printf( "NwkSKey : %02X", FNwkSIntKey[0] );
for( int i = 1; i < 16; i++ )
{
printf( " %02X", FNwkSIntKey[i] );
}
printf( "\r\n" );
printf( "AppSKey : %02X", AppSKey[0] );
for( int i = 1; i < 16; i++ )
{
printf( " %02X", AppSKey[i] );
}
printf( "\n\r\n" );
mibReq.Type = MIB_NETWORK_ACTIVATION;
mibReq.Param.NetworkActivation = ACTIVATION_TYPE_ABP;
LoRaMacMibSetRequestConfirm( &mibReq );
#if defined( USE_BEACON_TIMING )
DeviceState = DEVICE_STATE_REQ_BEACON_TIMING;
#else
DeviceState = DEVICE_STATE_REQ_DEVICE_TIME;
#endif
#else
JoinNetwork( );
#endif
break;
}
case DEVICE_STATE_REQ_DEVICE_TIME:
{
MlmeReq_t mlmeReq;
if( NextTx == true )
{
mlmeReq.Type = MLME_DEVICE_TIME;
if( LoRaMacMlmeRequest( &mlmeReq ) == LORAMAC_STATUS_OK )
{
WakeUpState = DEVICE_STATE_SEND;
}
}
DeviceState = DEVICE_STATE_SEND;
break;
}
case DEVICE_STATE_REQ_BEACON_TIMING:
{
MlmeReq_t mlmeReq;
if( NextTx == true )
{
mlmeReq.Type = MLME_BEACON_TIMING;
if( LoRaMacMlmeRequest( &mlmeReq ) == LORAMAC_STATUS_OK )
{
WakeUpState = DEVICE_STATE_SEND;
}
}
DeviceState = DEVICE_STATE_SEND;
break;
}
case DEVICE_STATE_BEACON_ACQUISITION:
{
MlmeReq_t mlmeReq;
if( NextTx == true )
{
mlmeReq.Type = MLME_BEACON_ACQUISITION;
LoRaMacMlmeRequest( &mlmeReq );
NextTx = false;
}
DeviceState = DEVICE_STATE_SEND;
break;
}
case DEVICE_STATE_REQ_PINGSLOT_ACK:
{
MlmeReq_t mlmeReq;
if( NextTx == true )
{
mlmeReq.Type = MLME_LINK_CHECK;
LoRaMacMlmeRequest( &mlmeReq );
mlmeReq.Type = MLME_PING_SLOT_INFO;
mlmeReq.Req.PingSlotInfo.PingSlot.Fields.Periodicity = LORAWAN_DEFAULT_PING_SLOT_PERIODICITY;
mlmeReq.Req.PingSlotInfo.PingSlot.Fields.RFU = 0;
if( LoRaMacMlmeRequest( &mlmeReq ) == LORAMAC_STATUS_OK )
{
WakeUpState = DEVICE_STATE_SEND;
}
}
DeviceState = DEVICE_STATE_SEND;
break;
}
case DEVICE_STATE_SEND:
{
if( NextTx == true )
{
PrepareTxFrame( AppPort );
NextTx = SendFrame( );
}
DeviceState = DEVICE_STATE_CYCLE;
break;
}
case DEVICE_STATE_CYCLE:
{
DeviceState = DEVICE_STATE_SLEEP;
if( ComplianceTest.Running == true )
{
// Schedule next packet transmission
TxDutyCycleTime = 5000; // 5000 ms
}
else
{
// Schedule next packet transmission
TxDutyCycleTime = APP_TX_DUTYCYCLE + randr( -APP_TX_DUTYCYCLE_RND, APP_TX_DUTYCYCLE_RND );
}
// Schedule next packet transmission
TimerSetValue( &TxNextPacketTimer, TxDutyCycleTime );
TimerStart( &TxNextPacketTimer );
break;
}
case DEVICE_STATE_SLEEP:
{
if( NvmCtxMgmtStore( ) == NVMCTXMGMT_STATUS_SUCCESS )
{
printf( "\r\n###### ===== CTXS STORED ==== ######\r\n" );
}
CRITICAL_SECTION_BEGIN( );
if( IsMacProcessPending == 1 )
{
// Clear flag and prevent MCU to go into low power modes.
IsMacProcessPending = 0;
}
else
{
// The MCU wakes up through events
BoardLowPowerHandler( );
}
CRITICAL_SECTION_END( );
break;
}
default:
{
DeviceState = DEVICE_STATE_START;
break;
}
}
}
}
|
160761.c | #include "../src/assets/header.c"
#include "../src/assets/data_structures.c"
#include "../src/assets/builtins.c"
#define assert(bool) \
if(!bool) { \
printf("failure on line %d\n", __LINE__); \
return 1; \
}
void dump_tree(struct ObjectTree* tree) {
printf("tree: pointer: %p\n", tree);
printf(". key: %s\n", tree->key.data);
printf(". key_size: %d\n", tree->key.size);
printf(". integer_value: %lld\n", tree->value.integer.value);
printf(". left: %p\n", tree->left);
printf(". right: %p\n", tree->right);
printf(". parent: %p\n", tree->parent);
if(tree->left != NULL) dump_tree(tree->left);
if(tree->right != NULL) dump_tree(tree->right);
}
void dump_object(struct ObjectData* object) {
printf("object: pointer: %p\n", object);
printf(". sealed: %s\n", object->sealed ? "yes" : "no");
printf(". tree-head: %p\n", object->tree);
dump_tree(object->tree);
}
int main(int argc, char** argv) {
struct ObjectData object;
struct ObjectIterator it;
union Value value;
initialize_object(&object);
initialize_object_iterator(&it, &object);
assert(object_iterator_complete(&it));
value.t = INTEGER;
value.integer.value = 42;
assert(set_field(&object, (struct ByteArray){"jtfield", 7}, value));
initialize_object_iterator(&it, &object);
assert(!object_iterator_complete(&it));
assert(object_iterator_current_node(&it)->value.t == INTEGER);
assert(object_iterator_current_node(&it)->value.integer.value == 42);
object_iterator_step(&it);
assert(object_iterator_complete(&it));
value.t = INTEGER;
value.integer.value = 6141;
assert(set_field(&object, (struct ByteArray){"field1", 6}, value));
value.t = INTEGER;
value.integer.value = 14677;
assert(set_field(&object, (struct ByteArray){"field3", 6}, value));
value.t = INTEGER;
value.integer.value = 46131;
assert(set_field(&object, (struct ByteArray){"field2", 6}, value));
// dump_object(&object);
initialize_object_iterator(&it, &object);
assert(!object_iterator_complete(&it));
assert(object_iterator_current_node(&it)->value.t == INTEGER);
assert(object_iterator_current_node(&it)->value.integer.value == 6141);
object_iterator_step(&it);
assert(!object_iterator_complete(&it));
assert(object_iterator_current_node(&it)->value.t == INTEGER);
assert(object_iterator_current_node(&it)->value.integer.value == 46131);
object_iterator_step(&it);
assert(!object_iterator_complete(&it));
assert(object_iterator_current_node(&it)->value.t == INTEGER);
assert(object_iterator_current_node(&it)->value.integer.value == 14677);
object_iterator_step(&it);
assert(!object_iterator_complete(&it));
assert(object_iterator_current_node(&it)->value.t == INTEGER);
assert(object_iterator_current_node(&it)->value.integer.value == 42);
object_iterator_step(&it);
assert(object_iterator_complete(&it));
return 0;
}
|
147027.c | /**
* @File: flexible_button.c
* @Author: MurphyZhao
* @Date: 2018-09-29
*
* Copyright (c) 2018-2019 MurphyZhao <[email protected]>
* https://github.com/murphyzhao
* All rights reserved.
* 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.
*
* Change logs:
* Date Author Notes
* 2018-09-29 MurphyZhao First add
* 2019-08-02 MurphyZhao Migrate code to github.com/murphyzhao account
* 2019-12-26 MurphyZhao Refactor code and implement multiple clicks
*
*/
#include "flexible_button.h"
#ifndef NULL
#define NULL 0
#endif
#define EVENT_SET_AND_EXEC_CB(btn, evt) \
do \
{ \
btn->event = evt; \
if(btn->cb) \
btn->cb((flex_button_t*)btn); \
} while(0)
/**
* BTN_IS_PRESSED
*
* 1: is pressed
* 0: is not pressed
*/
#define BTN_IS_PRESSED(i) (g_btn_status_reg & (1 << i))
enum FLEX_BTN_STAGE
{
FLEX_BTN_STAGE_DEFAULT = 0,
FLEX_BTN_STAGE_DOWN = 1,
FLEX_BTN_STAGE_MULTIPLE_CLICK = 2
};
typedef uint32_t btn_type_t;
static flex_button_t *btn_head = NULL;
/**
* g_logic_level
*
* The logic level of the button pressed,
* Each bit represents a button.
*
* First registered button, the logic level of the button pressed is
* at the low bit of g_logic_level.
*/
btn_type_t g_logic_level = (btn_type_t)0;
/**
* g_btn_status_reg
*
* The status register of all button, each bit records the pressing state of a button.
*
* First registered button, the pressing state of the button is
* at the low bit of g_btn_status_reg.
*/
btn_type_t g_btn_status_reg = (btn_type_t)0;
static uint8_t button_cnt = 0;
/**
* @brief Register a user button
*
* @param button: button structure instance
* @return Number of keys that have been registered, or -1 when error
*/
int32_t flex_button_register(flex_button_t *button)
{
flex_button_t *curr = btn_head;
if (!button || (button_cnt > sizeof(btn_type_t) * 8))
{
return -1;
}
while (curr)
{
if(curr == button)
{
return -1; /* already exist. */
}
curr = curr->next;
}
/**
* First registered button is at the end of the 'linked list'.
* btn_head points to the head of the 'linked list'.
*/
button->next = btn_head;
button->status = FLEX_BTN_STAGE_DEFAULT;
button->event = FLEX_BTN_PRESS_NONE;
button->scan_cnt = 0;
button->click_cnt = 0;
button->max_multiple_clicks_interval = MAX_MULTIPLE_CLICKS_INTERVAL;
btn_head = button;
/**
* First registered button, the logic level of the button pressed is
* at the low bit of g_logic_level.
*/
g_logic_level |= (button->pressed_logic_level << button_cnt);
button_cnt ++;
return button_cnt;
}
/**
* @brief Read all key values in one scan cycle
*
* @param void
* @return none
*/
static void flex_button_read(void)
{
uint8_t i;
flex_button_t* target;
/* The button that was registered first, the button value is in the low position of raw_data */
btn_type_t raw_data = 0;
for(target = btn_head, i = button_cnt - 1;
(target != NULL) && (target->usr_button_read != NULL);
target = target->next, i--)
{
raw_data = raw_data | ((target->usr_button_read)(target) << i);
}
g_btn_status_reg = (~raw_data) ^ g_logic_level;
}
/**
* @brief Handle all key events in one scan cycle.
* Must be used after 'flex_button_read' API
*
* @param void
* @return Activated button count
*/
static uint8_t flex_button_process(void)
{
uint8_t i;
uint8_t active_btn_cnt = 0;
flex_button_t* target;
for (target = btn_head, i = 0; target != NULL; target = target->next, i ++)
{
if (target->status > FLEX_BTN_STAGE_DEFAULT)
{
target->scan_cnt ++;
if (target->scan_cnt >= ((1 << (sizeof(target->scan_cnt) * 8)) - 1))
{
target->scan_cnt = target->long_hold_start_tick;
}
}
switch (target->status)
{
case FLEX_BTN_STAGE_DEFAULT: /* stage: default(button up) */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
target->scan_cnt = 0;
target->click_cnt = 0;
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_DOWN);
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
}
else
{
target->event = FLEX_BTN_PRESS_NONE;
}
break;
case FLEX_BTN_STAGE_DOWN: /* stage: button down */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
if (target->click_cnt > 0) /* multiple click */
{
if (target->scan_cnt > target->max_multiple_clicks_interval)
{
EVENT_SET_AND_EXEC_CB(target,
target->click_cnt < FLEX_BTN_PRESS_REPEAT_CLICK ?
target->click_cnt :
FLEX_BTN_PRESS_REPEAT_CLICK);
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
target->scan_cnt = 0;
target->click_cnt = 0;
}
}
else if (target->scan_cnt >= target->long_hold_start_tick)
{
if (target->event != FLEX_BTN_PRESS_LONG_HOLD)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_HOLD);
}
}
else if (target->scan_cnt >= target->long_press_start_tick)
{
if (target->event != FLEX_BTN_PRESS_LONG_START)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_START);
}
}
else if (target->scan_cnt >= target->short_press_start_tick)
{
if (target->event != FLEX_BTN_PRESS_SHORT_START)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_SHORT_START);
}
}
}
else /* button up */
{
if (target->scan_cnt >= target->long_hold_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_HOLD_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else if (target->scan_cnt >= target->long_press_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else if (target->scan_cnt >= target->short_press_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_SHORT_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else
{
/* swtich to multiple click stage */
target->status = FLEX_BTN_STAGE_MULTIPLE_CLICK;
target->click_cnt ++;
}
}
break;
case FLEX_BTN_STAGE_MULTIPLE_CLICK: /* stage: multiple click */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
target->scan_cnt = 0;
}
else
{
if (target->scan_cnt > target->max_multiple_clicks_interval)
{
EVENT_SET_AND_EXEC_CB(target,
target->click_cnt < FLEX_BTN_PRESS_REPEAT_CLICK ?
target->click_cnt :
FLEX_BTN_PRESS_REPEAT_CLICK);
/* swtich to default stage */
target->status = FLEX_BTN_STAGE_DEFAULT;
}
}
break;
}
if (target->status > FLEX_BTN_STAGE_DEFAULT)
{
active_btn_cnt ++;
}
}
return active_btn_cnt;
}
/**
* flex_button_event_read
*
* @brief Get the button event of the specified button.
*
* @param button: button structure instance
* @return button event
*/
flex_button_event_t flex_button_event_read(flex_button_t* button)
{
return (flex_button_event_t)(button->event);
}
/**
* flex_button_scan
*
* @brief Start key scan.
* Need to be called cyclically within the specified period.
* Sample cycle: 5 - 20ms
*
* @param void
* @return Activated button count
*/
uint8_t flex_button_scan(void)
{
flex_button_read();
return flex_button_process();
}
|
307275.c | //1+2+3+4...
#include "stdio.h"
int main(){
int n,sum=0;
printf("Enter Limit: ");
scanf("%d",&n);
int i;
i=1;
do
{
printf("%d ",i);
sum+=i;
i++;
}while( i <= n );
printf("\nSum: %d",sum);
} |
932944.c | /*************************************************************************************************/
/*!
* \file
*
* \brief Device manager connection management module for legacy master.
*
* Copyright (c) 2016-2018 Arm Ltd. All Rights Reserved.
*
* Copyright (c) 2019 Packetcraft, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************************************************/
#include "wsf_types.h"
#include "dm_api.h"
#include "dm_dev.h"
#include "dm_main.h"
#include "dm_conn.h"
/**************************************************************************************************
Local Variables
**************************************************************************************************/
/* Action set for this module */
static const dmConnAct_t dmConnActSetMaster[] =
{
dmConnSmActOpen,
dmConnSmActCancelOpen
};
/*************************************************************************************************/
/*!
* \brief Open a connection to a peer device with the given address.
*
* \param initPhys Initiating PHYs.
* \param addrType Address type.
* \param pAddr Peer device address.
*
* \return Connection identifier.
*/
/*************************************************************************************************/
static void dmConnOpen(uint8_t initPhys, uint8_t addrType, uint8_t *pAddr)
{
uint8_t phyIdx = DmScanPhyToIdx(HCI_SCAN_PHY_LE_1M_BIT);
/* Create connection */
HciLeCreateConnCmd(dmConnCb.scanInterval[phyIdx], dmConnCb.scanWindow[phyIdx], dmCb.initFiltPolicy,
addrType, pAddr, DmLlAddrType(dmCb.connAddrType), &(dmConnCb.connSpec[phyIdx]));
/* pass connection initiation started to dev priv */
dmDevPassEvtToDevPriv(DM_DEV_PRIV_MSG_CTRL, DM_DEV_PRIV_MSG_CONN_INIT_START, 0, 0);
}
/*************************************************************************************************/
/*!
* \brief Open a connection.
*
* \param pMsg WSF message.
* \param pCcb Connection control block.
*
* \return None.
*/
/*************************************************************************************************/
void dmConnSmActOpen(dmConnCcb_t *pCcb, dmConnMsg_t *pMsg)
{
dmConnOpen(pMsg->apiOpen.initPhys, pMsg->apiOpen.addrType, pMsg->apiOpen.peerAddr);
}
/*************************************************************************************************/
/*!
* \brief Initialize DM connection manager for operation as legacy master.
*
* \return None.
*/
/*************************************************************************************************/
void DmConnMasterInit(void)
{
WsfTaskLock();
dmConnActSet[DM_CONN_ACT_SET_MASTER] = (dmConnAct_t *) dmConnActSetMaster;
dmConnUpdActSet[DM_CONN_ACT_SET_MASTER] = (dmConnAct_t *) dmConnUpdActSetMaster;
WsfTaskUnlock();
}
|
320533.c | /* $OpenBSD: index.c,v 1.5 2005/08/08 08:05:37 espie Exp $ */
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <string.h>
char *
#ifdef STRCHR
strchr(const char *p, int ch)
#else
index(const char *p, int ch)
#endif
{
for (;; ++p) {
if (*p == ch)
return((char *)p);
if (!*p)
return((char *)NULL);
}
/* NOTREACHED */
}
|
894173.c | /*
Copyright (C) 2021 The Falco Authors.
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 <stdio.h>
#include <stdlib.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/uio.h>
#else
struct iovec {
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
#endif
#include "scap.h"
#include "scap-int.h"
#include "scap_savefile.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// WRITE FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Write data into a dump file
//
int scap_dump_write(scap_dumper_t *d, void* buf, unsigned len)
{
if(d->m_type == DT_FILE)
{
return gzwrite(d->m_f, buf, len);
}
else
{
if(d->m_targetbufcurpos + len < d->m_targetbufend)
{
memcpy(d->m_targetbufcurpos, buf, len);
d->m_targetbufcurpos += len;
return len;
}
else
{
return -1;
}
}
}
int scap_dump_writev(scap_dumper_t *d, const struct iovec *iov, int iovcnt)
{
unsigned totlen = 0;
int i;
for (i = 0; i < iovcnt; i++)
{
if(scap_dump_write(d, iov[i].iov_base, iov[i].iov_len) < 0)
{
return -1;
}
totlen += iov[i].iov_len;
}
return totlen;
}
#ifdef USE_ZLIB
int32_t compr(uint8_t* dest, uint64_t* destlen, const uint8_t* source, uint64_t sourcelen, int level)
{
uLongf dl = compressBound(sourcelen);
if(dl >= *destlen)
{
return SCAP_FAILURE;
}
int res = compress2(dest, &dl, source, sourcelen, level);
if(res == Z_OK)
{
*destlen = (uint64_t)dl;
return SCAP_SUCCESS;
}
else
{
return SCAP_FAILURE;
}
}
#endif
uint8_t* scap_get_memorydumper_curpos(scap_dumper_t *d)
{
return d->m_targetbufcurpos;
}
#ifndef WIN32
static inline uint32_t scap_normalize_block_len(uint32_t blocklen)
#else
static uint32_t scap_normalize_block_len(uint32_t blocklen)
#endif
{
return ((blocklen + 3) >> 2) << 2;
}
static int32_t scap_write_padding(scap_dumper_t *d, uint32_t blocklen)
{
int32_t val = 0;
uint32_t bytestowrite = scap_normalize_block_len(blocklen) - blocklen;
if(scap_dump_write(d, &val, bytestowrite) == bytestowrite)
{
return SCAP_SUCCESS;
}
else
{
return SCAP_FAILURE;
}
}
int32_t scap_write_proc_fds(scap_t *handle, struct scap_threadinfo *tinfo, scap_dumper_t *d)
{
block_header bh;
uint32_t bt;
uint32_t totlen = MEMBER_SIZE(scap_threadinfo, tid); // This includes the tid
uint32_t idx = 0;
struct scap_fdinfo *fdi;
struct scap_fdinfo *tfdi;
uint32_t* lengths = calloc(HASH_COUNT(tinfo->fdlist), sizeof(uint32_t));
if(lengths == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_write_proc_fds memory allocation failure");
return SCAP_FAILURE;
}
//
// First pass of the table to calculate the lengths
//
HASH_ITER(hh, tinfo->fdlist, fdi, tfdi)
{
if(fdi->type != SCAP_FD_UNINITIALIZED &&
fdi->type != SCAP_FD_UNKNOWN)
{
uint32_t fl = scap_fd_info_len(fdi);
lengths[idx++] = fl;
totlen += fl;
}
}
idx = 0;
//
// Create the block
//
bh.block_type = FDL_BLOCK_TYPE_V2;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4);
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh))
{
free(lengths);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd1)");
return SCAP_FAILURE;
}
//
// Write the tid
//
if(scap_dump_write(d, &tinfo->tid, sizeof(tinfo->tid)) != sizeof(tinfo->tid))
{
free(lengths);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd2)");
return SCAP_FAILURE;
}
//
// Second pass of the table to dump it
//
HASH_ITER(hh, tinfo->fdlist, fdi, tfdi)
{
if(fdi->type != SCAP_FD_UNINITIALIZED && fdi->type != SCAP_FD_UNKNOWN)
{
if(scap_fd_write_to_disk(handle, fdi, d, lengths[idx++]) != SCAP_SUCCESS)
{
free(lengths);
return SCAP_FAILURE;
}
}
}
free(lengths);
//
// Add the padding
//
if(scap_write_padding(d, totlen) != SCAP_SUCCESS)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd3)");
return SCAP_FAILURE;
}
//
// Create the trailer
//
bt = bh.block_total_length;
if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd4)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the fd list blocks
//
static int32_t scap_write_fdlist(scap_t *handle, scap_dumper_t *d)
{
struct scap_threadinfo *tinfo;
struct scap_threadinfo *ttinfo;
int32_t res;
//
// No fd list on disk if the source is a plugin
//
if(handle->m_mode == SCAP_MODE_PLUGIN)
{
return SCAP_SUCCESS;
}
HASH_ITER(hh, handle->m_proclist, tinfo, ttinfo)
{
if(!tinfo->filtered_out)
{
res = scap_write_proc_fds(handle, tinfo, d);
if(res != SCAP_SUCCESS)
{
return res;
}
}
}
return SCAP_SUCCESS;
}
//
// Write the process list block
//
int32_t scap_write_proclist_header(scap_t *handle, scap_dumper_t *d, uint32_t totlen)
{
block_header bh;
//
// Create the block header
//
bh.block_type = PL_BLOCK_TYPE_V9;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4);
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (1)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the process list block
//
int32_t scap_write_proclist_trailer(scap_t *handle, scap_dumper_t *d, uint32_t totlen)
{
block_header bh;
uint32_t bt;
bh.block_type = PL_BLOCK_TYPE_V9;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4);
//
// Blocks need to be 4-byte padded
//
if(scap_write_padding(d, totlen) != SCAP_SUCCESS)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (3)");
return SCAP_FAILURE;
}
//
// Create the trailer
//
bt = bh.block_total_length;
if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (4)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the process list block
//
int32_t scap_write_proclist_entry(scap_t *handle, scap_dumper_t *d, struct scap_threadinfo *tinfo, uint32_t len)
{
struct iovec args = {tinfo->args, tinfo->args_len};
struct iovec env = {tinfo->env, tinfo->env_len};
struct iovec cgroups = {tinfo->cgroups, tinfo->cgroups_len};
return scap_write_proclist_entry_bufs(handle, d, tinfo, len,
tinfo->comm,
tinfo->exe,
tinfo->exepath,
&args, 1,
&env, 1,
tinfo->cwd,
&cgroups, 1,
tinfo->root);
}
static uint16_t iov_size(const struct iovec *iov, uint32_t iovcnt)
{
uint16_t len = 0;
uint32_t i;
for (i = 0; i < iovcnt; i++)
{
len += iov[i].iov_len;
}
return len;
}
int32_t scap_write_proclist_entry_bufs(scap_t *handle, scap_dumper_t *d, struct scap_threadinfo *tinfo, uint32_t len,
const char *comm,
const char *exe,
const char *exepath,
const struct iovec *args, int argscnt,
const struct iovec *envs, int envscnt,
const char *cwd,
const struct iovec *cgroups, int cgroupscnt,
const char *root)
{
uint16_t commlen;
uint16_t exelen;
uint16_t exepathlen;
uint16_t cwdlen;
uint16_t rootlen;
uint16_t argslen;
uint16_t envlen;
uint16_t cgroupslen;
commlen = (uint16_t)strnlen(comm, SCAP_MAX_PATH_SIZE);
exelen = (uint16_t)strnlen(exe, SCAP_MAX_PATH_SIZE);
exepathlen = (uint16_t)strnlen(exepath, SCAP_MAX_PATH_SIZE);
cwdlen = (uint16_t)strnlen(cwd, SCAP_MAX_PATH_SIZE);
rootlen = (uint16_t)strnlen(root, SCAP_MAX_PATH_SIZE);
argslen = iov_size(args, argscnt);
envlen = iov_size(envs, envscnt);
cgroupslen = iov_size(cgroups, cgroupscnt);
if(scap_dump_write(d, &len, sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->tid), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->pid), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->ptid), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->sid), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->vpgid), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &commlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, (char *) comm, commlen) != commlen ||
scap_dump_write(d, &exelen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, (char *) exe, exelen) != exelen ||
scap_dump_write(d, &exepathlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, (char *) exepath, exepathlen) != exepathlen ||
scap_dump_write(d, &argslen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_writev(d, args, argscnt) != argslen ||
scap_dump_write(d, &cwdlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, (char *) cwd, cwdlen) != cwdlen ||
scap_dump_write(d, &(tinfo->fdlimit), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->flags), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->uid), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->gid), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->vmsize_kb), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->vmrss_kb), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->vmswap_kb), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->pfmajor), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->pfminor), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &envlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_writev(d, envs, envscnt) != envlen ||
scap_dump_write(d, &(tinfo->vtid), sizeof(int64_t)) != sizeof(int64_t) ||
scap_dump_write(d, &(tinfo->vpid), sizeof(int64_t)) != sizeof(int64_t) ||
scap_dump_write(d, &(cgroupslen), sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_writev(d, cgroups, cgroupscnt) != cgroupslen ||
scap_dump_write(d, &rootlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, (char *) root, rootlen) != rootlen ||
scap_dump_write(d, &(tinfo->loginuid), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(tinfo->exe_writable), sizeof(uint8_t)) != sizeof(uint8_t) ||
scap_dump_write(d, &(tinfo->cap_inheritable), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->cap_permitted), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(tinfo->cap_effective), sizeof(uint64_t)) != sizeof(uint64_t))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (2)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the process list block
//
static int32_t scap_write_proclist(scap_t *handle, scap_dumper_t *d)
{
uint32_t totlen = 0;
uint32_t idx = 0;
struct scap_threadinfo *tinfo;
struct scap_threadinfo *ttinfo;
//
// No process list on disk if the source is a plugin
//
if(handle->m_mode == SCAP_MODE_PLUGIN)
{
return SCAP_SUCCESS;
}
uint32_t* lengths = calloc(HASH_COUNT(handle->m_proclist), sizeof(uint32_t));
if(lengths == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_write_proclist memory allocation failure");
return SCAP_FAILURE;
}
//
// First pass of the table to calculate the lengths
//
HASH_ITER(hh, handle->m_proclist, tinfo, ttinfo)
{
if(!tinfo->filtered_out)
{
//
// NB: new fields must be appended
//
uint32_t il= (uint32_t)
(sizeof(uint32_t) + // len
sizeof(uint64_t) + // tid
sizeof(uint64_t) + // pid
sizeof(uint64_t) + // ptid
sizeof(uint64_t) + // sid
sizeof(uint64_t) + // vpgid
2 + strnlen(tinfo->comm, SCAP_MAX_PATH_SIZE) +
2 + strnlen(tinfo->exe, SCAP_MAX_PATH_SIZE) +
2 + strnlen(tinfo->exepath, SCAP_MAX_PATH_SIZE) +
2 + tinfo->args_len +
2 + strnlen(tinfo->cwd, SCAP_MAX_PATH_SIZE) +
sizeof(uint64_t) + // fdlimit
sizeof(uint32_t) + // flags
sizeof(uint32_t) + // uid
sizeof(uint32_t) + // gid
sizeof(uint32_t) + // vmsize_kb
sizeof(uint32_t) + // vmrss_kb
sizeof(uint32_t) + // vmswap_kb
sizeof(uint64_t) + // pfmajor
sizeof(uint64_t) + // pfminor
2 + tinfo->env_len +
sizeof(int64_t) + // vtid
sizeof(int64_t) + // vpid
2 + tinfo->cgroups_len +
2 + strnlen(tinfo->root, SCAP_MAX_PATH_SIZE) +
sizeof(int32_t) + // loginuid;
sizeof(uint8_t) + // exe_writable
sizeof(uint64_t) + // cap_inheritable
sizeof(uint64_t) + // cap_permitted
sizeof(uint64_t)); // cap_effective
lengths[idx++] = il;
totlen += il;
}
}
idx = 0;
if(scap_write_proclist_header(handle, d, totlen) != SCAP_SUCCESS)
{
free(lengths);
return SCAP_FAILURE;
}
//
// Second pass of the table to dump it
//
HASH_ITER(hh, handle->m_proclist, tinfo, ttinfo)
{
if(tinfo->filtered_out)
{
continue;
}
if(scap_write_proclist_entry(handle, d, tinfo, lengths[idx++]) != SCAP_SUCCESS)
{
free(lengths);
return SCAP_FAILURE;
}
}
free(lengths);
return scap_write_proclist_trailer(handle, d, totlen);
}
//
// Write the machine info block
//
static int32_t scap_write_machine_info(scap_t *handle, scap_dumper_t *d)
{
block_header bh;
uint32_t bt;
//
// No machine info on disk if the source is a plugin
//
if(handle->m_mode == SCAP_MODE_PLUGIN)
{
return SCAP_SUCCESS;
}
//
// Write the section header
//
bh.block_type = MI_BLOCK_TYPE;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(scap_machine_info) + 4);
bt = bh.block_total_length;
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) ||
scap_dump_write(d, &handle->m_machine_info, sizeof(handle->m_machine_info)) != sizeof(handle->m_machine_info) ||
scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (MI1)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the interface list block
//
static int32_t scap_write_iflist(scap_t *handle, scap_dumper_t* d)
{
block_header bh;
uint32_t bt;
uint32_t entrylen;
uint32_t totlen = 0;
uint32_t j;
//
// No interface list on disk if the source is a plugin
//
if(handle->m_mode == SCAP_MODE_PLUGIN)
{
return SCAP_SUCCESS;
}
//
// Get the interface list
//
if(handle->m_addrlist == NULL)
{
//
// This can happen when the event source is a capture that was generated by a plugin, no big deal
//
return SCAP_SUCCESS;
}
//
// Create the block
//
bh.block_type = IL_BLOCK_TYPE_V2;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + (handle->m_addrlist->n_v4_addrs + handle->m_addrlist->n_v6_addrs)*sizeof(uint32_t) +
handle->m_addrlist->totlen + 4);
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF1)");
return SCAP_FAILURE;
}
//
// Dump the ipv4 list
//
for(j = 0; j < handle->m_addrlist->n_v4_addrs; j++)
{
scap_ifinfo_ipv4 *entry = &(handle->m_addrlist->v4list[j]);
entrylen = sizeof(scap_ifinfo_ipv4) + entry->ifnamelen - SCAP_MAX_PATH_SIZE;
if(scap_dump_write(d, &entrylen, sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(entry->type), sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, &(entry->ifnamelen), sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, &(entry->addr), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(entry->netmask), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(entry->bcast), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(entry->linkspeed), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF2)");
return SCAP_FAILURE;
}
totlen += sizeof(uint32_t) + entrylen;
}
//
// Dump the ipv6 list
//
for(j = 0; j < handle->m_addrlist->n_v6_addrs; j++)
{
scap_ifinfo_ipv6 *entry = &(handle->m_addrlist->v6list[j]);
entrylen = sizeof(scap_ifinfo_ipv6) + entry->ifnamelen - SCAP_MAX_PATH_SIZE;
if(scap_dump_write(d, &entrylen, sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(entry->type), sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, &(entry->ifnamelen), sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, &(entry->addr), SCAP_IPV6_ADDR_LEN) != SCAP_IPV6_ADDR_LEN ||
scap_dump_write(d, &(entry->netmask), SCAP_IPV6_ADDR_LEN) != SCAP_IPV6_ADDR_LEN ||
scap_dump_write(d, &(entry->bcast), SCAP_IPV6_ADDR_LEN) != SCAP_IPV6_ADDR_LEN ||
scap_dump_write(d, &(entry->linkspeed), sizeof(uint64_t)) != sizeof(uint64_t) ||
scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF2)");
return SCAP_FAILURE;
}
totlen += sizeof(uint32_t) + entrylen;
}
//
// Blocks need to be 4-byte padded
//
if(scap_write_padding(d, totlen) != SCAP_SUCCESS)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF3)");
return SCAP_FAILURE;
}
//
// Create the trailer
//
bt = bh.block_total_length;
if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF4)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Write the user list block
//
static int32_t scap_write_userlist(scap_t *handle, scap_dumper_t* d)
{
block_header bh;
uint32_t bt;
uint32_t j;
uint16_t namelen;
uint16_t homedirlen;
uint16_t shelllen;
uint8_t type;
uint32_t totlen = 0;
//
// No user list on disk if the source is a plugin
//
if(handle->m_mode == SCAP_MODE_PLUGIN)
{
return SCAP_SUCCESS;
}
//
// Make sure we have a user list interface list
//
if(handle->m_userlist == NULL)
{
//
// This can happen when the event source is a capture that was generated by a plugin, no big deal
//
return SCAP_SUCCESS;
}
uint32_t* lengths = calloc(handle->m_userlist->nusers + handle->m_userlist->ngroups, sizeof(uint32_t));
if(lengths == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_write_userlist memory allocation failure (1)");
return SCAP_FAILURE;
}
//
// Calculate the lengths
//
for(j = 0; j < handle->m_userlist->nusers; j++)
{
scap_userinfo* info = &handle->m_userlist->users[j];
namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN);
homedirlen = (uint16_t)strnlen(info->homedir, SCAP_MAX_PATH_SIZE);
shelllen = (uint16_t)strnlen(info->shell, SCAP_MAX_PATH_SIZE);
// NB: new fields must be appended
size_t ul = sizeof(uint32_t) + sizeof(type) + sizeof(info->uid) + sizeof(info->gid) + sizeof(uint16_t) +
namelen + sizeof(uint16_t) + homedirlen + sizeof(uint16_t) + shelllen;
totlen += ul;
lengths[j] = ul;
}
for(j = 0; j < handle->m_userlist->ngroups; j++)
{
scap_groupinfo* info = &handle->m_userlist->groups[j];
namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN);
// NB: new fields must be appended
uint32_t gl = sizeof(uint32_t) + sizeof(type) + sizeof(info->gid) + sizeof(uint16_t) + namelen;
totlen += gl;
lengths[handle->m_userlist->nusers + j] = gl;
}
//
// Create the block
//
bh.block_type = UL_BLOCK_TYPE_V2;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4);
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh))
{
free(lengths);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF1)");
return SCAP_FAILURE;
}
//
// Dump the users
//
type = USERBLOCK_TYPE_USER;
for(j = 0; j < handle->m_userlist->nusers; j++)
{
scap_userinfo* info = &handle->m_userlist->users[j];
namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN);
homedirlen = (uint16_t)strnlen(info->homedir, SCAP_MAX_PATH_SIZE);
shelllen = (uint16_t)strnlen(info->shell, SCAP_MAX_PATH_SIZE);
if(scap_dump_write(d, &(lengths[j]), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) ||
scap_dump_write(d, &(info->uid), sizeof(info->uid)) != sizeof(info->uid) ||
scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) ||
scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, info->name, namelen) != namelen ||
scap_dump_write(d, &homedirlen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, info->homedir, homedirlen) != homedirlen ||
scap_dump_write(d, &shelllen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, info->shell, shelllen) != shelllen)
{
free(lengths);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (U1)");
return SCAP_FAILURE;
}
}
//
// Dump the groups
//
type = USERBLOCK_TYPE_GROUP;
for(j = 0; j < handle->m_userlist->ngroups; j++)
{
scap_groupinfo* info = &handle->m_userlist->groups[j];
namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN);
if(scap_dump_write(d, &(lengths[handle->m_userlist->nusers + j]), sizeof(uint32_t)) != sizeof(uint32_t) ||
scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) ||
scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) ||
scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) ||
scap_dump_write(d, info->name, namelen) != namelen)
{
free(lengths);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (U2)");
return SCAP_FAILURE;
}
}
free(lengths);
//
// Blocks need to be 4-byte padded
//
if(scap_write_padding(d, totlen) != SCAP_SUCCESS)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF3)");
return SCAP_FAILURE;
}
//
// Create the trailer
//
bt = bh.block_total_length;
if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF4)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Create the dump file headers and add the tables
//
int32_t scap_setup_dump(scap_t *handle, scap_dumper_t* d, const char *fname)
{
block_header bh;
section_header_block sh;
uint32_t bt;
//
// Write the section header
//
bh.block_type = SHB_BLOCK_TYPE;
bh.block_total_length = sizeof(block_header) + sizeof(section_header_block) + 4;
sh.byte_order_magic = SHB_MAGIC;
sh.major_version = CURRENT_MAJOR_VERSION;
sh.minor_version = CURRENT_MINOR_VERSION;
sh.section_length = 0xffffffffffffffffLL;
bt = bh.block_total_length;
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) ||
scap_dump_write(d, &sh, sizeof(sh)) != sizeof(sh) ||
scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file %s (5)", fname);
return SCAP_FAILURE;
}
//
// If we're dumping in live mode, refresh the process tables list
// so we don't lose information about processes created in the interval
// between opening the handle and starting the dump
//
#if defined(HAS_CAPTURE) && !defined(WIN32)
if(handle->m_reader == NULL && handle->refresh_proc_table_when_saving)
{
proc_entry_callback tcb = handle->m_proc_callback;
handle->m_proc_callback = NULL;
scap_proc_free_table(handle);
char filename[SCAP_MAX_PATH_SIZE];
snprintf(filename, sizeof(filename), "%s/proc", scap_get_host_root());
if(scap_proc_scan_proc_dir(handle, filename, handle->m_lasterr) != SCAP_SUCCESS)
{
handle->m_proc_callback = tcb;
return SCAP_FAILURE;
}
handle->m_proc_callback = tcb;
}
#endif
//
// Write the machine info
//
if(scap_write_machine_info(handle, d) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
//
// Write the interface list
//
if(scap_write_iflist(handle, d) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
//
// Write the user list
//
if(scap_write_userlist(handle, d) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
//
// Write the process list
//
if(scap_write_proclist(handle, d) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
//
// Write the fd lists
//
if(scap_write_fdlist(handle, d) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
//
// If the user doesn't need the thread table, free it
//
if(handle->m_proc_callback != NULL)
{
scap_proc_free_table(handle);
}
//
// Done, return the file
//
return SCAP_SUCCESS;
}
// fname is only used for log messages in scap_setup_dump
static scap_dumper_t *scap_dump_open_gzfile(scap_t *handle, gzFile gzfile, const char *fname, bool skip_proc_scan)
{
scap_dumper_t* res = (scap_dumper_t*)malloc(sizeof(scap_dumper_t));
res->m_f = gzfile;
res->m_type = DT_FILE;
res->m_targetbuf = NULL;
res->m_targetbufcurpos = NULL;
res->m_targetbufend = NULL;
bool tmp_refresh_proc_table_when_saving = handle->refresh_proc_table_when_saving;
if(skip_proc_scan)
{
handle->refresh_proc_table_when_saving = false;
}
if(scap_setup_dump(handle, res, fname) != SCAP_SUCCESS)
{
res = NULL;
}
if(skip_proc_scan)
{
handle->refresh_proc_table_when_saving = tmp_refresh_proc_table_when_saving;
}
return res;
}
//
// Open a "savefile" for writing.
//
scap_dumper_t *scap_dump_open(scap_t *handle, const char *fname, compression_mode compress, bool skip_proc_scan)
{
gzFile f = NULL;
int fd = -1;
const char* mode;
switch(compress)
{
case SCAP_COMPRESSION_GZIP:
mode = "wb";
break;
case SCAP_COMPRESSION_NONE:
mode = "wbT";
break;
default:
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid compression mode");
return NULL;
}
if(fname[0] == '-' && fname[1] == '\0')
{
#ifndef WIN32
fd = dup(STDOUT_FILENO);
#else
fd = 1;
#endif
if(fd != -1)
{
f = gzdopen(fd, mode);
fname = "standard output";
}
}
else
{
f = gzopen(fname, mode);
}
if(f == NULL)
{
#ifndef WIN32
if(fd != -1)
{
close(fd);
}
#endif
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "can't open %s", fname);
return NULL;
}
return scap_dump_open_gzfile(handle, f, fname, skip_proc_scan);
}
//
// Open a savefile for writing, using the provided fd
scap_dumper_t* scap_dump_open_fd(scap_t *handle, int fd, compression_mode compress, bool skip_proc_scan)
{
gzFile f = NULL;
switch(compress)
{
case SCAP_COMPRESSION_GZIP:
f = gzdopen(fd, "wb");
break;
case SCAP_COMPRESSION_NONE:
f = gzdopen(fd, "wbT");
break;
default:
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid compression mode");
return NULL;
}
if(f == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "can't open fd %d", fd);
return NULL;
}
return scap_dump_open_gzfile(handle, f, "", skip_proc_scan);
}
//
// Open a memory "savefile"
//
scap_dumper_t *scap_memory_dump_open(scap_t *handle, uint8_t* targetbuf, uint64_t targetbufsize)
{
scap_dumper_t* res = (scap_dumper_t*)malloc(sizeof(scap_dumper_t));
if(res == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_dump_memory_open memory allocation failure (1)");
return NULL;
}
res->m_f = NULL;
res->m_type = DT_MEM;
res->m_targetbuf = targetbuf;
res->m_targetbufcurpos = targetbuf;
res->m_targetbufend = targetbuf + targetbufsize;
//
// Disable proc parsing since it would be too heavy when saving to memory.
// Before doing that, backup handle->refresh_proc_table_when_saving so we can
// restore whatever the current setting is as soon as we're done.
//
bool tmp_refresh_proc_table_when_saving = handle->refresh_proc_table_when_saving;
handle->refresh_proc_table_when_saving = false;
if(scap_setup_dump(handle, res, "") != SCAP_SUCCESS)
{
free(res);
res = NULL;
}
handle->refresh_proc_table_when_saving = tmp_refresh_proc_table_when_saving;
return res;
}
//
// Close a "savefile" opened with scap_dump_open
//
void scap_dump_close(scap_dumper_t *d)
{
if(d->m_type == DT_FILE)
{
gzclose(d->m_f);
}
free(d);
}
//
// Return the current size of a tracefile
//
int64_t scap_dump_get_offset(scap_dumper_t *d)
{
if(d->m_type == DT_FILE)
{
return gzoffset(d->m_f);
}
else
{
return (int64_t)d->m_targetbufcurpos - (int64_t)d->m_targetbuf;
}
}
int64_t scap_dump_ftell(scap_dumper_t *d)
{
if(d->m_type == DT_FILE)
{
return gztell(d->m_f);
}
else
{
return (int64_t)d->m_targetbufcurpos - (int64_t)d->m_targetbuf;
}
}
void scap_dump_flush(scap_dumper_t *d)
{
if(d->m_type == DT_FILE)
{
gzflush(d->m_f, Z_FULL_FLUSH);
}
}
//
// Tell me how many bytes we will have written if we did.
//
int32_t scap_number_of_bytes_to_write(scap_evt *e, uint16_t cpuid, int32_t *bytes)
{
*bytes = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + e->len + 4);
return SCAP_SUCCESS;
}
//
// Write an event to a dump file
//
int32_t scap_dump(scap_t *handle, scap_dumper_t *d, scap_evt *e, uint16_t cpuid, uint32_t flags)
{
block_header bh;
uint32_t bt;
bool large_payload = flags & SCAP_DF_LARGE;
flags &= ~SCAP_DF_LARGE;
if(flags == 0)
{
//
// Write the section header
//
bh.block_type = large_payload ? EV_BLOCK_TYPE_V2_LARGE : EV_BLOCK_TYPE_V2;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + e->len + 4);
bt = bh.block_total_length;
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) ||
scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) ||
scap_dump_write(d, e, e->len) != e->len ||
scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS ||
scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (6)");
return SCAP_FAILURE;
}
}
else
{
//
// Write the section header
//
bh.block_type = large_payload ? EVF_BLOCK_TYPE_V2_LARGE : EVF_BLOCK_TYPE_V2;
bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + sizeof(flags) + e->len + 4);
bt = bh.block_total_length;
if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) ||
scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) ||
scap_dump_write(d, &flags, sizeof(flags)) != sizeof(flags) ||
scap_dump_write(d, e, e->len) != e->len ||
scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS ||
scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (7)");
return SCAP_FAILURE;
}
}
//
// Enable this to make sure that everything is saved to disk during the tests
//
#if 0
fflush(f);
#endif
return SCAP_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// READ FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Load the machine info block
//
static int32_t scap_read_machine_info(scap_t *handle, scap_reader_t* r, uint32_t block_length)
{
//
// Read the section header block
//
if(scap_reader_read(r, &handle->m_machine_info, sizeof(handle->m_machine_info)) !=
sizeof(handle->m_machine_info))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error reading from file (1)");
return SCAP_FAILURE;
}
return SCAP_SUCCESS;
}
//
// Parse a process list block
//
static int32_t scap_read_proclist(scap_t *handle, scap_reader_t* r, uint32_t block_length, uint32_t block_type)
{
size_t readsize;
size_t subreadsize = 0;
size_t totreadsize = 0;
size_t padding_len;
uint16_t stlen;
uint32_t padding;
int32_t uth_status = SCAP_SUCCESS;
uint32_t toread;
int fseekres;
while(((int32_t)block_length - (int32_t)totreadsize) >= 4)
{
struct scap_threadinfo tinfo;
tinfo.fdlist = NULL;
tinfo.flags = 0;
tinfo.vmsize_kb = 0;
tinfo.vmrss_kb = 0;
tinfo.vmswap_kb = 0;
tinfo.pfmajor = 0;
tinfo.pfminor = 0;
tinfo.env_len = 0;
tinfo.vtid = -1;
tinfo.vpid = -1;
tinfo.cgroups_len = 0;
tinfo.filtered_out = 0;
tinfo.root[0] = 0;
tinfo.sid = -1;
tinfo.vpgid = -1;
tinfo.clone_ts = 0;
tinfo.tty = 0;
tinfo.exepath[0] = 0;
tinfo.loginuid = -1;
tinfo.exe_writable = false;
tinfo.cap_inheritable = 0;
tinfo.cap_permitted = 0;
tinfo.cap_effective = 0;
//
// len
//
uint32_t sub_len = 0;
switch(block_type)
{
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V1_INT:
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V3_INT:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
case PL_BLOCK_TYPE_V6:
case PL_BLOCK_TYPE_V7:
case PL_BLOCK_TYPE_V8:
break;
case PL_BLOCK_TYPE_V9:
readsize = scap_reader_read(r, &(sub_len), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
break;
default:
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted process block type (fd1)");
ASSERT(false);
return SCAP_FAILURE;
}
//
// tid
//
readsize = scap_reader_read(r, &(tinfo.tid), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// pid
//
readsize = scap_reader_read(r, &(tinfo.pid), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// ptid
//
readsize = scap_reader_read(r, &(tinfo.ptid), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
switch(block_type)
{
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V1_INT:
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V3_INT:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
break;
case PL_BLOCK_TYPE_V6:
case PL_BLOCK_TYPE_V7:
case PL_BLOCK_TYPE_V8:
case PL_BLOCK_TYPE_V9:
readsize = scap_reader_read(r, &(tinfo.sid), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
break;
default:
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted process block type (fd1)");
ASSERT(false);
return SCAP_FAILURE;
}
//
// vpgid
//
switch(block_type)
{
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V1_INT:
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V3_INT:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
case PL_BLOCK_TYPE_V6:
case PL_BLOCK_TYPE_V7:
break;
case PL_BLOCK_TYPE_V8:
case PL_BLOCK_TYPE_V9:
readsize = scap_reader_read(r, &(tinfo.vpgid), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
break;
default:
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted process block type (fd1)");
ASSERT(false);
return SCAP_FAILURE;
}
//
// comm
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid commlen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.comm, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.comm[stlen] = 0;
subreadsize += readsize;
//
// exe
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid exelen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.exe, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.exe[stlen] = 0;
subreadsize += readsize;
switch(block_type)
{
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V1_INT:
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V3_INT:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
case PL_BLOCK_TYPE_V6:
break;
case PL_BLOCK_TYPE_V7:
case PL_BLOCK_TYPE_V8:
case PL_BLOCK_TYPE_V9:
//
// exepath
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid exepathlen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.exepath, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.exepath[stlen] = 0;
subreadsize += readsize;
break;
default:
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted process block type (fd1)");
ASSERT(false);
return SCAP_FAILURE;
}
//
// args
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_ARGS_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid argslen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.args, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.args[stlen] = 0;
tinfo.args_len = stlen;
subreadsize += readsize;
//
// cwd
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid cwdlen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.cwd, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.cwd[stlen] = 0;
subreadsize += readsize;
//
// fdlimit
//
readsize = scap_reader_read(r, &(tinfo.fdlimit), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// flags
//
readsize = scap_reader_read(r, &(tinfo.flags), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// uid
//
readsize = scap_reader_read(r, &(tinfo.uid), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// gid
//
readsize = scap_reader_read(r, &(tinfo.gid), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
switch(block_type)
{
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V1_INT:
break;
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V3_INT:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
case PL_BLOCK_TYPE_V6:
case PL_BLOCK_TYPE_V7:
case PL_BLOCK_TYPE_V8:
case PL_BLOCK_TYPE_V9:
//
// vmsize_kb
//
readsize = scap_reader_read(r, &(tinfo.vmsize_kb), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// vmrss_kb
//
readsize = scap_reader_read(r, &(tinfo.vmrss_kb), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// vmswap_kb
//
readsize = scap_reader_read(r, &(tinfo.vmswap_kb), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// pfmajor
//
readsize = scap_reader_read(r, &(tinfo.pfmajor), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// pfminor
//
readsize = scap_reader_read(r, &(tinfo.pfminor), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
if(block_type == PL_BLOCK_TYPE_V3 ||
block_type == PL_BLOCK_TYPE_V3_INT ||
block_type == PL_BLOCK_TYPE_V4 ||
block_type == PL_BLOCK_TYPE_V5 ||
block_type == PL_BLOCK_TYPE_V6 ||
block_type == PL_BLOCK_TYPE_V7 ||
block_type == PL_BLOCK_TYPE_V8 ||
block_type == PL_BLOCK_TYPE_V9)
{
//
// env
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_ENV_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid envlen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.env, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.env[stlen] = 0;
tinfo.env_len = stlen;
subreadsize += readsize;
}
if(block_type == PL_BLOCK_TYPE_V4 ||
block_type == PL_BLOCK_TYPE_V5 ||
block_type == PL_BLOCK_TYPE_V6 ||
block_type == PL_BLOCK_TYPE_V7 ||
block_type == PL_BLOCK_TYPE_V8 ||
block_type == PL_BLOCK_TYPE_V9)
{
//
// vtid
//
readsize = scap_reader_read(r, &(tinfo.vtid), sizeof(int64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// vpid
//
readsize = scap_reader_read(r, &(tinfo.vpid), sizeof(int64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
//
// cgroups
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_CGROUPS_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid cgroupslen %d", stlen);
return SCAP_FAILURE;
}
tinfo.cgroups_len = stlen;
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.cgroups, stlen);
CHECK_READ_SIZE(readsize, stlen);
subreadsize += readsize;
if(block_type == PL_BLOCK_TYPE_V5 ||
block_type == PL_BLOCK_TYPE_V6 ||
block_type == PL_BLOCK_TYPE_V7 ||
block_type == PL_BLOCK_TYPE_V8 ||
block_type == PL_BLOCK_TYPE_V9)
{
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen > SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid rootlen %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, tinfo.root, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
tinfo.root[stlen] = 0;
subreadsize += readsize;
}
}
break;
default:
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted process block type (fd1)");
ASSERT(false);
return SCAP_FAILURE;
}
// If new parameters are added, sub_len can be used to
// see if they are available in the current capture.
// For example, for a 32bit parameter:
//
// if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len)
// {
// ...
// }
//
// loginuid
//
if(sub_len && (subreadsize + sizeof(int32_t)) <= sub_len)
{
readsize = scap_reader_read(r, &(tinfo.loginuid), sizeof(int32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
}
//
// exe_writable
//
if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len)
{
readsize = scap_reader_read(r, &(tinfo.exe_writable), sizeof(uint8_t));
CHECK_READ_SIZE(readsize, sizeof(uint8_t));
subreadsize += readsize;
}
//
// Capabilities
//
if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len)
{
readsize = scap_reader_read(r, &(tinfo.cap_inheritable), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
}
if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len)
{
readsize = scap_reader_read(r, &(tinfo.cap_permitted), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
}
if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len)
{
readsize = scap_reader_read(r, &(tinfo.cap_effective), sizeof(uint64_t));
CHECK_READ_SIZE(readsize, sizeof(uint64_t));
subreadsize += readsize;
}
//
// All parsed. Add the entry to the table, or fire the notification callback
//
if(handle->m_proc_callback == NULL)
{
//
// All parsed. Allocate the new entry and copy the temp one into into it.
//
struct scap_threadinfo *ntinfo = (scap_threadinfo *)malloc(sizeof(scap_threadinfo));
if(ntinfo == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "process table allocation error (fd1)");
return SCAP_FAILURE;
}
// Structure copy
*ntinfo = tinfo;
HASH_ADD_INT64(handle->m_proclist, tid, ntinfo);
if(uth_status != SCAP_SUCCESS)
{
free(ntinfo);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "process table allocation error (fd2)");
return SCAP_FAILURE;
}
}
else
{
handle->m_proc_callback(handle->m_proc_callback_context, handle, tinfo.tid, &tinfo, NULL);
}
if(sub_len && subreadsize != sub_len)
{
if(subreadsize > sub_len)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted input file. Had read %lu bytes, but proclist entry have length %u.",
subreadsize, sub_len);
return SCAP_FAILURE;
}
toread = sub_len - subreadsize;
fseekres = (int)scap_reader_seek(r, (long)toread, SEEK_CUR);
if(fseekres == -1)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip %u bytes.",
(unsigned int)toread);
return SCAP_FAILURE;
}
subreadsize = sub_len;
}
totreadsize += subreadsize;
subreadsize = 0;
}
//
// Read the padding bytes so we properly align to the end of the data
//
if(totreadsize > block_length)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_read_proclist read more %lu than a block %u", totreadsize, block_length);
ASSERT(false);
return SCAP_FAILURE;
}
padding_len = block_length - totreadsize;
readsize = (size_t)scap_reader_read(r, &padding, (unsigned int)padding_len);
CHECK_READ_SIZE(readsize, padding_len);
return SCAP_SUCCESS;
}
//
// Parse an interface list block
//
static int32_t scap_read_iflist(scap_t *handle, scap_reader_t* r, uint32_t block_length, uint32_t block_type)
{
int32_t res = SCAP_SUCCESS;
size_t readsize;
size_t totreadsize;
char *readbuf = NULL;
char *pif;
uint16_t iftype;
uint16_t ifnamlen;
uint32_t toread;
uint32_t entrysize;
uint32_t ifcnt4 = 0;
uint32_t ifcnt6 = 0;
//
// If the list of interfaces was already allocated for this handle (for example because this is
// not the first interface list block), free it
//
if(handle->m_addrlist != NULL)
{
scap_free_iflist(handle->m_addrlist);
handle->m_addrlist = NULL;
}
//
// Bring the block to memory
// We assume that this block is always small enough that we can read it in a single shot
//
readbuf = (char *)malloc(block_length);
if(!readbuf)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_iflist");
return SCAP_FAILURE;
}
readsize = scap_reader_read(r, readbuf, block_length);
CHECK_READ_SIZE_WITH_FREE(readbuf, readsize, block_length);
//
// First pass, count the number of addresses
//
pif = readbuf;
totreadsize = 0;
while(true)
{
toread = (int32_t)block_length - (int32_t)totreadsize;
if(toread < 4)
{
break;
}
if(block_type != IL_BLOCK_TYPE_V2)
{
iftype = *(uint16_t *)pif;
ifnamlen = *(uint16_t *)(pif + 2);
if(iftype == SCAP_II_IPV4)
{
entrysize = sizeof(scap_ifinfo_ipv4) + ifnamlen - SCAP_MAX_PATH_SIZE;
}
else if(iftype == SCAP_II_IPV6)
{
entrysize = sizeof(scap_ifinfo_ipv6) + ifnamlen - SCAP_MAX_PATH_SIZE;
}
else if(iftype == SCAP_II_IPV4_NOLINKSPEED)
{
entrysize = sizeof(scap_ifinfo_ipv4_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE;
}
else if(iftype == SCAP_II_IPV6_NOLINKSPEED)
{
entrysize = sizeof(scap_ifinfo_ipv6_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE;
}
else
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(1)");
ASSERT(false);
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
}
else
{
entrysize = *(uint32_t *)pif + sizeof(uint32_t);
iftype = *(uint16_t *)(pif + 4);
ifnamlen = *(uint16_t *)(pif + 4 + 2);
}
if(toread < entrysize)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(2) toread=%u, entrysize=%u", toread, entrysize);
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
pif += entrysize;
totreadsize += entrysize;
if(iftype == SCAP_II_IPV4 || iftype == SCAP_II_IPV4_NOLINKSPEED)
{
ifcnt4++;
}
else if(iftype == SCAP_II_IPV6 || iftype == SCAP_II_IPV6_NOLINKSPEED)
{
ifcnt6++;
}
else
{
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "unknown interface type %d", (int)iftype);
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
}
//
// Allocate the handle and the arrays
//
handle->m_addrlist = (scap_addrlist *)malloc(sizeof(scap_addrlist));
if(!handle->m_addrlist)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_read_iflist allocation failed(1)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
handle->m_addrlist->n_v4_addrs = 0;
handle->m_addrlist->n_v6_addrs = 0;
handle->m_addrlist->v4list = NULL;
handle->m_addrlist->v6list = NULL;
handle->m_addrlist->totlen = block_length - (ifcnt4 + ifcnt6) * sizeof(uint32_t);
if(ifcnt4 != 0)
{
handle->m_addrlist->v4list = (scap_ifinfo_ipv4 *)malloc(ifcnt4 * sizeof(scap_ifinfo_ipv4));
if(!handle->m_addrlist->v4list)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_read_iflist allocation failed(2)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
}
else
{
handle->m_addrlist->v4list = NULL;
}
if(ifcnt6 != 0)
{
handle->m_addrlist->v6list = (scap_ifinfo_ipv6 *)malloc(ifcnt6 * sizeof(scap_ifinfo_ipv6));
if(!handle->m_addrlist->v6list)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(3)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
}
else
{
handle->m_addrlist->v6list = NULL;
}
handle->m_addrlist->n_v4_addrs = ifcnt4;
handle->m_addrlist->n_v6_addrs = ifcnt6;
//
// Second pass: populate the arrays
//
ifcnt4 = 0;
ifcnt6 = 0;
pif = readbuf;
totreadsize = 0;
while(true)
{
toread = (int32_t)block_length - (int32_t)totreadsize;
entrysize = 0;
if(toread < 4)
{
break;
}
if(block_type == IL_BLOCK_TYPE_V2)
{
entrysize = *(uint32_t *)pif;
totreadsize += sizeof(uint32_t);
pif += sizeof(uint32_t);
}
iftype = *(uint16_t *)pif;
ifnamlen = *(uint16_t *)(pif + 2);
if(ifnamlen >= SCAP_MAX_PATH_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(0)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
// If new parameters are added, entrysize can be used to
// see if they are available in the current capture.
// For example, for a 32bit parameter:
//
// if(entrysize && (ifsize + sizeof(uint32_t)) <= entrysize)
// {
// ifsize += sizeof(uint32_t);
// ...
// }
uint32_t ifsize;
if(iftype == SCAP_II_IPV4)
{
ifsize = sizeof(uint16_t) + // type
sizeof(uint16_t) + // ifnamelen
sizeof(uint32_t) + // addr
sizeof(uint32_t) + // netmask
sizeof(uint32_t) + // bcast
sizeof(uint64_t) + // linkspeed
ifnamlen;
if(toread < ifsize)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(3)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
// Copy the entry
memcpy(handle->m_addrlist->v4list + ifcnt4, pif, ifsize - ifnamlen);
memcpy(handle->m_addrlist->v4list[ifcnt4].ifname, pif + ifsize - ifnamlen, ifnamlen);
// Make sure the name string is NULL-terminated
*((char *)(handle->m_addrlist->v4list + ifcnt4) + ifsize) = 0;
ifcnt4++;
}
else if(iftype == SCAP_II_IPV4_NOLINKSPEED)
{
scap_ifinfo_ipv4_nolinkspeed* src;
scap_ifinfo_ipv4* dst;
ifsize = sizeof(scap_ifinfo_ipv4_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE;
if(toread < ifsize)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(4)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
// Copy the entry
src = (scap_ifinfo_ipv4_nolinkspeed*)pif;
dst = handle->m_addrlist->v4list + ifcnt4;
dst->type = src->type;
dst->ifnamelen = src->ifnamelen;
dst->addr = src->addr;
dst->netmask = src->netmask;
dst->bcast = src->bcast;
dst->linkspeed = 0;
memcpy(dst->ifname, src->ifname, MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1));
// Make sure the name string is NULL-terminated
*((char *)(dst->ifname + MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1))) = 0;
ifcnt4++;
}
else if(iftype == SCAP_II_IPV6)
{
ifsize = sizeof(uint16_t) + // type
sizeof(uint16_t) + // ifnamelen
SCAP_IPV6_ADDR_LEN + // addr
SCAP_IPV6_ADDR_LEN + // netmask
SCAP_IPV6_ADDR_LEN + // bcast
sizeof(uint64_t) + // linkspeed
ifnamlen;
if(toread < ifsize)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(5)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
// Copy the entry
memcpy(handle->m_addrlist->v6list + ifcnt6, pif, ifsize - ifnamlen);
memcpy(handle->m_addrlist->v6list[ifcnt6].ifname, pif + ifsize - ifnamlen, ifnamlen);
// Make sure the name string is NULL-terminated
*((char *)(handle->m_addrlist->v6list + ifcnt6) + ifsize) = 0;
ifcnt6++;
}
else if(iftype == SCAP_II_IPV6_NOLINKSPEED)
{
scap_ifinfo_ipv6_nolinkspeed* src;
scap_ifinfo_ipv6* dst;
ifsize = sizeof(scap_ifinfo_ipv6_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE;
if(toread < ifsize)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(6)");
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
// Copy the entry
src = (scap_ifinfo_ipv6_nolinkspeed*)pif;
dst = handle->m_addrlist->v6list + ifcnt6;
dst->type = src->type;
dst->ifnamelen = src->ifnamelen;
memcpy(dst->addr, src->addr, SCAP_IPV6_ADDR_LEN);
memcpy(dst->netmask, src->netmask, SCAP_IPV6_ADDR_LEN);
memcpy(dst->bcast, src->bcast, SCAP_IPV6_ADDR_LEN);
dst->linkspeed = 0;
memcpy(dst->ifname, src->ifname, MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1));
// Make sure the name string is NULL-terminated
*((char *)(dst->ifname + MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1))) = 0;
ifcnt6++;
}
else
{
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "unknown interface type %d", (int)iftype);
res = SCAP_FAILURE;
goto scap_read_iflist_error;
}
entrysize = entrysize ? entrysize : ifsize;
pif += entrysize;
totreadsize += entrysize;
}
//
// Release the read storage
//
free(readbuf);
return res;
scap_read_iflist_error:
scap_free_iflist(handle->m_addrlist);
handle->m_addrlist = NULL;
if(readbuf)
{
free(readbuf);
}
return res;
}
//
// Parse a user list block
//
static int32_t scap_read_userlist(scap_t *handle, scap_reader_t* r, uint32_t block_length, uint32_t block_type)
{
size_t readsize;
size_t totreadsize = 0;
size_t subreadsize = 0;
size_t padding_len;
uint32_t padding;
uint8_t type;
uint16_t stlen;
uint32_t toread;
int fseekres;
//
// If the list of users was already allocated for this handle (for example because this is
// not the first interface list block), free it
//
if(handle->m_userlist != NULL)
{
scap_free_userlist(handle->m_userlist);
handle->m_userlist = NULL;
}
//
// Allocate and initialize the handle info
//
handle->m_userlist = (scap_userlist*)malloc(sizeof(scap_userlist));
if(handle->m_userlist == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(2)");
return SCAP_FAILURE;
}
handle->m_userlist->nusers = 0;
handle->m_userlist->ngroups = 0;
handle->m_userlist->totsavelen = 0;
handle->m_userlist->users = NULL;
handle->m_userlist->groups = NULL;
//
// Import the blocks
//
while(((int32_t)block_length - (int32_t)totreadsize) >= 4)
{
uint32_t sub_len = 0;
if(block_type == UL_BLOCK_TYPE_V2)
{
//
// len
//
readsize = scap_reader_read(r, &(sub_len), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
}
//
// type
//
readsize = scap_reader_read(r, &(type), sizeof(type));
CHECK_READ_SIZE(readsize, sizeof(type));
subreadsize += readsize;
if(type == USERBLOCK_TYPE_USER)
{
scap_userinfo* puser;
handle->m_userlist->nusers++;
handle->m_userlist->users = (scap_userinfo*)realloc(handle->m_userlist->users, handle->m_userlist->nusers * sizeof(scap_userinfo));
if(handle->m_userlist->users == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_userlist(1)");
return SCAP_FAILURE;
}
puser = &handle->m_userlist->users[handle->m_userlist->nusers -1];
//
// uid
//
readsize = scap_reader_read(r, &(puser->uid), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// gid
//
readsize = scap_reader_read(r, &(puser->gid), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// name
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen >= MAX_CREDENTIALS_STR_LEN)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid user name len %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, puser->name, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
puser->name[stlen] = 0;
subreadsize += readsize;
//
// homedir
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen >= MAX_CREDENTIALS_STR_LEN)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid user homedir len %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, puser->homedir, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
puser->homedir[stlen] = 0;
subreadsize += readsize;
//
// shell
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen >= MAX_CREDENTIALS_STR_LEN)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid user shell len %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, puser->shell, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
puser->shell[stlen] = 0;
subreadsize += readsize;
// If new parameters are added, sub_len can be used to
// see if they are available in the current capture.
// For example, for a 32bit parameter:
//
// if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len)
// {
// ...
// }
}
else
{
scap_groupinfo* pgroup;
handle->m_userlist->ngroups++;
handle->m_userlist->groups = (scap_groupinfo*)realloc(handle->m_userlist->groups, handle->m_userlist->ngroups * sizeof(scap_groupinfo));
if(handle->m_userlist->groups == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_userlist(2)");
return SCAP_FAILURE;
}
pgroup = &handle->m_userlist->groups[handle->m_userlist->ngroups -1];
//
// gid
//
readsize = scap_reader_read(r, &(pgroup->gid), sizeof(uint32_t));
CHECK_READ_SIZE(readsize, sizeof(uint32_t));
subreadsize += readsize;
//
// name
//
readsize = scap_reader_read(r, &(stlen), sizeof(uint16_t));
CHECK_READ_SIZE(readsize, sizeof(uint16_t));
if(stlen >= MAX_CREDENTIALS_STR_LEN)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid group name len %d", stlen);
return SCAP_FAILURE;
}
subreadsize += readsize;
readsize = scap_reader_read(r, pgroup->name, stlen);
CHECK_READ_SIZE(readsize, stlen);
// the string is not null-terminated on file
pgroup->name[stlen] = 0;
subreadsize += readsize;
// If new parameters are added, sub_len can be used to
// see if they are available in the current capture.
// For example, for a 32bit parameter:
//
// if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len)
// {
// ...
// }
}
if(sub_len && subreadsize != sub_len)
{
if(subreadsize > sub_len)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted input file. Had read %lu bytes, but userlist entry have length %u.",
subreadsize, sub_len);
return SCAP_FAILURE;
}
toread = sub_len - subreadsize;
fseekres = (int)scap_reader_seek(r, (long)toread, SEEK_CUR);
if(fseekres == -1)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip %u bytes.",
(unsigned int)toread);
return SCAP_FAILURE;
}
subreadsize = sub_len;
}
totreadsize += subreadsize;
subreadsize = 0;
}
//
// Read the padding bytes so we properly align to the end of the data
//
if(totreadsize > block_length)
{
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_read_userlist read more %lu than a block %u", totreadsize, block_length);
return SCAP_FAILURE;
}
padding_len = block_length - totreadsize;
readsize = scap_reader_read(r, &padding, (unsigned int)padding_len);
CHECK_READ_SIZE(readsize, padding_len);
return SCAP_SUCCESS;
}
//
// Parse a process list block
//
static int32_t scap_read_fdlist(scap_t *handle, scap_reader_t* r, uint32_t block_length, uint32_t block_type)
{
size_t readsize;
size_t totreadsize = 0;
size_t padding_len;
struct scap_threadinfo *tinfo;
scap_fdinfo fdi;
scap_fdinfo *nfdi;
// uint16_t stlen;
uint64_t tid;
int32_t uth_status = SCAP_SUCCESS;
uint32_t padding;
//
// Read the tid
//
readsize = scap_reader_read(r, &tid, sizeof(tid));
CHECK_READ_SIZE(readsize, sizeof(tid));
totreadsize += readsize;
if(handle->m_proc_callback == NULL)
{
//
// Identify the process descriptor
//
HASH_FIND_INT64(handle->m_proclist, &tid, tinfo);
if(tinfo == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted trace file. FD block references TID %"PRIu64", which doesn't exist.",
tid);
return SCAP_FAILURE;
}
}
else
{
tinfo = NULL;
}
while(((int32_t)block_length - (int32_t)totreadsize) >= 4)
{
if(scap_fd_read_from_disk(handle, &fdi, &readsize, block_type, r) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
totreadsize += readsize;
//
// Add the entry to the table, or fire the notification callback
//
if(handle->m_proc_callback == NULL)
{
//
// Parsed successfully. Allocate the new entry and copy the temp one into into it.
//
nfdi = (scap_fdinfo *)malloc(sizeof(scap_fdinfo));
if(nfdi == NULL)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "process table allocation error (fd1)");
return SCAP_FAILURE;
}
// Structure copy
*nfdi = fdi;
ASSERT(tinfo != NULL);
HASH_ADD_INT64(tinfo->fdlist, fd, nfdi);
if(uth_status != SCAP_SUCCESS)
{
free(nfdi);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "process table allocation error (fd2)");
return SCAP_FAILURE;
}
}
else
{
ASSERT(tinfo == NULL);
handle->m_proc_callback(handle->m_proc_callback_context, handle, tid, NULL, &fdi);
}
}
//
// Read the padding bytes so we properly align to the end of the data
//
if(totreadsize > block_length)
{
ASSERT(false);
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_read_fdlist read more %lu than a block %u", totreadsize, block_length);
return SCAP_FAILURE;
}
padding_len = block_length - totreadsize;
readsize = scap_reader_read(r, &padding, (unsigned int)padding_len);
CHECK_READ_SIZE(readsize, padding_len);
return SCAP_SUCCESS;
}
int32_t scap_read_section_header(scap_t *handle, scap_reader_t* r)
{
section_header_block sh;
uint32_t bt;
//
// Read the section header block
//
if(scap_reader_read(r, &sh, sizeof(sh)) != sizeof(sh) ||
scap_reader_read(r, &bt, sizeof(bt)) != sizeof(bt))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error reading from file (1)");
return SCAP_FAILURE;
}
if(sh.byte_order_magic != 0x1a2b3c4d)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid magic number");
return SCAP_FAILURE;
}
if(sh.major_version > CURRENT_MAJOR_VERSION)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE,
"cannot correctly parse the capture. Upgrade your version.");
return SCAP_VERSION_MISMATCH;
}
return SCAP_SUCCESS;
}
//
// Parse the headers of a trace file and load the tables
//
int32_t scap_read_init(scap_t *handle, scap_reader_t* r)
{
block_header bh;
uint32_t bt;
size_t readsize;
size_t toread;
int fseekres;
int32_t rc;
int8_t found_ev = 0;
//
// Read the section header block
//
if(scap_reader_read(r, &bh, sizeof(bh)) != sizeof(bh))
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error reading from file (1)");
return SCAP_FAILURE;
}
if(bh.block_type != SHB_BLOCK_TYPE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid block type");
return SCAP_FAILURE;
}
if((rc = scap_read_section_header(handle, r)) != SCAP_SUCCESS)
{
return rc;
}
//
// Read the metadata blocks (processes, FDs, etc.)
//
while(true)
{
readsize = scap_reader_read(r, &bh, sizeof(bh));
//
// If we don't find the event block header,
// it means there is no event in the file.
//
if (readsize == 0 && !found_ev)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "no events in file");
return SCAP_FAILURE;
}
CHECK_READ_SIZE(readsize, sizeof(bh));
switch(bh.block_type)
{
case MI_BLOCK_TYPE:
case MI_BLOCK_TYPE_INT:
if(scap_read_machine_info(handle, r, bh.block_total_length - sizeof(block_header) - 4) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
break;
case PL_BLOCK_TYPE_V1:
case PL_BLOCK_TYPE_V2:
case PL_BLOCK_TYPE_V3:
case PL_BLOCK_TYPE_V4:
case PL_BLOCK_TYPE_V5:
case PL_BLOCK_TYPE_V6:
case PL_BLOCK_TYPE_V7:
case PL_BLOCK_TYPE_V8:
case PL_BLOCK_TYPE_V9:
case PL_BLOCK_TYPE_V1_INT:
case PL_BLOCK_TYPE_V2_INT:
case PL_BLOCK_TYPE_V3_INT:
if(scap_read_proclist(handle, r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
break;
case FDL_BLOCK_TYPE:
case FDL_BLOCK_TYPE_INT:
case FDL_BLOCK_TYPE_V2:
if(scap_read_fdlist(handle, r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
break;
case EV_BLOCK_TYPE:
case EV_BLOCK_TYPE_INT:
case EV_BLOCK_TYPE_V2:
case EVF_BLOCK_TYPE:
case EVF_BLOCK_TYPE_V2:
case EV_BLOCK_TYPE_V2_LARGE:
case EVF_BLOCK_TYPE_V2_LARGE:
found_ev = 1;
//
// We're done with the metadata headers. Rewind the file position so we are aligned to start reading the events.
//
fseekres = scap_reader_seek(r, (long)0 - sizeof(bh), SEEK_CUR);
if(fseekres != -1)
{
break;
}
else
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error seeking in file");
return SCAP_FAILURE;
}
case IL_BLOCK_TYPE:
case IL_BLOCK_TYPE_INT:
case IL_BLOCK_TYPE_V2:
if(scap_read_iflist(handle, r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
break;
case UL_BLOCK_TYPE:
case UL_BLOCK_TYPE_INT:
case UL_BLOCK_TYPE_V2:
if(scap_read_userlist(handle, r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type) != SCAP_SUCCESS)
{
return SCAP_FAILURE;
}
break;
default:
//
// Unknown block type. Skip the block.
//
toread = bh.block_total_length - sizeof(block_header) - 4;
fseekres = (int)scap_reader_seek(r, (long)toread, SEEK_CUR);
if(fseekres == -1)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip block of type %x and size %u.",
(int)bh.block_type,
(unsigned int)toread);
return SCAP_FAILURE;
}
break;
}
if(found_ev)
{
break;
}
//
// Read and validate the trailer
//
readsize = scap_reader_read(r, &bt, sizeof(bt));
CHECK_READ_SIZE(readsize, sizeof(bt));
if(bt != bh.block_total_length)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "wrong block total length, header=%u, trailer=%u",
bh.block_total_length,
bt);
return SCAP_FAILURE;
}
}
//
// NOTE: can't require a user list block, interface list block, or machine info block
// any longer--with the introduction of source plugins, it is legitimate to have
// trace files that don't contain those blocks
//
return SCAP_SUCCESS;
}
//
// Read an event from disk
//
int32_t scap_next_offline(scap_t *handle, OUT scap_evt **pevent, OUT uint16_t *pcpuid)
{
block_header bh;
size_t readsize;
uint32_t readlen;
size_t hdr_len;
scap_reader_t* r = handle->m_reader;
ASSERT(r != NULL);
//
// We may have to repeat the whole process
// if the capture contains new syscalls
//
while(true)
{
//
// Read the block header
//
readsize = scap_reader_read(r, &bh, sizeof(bh));
if(readsize != sizeof(bh))
{
int err_no = 0;
#ifdef WIN32
const char* err_str = "read error";
#else
const char* err_str = scap_reader_error(r, &err_no);
#endif
if(err_no)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error reading file: %s, ernum=%d", err_str, err_no);
return SCAP_FAILURE;
}
if(readsize == 0)
{
//
// We read exactly 0 bytes. This indicates a correct end of file.
//
return SCAP_EOF;
}
else
{
CHECK_READ_SIZE(readsize, sizeof(bh));
}
}
if(bh.block_type != EV_BLOCK_TYPE &&
bh.block_type != EV_BLOCK_TYPE_V2 &&
bh.block_type != EV_BLOCK_TYPE_V2_LARGE &&
bh.block_type != EV_BLOCK_TYPE_INT &&
bh.block_type != EVF_BLOCK_TYPE &&
bh.block_type != EVF_BLOCK_TYPE_V2 &&
bh.block_type != EVF_BLOCK_TYPE_V2_LARGE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "unexpected block type %u", (uint32_t)bh.block_type);
handle->m_unexpected_block_readsize = readsize;
return SCAP_UNEXPECTED_BLOCK;
}
hdr_len = sizeof(struct ppm_evt_hdr);
if(bh.block_type != EV_BLOCK_TYPE_V2 &&
bh.block_type != EV_BLOCK_TYPE_V2_LARGE &&
bh.block_type != EVF_BLOCK_TYPE_V2 &&
bh.block_type != EVF_BLOCK_TYPE_V2_LARGE)
{
hdr_len -= 4;
}
if(bh.block_total_length < sizeof(bh) + hdr_len + 4)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "block length too short %u", (uint32_t)bh.block_total_length);
return SCAP_FAILURE;
}
//
// Read the event
//
readlen = bh.block_total_length - sizeof(bh);
// Non-large block types have an uint16_max maximum size
if (bh.block_type != EV_BLOCK_TYPE_V2_LARGE && bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) {
if(readlen > READER_BUF_SIZE) {
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "event block length %u greater than NON-LARGE read buffer size %u",
readlen,
READER_BUF_SIZE);
return SCAP_FAILURE;
}
} else if (readlen > handle->m_reader_evt_buf_size) {
// Try to allocate a buffer large enough
char *tmp = realloc(handle->m_reader_evt_buf, readlen);
if (!tmp) {
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "event block length %u greater than read buffer size %zu",
readlen,
handle->m_reader_evt_buf_size);
return SCAP_FAILURE;
}
handle->m_reader_evt_buf = tmp;
handle->m_reader_evt_buf_size = readlen;
}
readsize = scap_reader_read(r, handle->m_reader_evt_buf, readlen);
CHECK_READ_SIZE(readsize, readlen);
//
// EVF_BLOCK_TYPE has 32 bits of flags
//
*pcpuid = *(uint16_t *)handle->m_reader_evt_buf;
if(bh.block_type == EVF_BLOCK_TYPE || bh.block_type == EVF_BLOCK_TYPE_V2 || bh.block_type == EVF_BLOCK_TYPE_V2_LARGE)
{
handle->m_last_evt_dump_flags = *(uint32_t*)(handle->m_reader_evt_buf + sizeof(uint16_t));
*pevent = (struct ppm_evt_hdr *)(handle->m_reader_evt_buf + sizeof(uint16_t) + sizeof(uint32_t));
}
else
{
handle->m_last_evt_dump_flags = 0;
*pevent = (struct ppm_evt_hdr *)(handle->m_reader_evt_buf + sizeof(uint16_t));
}
if((*pevent)->type >= PPM_EVENT_MAX)
{
//
// We're reading a capture that contains new syscalls.
// We can't do anything else that skips them.
//
continue;
}
if(bh.block_type != EV_BLOCK_TYPE_V2 &&
bh.block_type != EV_BLOCK_TYPE_V2_LARGE &&
bh.block_type != EVF_BLOCK_TYPE_V2 &&
bh.block_type != EVF_BLOCK_TYPE_V2_LARGE)
{
//
// We're reading an old capture whose events don't have nparams in the header.
// Convert it to the current version.
//
if((readlen + sizeof(uint32_t)) > READER_BUF_SIZE)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (%lu greater than read buffer size %u)",
readlen + sizeof(uint32_t),
READER_BUF_SIZE);
return SCAP_FAILURE;
}
memmove((char *)*pevent + sizeof(struct ppm_evt_hdr),
(char *)*pevent + sizeof(struct ppm_evt_hdr) - sizeof(uint32_t),
readlen - ((char *)*pevent - handle->m_reader_evt_buf) - (sizeof(struct ppm_evt_hdr) - sizeof(uint32_t)));
(*pevent)->len += sizeof(uint32_t);
// In old captures, the length of PPME_NOTIFICATION_E and PPME_INFRASTRUCTURE_EVENT_E
// is not correct. Adjust it, otherwise the following code will never find a match
if((*pevent)->type == PPME_NOTIFICATION_E || (*pevent)->type == PPME_INFRASTRUCTURE_EVENT_E)
{
(*pevent)->len -= 3;
}
//
// The number of parameters needs to be calculated based on the block len.
// Use the current number of parameters as starting point and decrease it
// until size matches.
//
char *end = (char *)*pevent + (*pevent)->len;
uint16_t *lens = (uint16_t *)((char *)*pevent + sizeof(struct ppm_evt_hdr));
uint32_t nparams;
bool done = false;
for(nparams = g_event_info[(*pevent)->type].nparams; (int)nparams >= 0; nparams--)
{
char *valptr = (char *)lens + nparams * sizeof(uint16_t);
if(valptr > end)
{
continue;
}
uint32_t i;
for(i = 0; i < nparams; i++)
{
valptr += lens[i];
}
if(valptr < end)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (corrupted trace file - can't calculate nparams).");
return SCAP_FAILURE;
}
ASSERT(valptr >= end);
if(valptr == end)
{
done = true;
break;
}
}
if(!done)
{
snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (corrupted trace file - can't calculate nparams) (2).");
return SCAP_FAILURE;
}
(*pevent)->nparams = nparams;
}
break;
}
return SCAP_SUCCESS;
}
uint64_t scap_ftell(scap_t *handle)
{
return scap_reader_tell(handle->m_reader);
}
void scap_fseek(scap_t *handle, uint64_t off)
{
switch (scap_reader_type(handle->m_reader))
{
case RT_FILE:
scap_reader_seek(handle->m_reader, off, SEEK_SET);
return;
default:
ASSERT(false);
return;
}
}
|
229546.c | /*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/objects.h>
#include <openssl/err.h>
#include <openssl/ts.h>
#include <openssl/pkcs7.h>
/* Function definitions. */
int TS_RESP_set_status_info(TS_RESP *a, TS_STATUS_INFO *status_info)
{
TS_STATUS_INFO *new_status_info;
if (a->status_info == status_info)
return 1;
new_status_info = TS_STATUS_INFO_dup(status_info);
if (new_status_info == NULL) {
TSerr(TS_F_TS_RESP_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
return 0;
}
TS_STATUS_INFO_free(a->status_info);
a->status_info = new_status_info;
return 1;
}
TS_STATUS_INFO *TS_RESP_get_status_info(TS_RESP *a)
{
return a->status_info;
}
/* Caller loses ownership of PKCS7 and TS_TST_INFO objects. */
void TS_RESP_set_tst_info(TS_RESP *a, PKCS7 *p7, TS_TST_INFO *tst_info)
{
/* Set new PKCS7 and TST_INFO objects. */
PKCS7_free(a->token);
a->token = p7;
TS_TST_INFO_free(a->tst_info);
a->tst_info = tst_info;
}
PKCS7 *TS_RESP_get_token(TS_RESP *a)
{
return a->token;
}
TS_TST_INFO *TS_RESP_get_tst_info(TS_RESP *a)
{
return a->tst_info;
}
int TS_TST_INFO_set_version(TS_TST_INFO *a, long version)
{
return ASN1_INTEGER_set(a->version, version);
}
long TS_TST_INFO_get_version(const TS_TST_INFO *a)
{
return ASN1_INTEGER_get(a->version);
}
int TS_TST_INFO_set_policy_id(TS_TST_INFO *a, ASN1_OBJECT *policy)
{
ASN1_OBJECT *new_policy;
if (a->policy_id == policy)
return 1;
new_policy = OBJ_dup(policy);
if (new_policy == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_POLICY_ID, ERR_R_MALLOC_FAILURE);
return 0;
}
ASN1_OBJECT_free(a->policy_id);
a->policy_id = new_policy;
return 1;
}
ASN1_OBJECT *TS_TST_INFO_get_policy_id(TS_TST_INFO *a)
{
return a->policy_id;
}
int TS_TST_INFO_set_msg_imprint(TS_TST_INFO *a, TS_MSG_IMPRINT *msg_imprint)
{
TS_MSG_IMPRINT *new_msg_imprint;
if (a->msg_imprint == msg_imprint)
return 1;
new_msg_imprint = TS_MSG_IMPRINT_dup(msg_imprint);
if (new_msg_imprint == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_MSG_IMPRINT, ERR_R_MALLOC_FAILURE);
return 0;
}
TS_MSG_IMPRINT_free(a->msg_imprint);
a->msg_imprint = new_msg_imprint;
return 1;
}
TS_MSG_IMPRINT *TS_TST_INFO_get_msg_imprint(TS_TST_INFO *a)
{
return a->msg_imprint;
}
int TS_TST_INFO_set_serial(TS_TST_INFO *a, const ASN1_INTEGER *serial)
{
ASN1_INTEGER *new_serial;
if (a->serial == serial)
return 1;
new_serial = ASN1_INTEGER_dup(serial);
if (new_serial == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_SERIAL, ERR_R_MALLOC_FAILURE);
return 0;
}
ASN1_INTEGER_free(a->serial);
a->serial = new_serial;
return 1;
}
const ASN1_INTEGER *TS_TST_INFO_get_serial(const TS_TST_INFO *a)
{
return a->serial;
}
int TS_TST_INFO_set_time(TS_TST_INFO *a, const ASN1_GENERALIZEDTIME *gtime)
{
ASN1_GENERALIZEDTIME *new_time;
if (a->time == gtime)
return 1;
new_time = ASN1_STRING_dup(gtime);
if (new_time == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_TIME, ERR_R_MALLOC_FAILURE);
return 0;
}
ASN1_GENERALIZEDTIME_free(a->time);
a->time = new_time;
return 1;
}
const ASN1_GENERALIZEDTIME *TS_TST_INFO_get_time(const TS_TST_INFO *a)
{
return a->time;
}
int TS_TST_INFO_set_accuracy(TS_TST_INFO *a, TS_ACCURACY *accuracy)
{
TS_ACCURACY *new_accuracy;
if (a->accuracy == accuracy)
return 1;
new_accuracy = TS_ACCURACY_dup(accuracy);
if (new_accuracy == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_ACCURACY, ERR_R_MALLOC_FAILURE);
return 0;
}
TS_ACCURACY_free(a->accuracy);
a->accuracy = new_accuracy;
return 1;
}
TS_ACCURACY *TS_TST_INFO_get_accuracy(TS_TST_INFO *a)
{
return a->accuracy;
}
int TS_ACCURACY_set_seconds(TS_ACCURACY *a, const ASN1_INTEGER *seconds)
{
ASN1_INTEGER *new_seconds;
if (a->seconds == seconds)
return 1;
new_seconds = ASN1_INTEGER_dup(seconds);
if (new_seconds == NULL) {
TSerr(TS_F_TS_ACCURACY_SET_SECONDS, ERR_R_MALLOC_FAILURE);
return 0;
}
ASN1_INTEGER_free(a->seconds);
a->seconds = new_seconds;
return 1;
}
const ASN1_INTEGER *TS_ACCURACY_get_seconds(const TS_ACCURACY *a)
{
return a->seconds;
}
int TS_ACCURACY_set_millis(TS_ACCURACY *a, const ASN1_INTEGER *millis)
{
ASN1_INTEGER *new_millis = NULL;
if (a->millis == millis)
return 1;
if (millis != NULL) {
new_millis = ASN1_INTEGER_dup(millis);
if (new_millis == NULL) {
TSerr(TS_F_TS_ACCURACY_SET_MILLIS,
ERR_R_MALLOC_FAILURE);
return 0;
}
}
ASN1_INTEGER_free(a->millis);
a->millis = new_millis;
return 1;
}
const ASN1_INTEGER *TS_ACCURACY_get_millis(const TS_ACCURACY *a)
{
return a->millis;
}
int TS_ACCURACY_set_micros(TS_ACCURACY *a, const ASN1_INTEGER *micros)
{
ASN1_INTEGER *new_micros = NULL;
if (a->micros == micros)
return 1;
if (micros != NULL) {
new_micros = ASN1_INTEGER_dup(micros);
if (new_micros == NULL) {
TSerr(TS_F_TS_ACCURACY_SET_MICROS,
ERR_R_MALLOC_FAILURE);
return 0;
}
}
ASN1_INTEGER_free(a->micros);
a->micros = new_micros;
return 1;
}
const ASN1_INTEGER *TS_ACCURACY_get_micros(const TS_ACCURACY *a)
{
return a->micros;
}
int TS_TST_INFO_set_ordering(TS_TST_INFO *a, int ordering)
{
a->ordering = ordering ? 0xFF : 0x00;
return 1;
}
int TS_TST_INFO_get_ordering(const TS_TST_INFO *a)
{
return a->ordering ? 1 : 0;
}
int TS_TST_INFO_set_nonce(TS_TST_INFO *a, const ASN1_INTEGER *nonce)
{
ASN1_INTEGER *new_nonce;
if (a->nonce == nonce)
return 1;
new_nonce = ASN1_INTEGER_dup(nonce);
if (new_nonce == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_NONCE, ERR_R_MALLOC_FAILURE);
return 0;
}
ASN1_INTEGER_free(a->nonce);
a->nonce = new_nonce;
return 1;
}
const ASN1_INTEGER *TS_TST_INFO_get_nonce(const TS_TST_INFO *a)
{
return a->nonce;
}
int TS_TST_INFO_set_tsa(TS_TST_INFO *a, GENERAL_NAME *tsa)
{
GENERAL_NAME *new_tsa;
if (a->tsa == tsa)
return 1;
new_tsa = GENERAL_NAME_dup(tsa);
if (new_tsa == NULL) {
TSerr(TS_F_TS_TST_INFO_SET_TSA, ERR_R_MALLOC_FAILURE);
return 0;
}
GENERAL_NAME_free(a->tsa);
a->tsa = new_tsa;
return 1;
}
GENERAL_NAME *TS_TST_INFO_get_tsa(TS_TST_INFO *a)
{
return a->tsa;
}
STACK_OF(X509_EXTENSION) *TS_TST_INFO_get_exts(TS_TST_INFO *a)
{
return a->extensions;
}
void TS_TST_INFO_ext_free(TS_TST_INFO *a)
{
if (!a)
return;
sk_X509_EXTENSION_pop_free(a->extensions, X509_EXTENSION_free);
a->extensions = NULL;
}
int TS_TST_INFO_get_ext_count(TS_TST_INFO *a)
{
return X509v3_get_ext_count(a->extensions);
}
int TS_TST_INFO_get_ext_by_NID(TS_TST_INFO *a, int nid, int lastpos)
{
return X509v3_get_ext_by_NID(a->extensions, nid, lastpos);
}
int TS_TST_INFO_get_ext_by_OBJ(TS_TST_INFO *a, ASN1_OBJECT *obj, int lastpos)
{
return X509v3_get_ext_by_OBJ(a->extensions, obj, lastpos);
}
int TS_TST_INFO_get_ext_by_critical(TS_TST_INFO *a, int crit, int lastpos)
{
return X509v3_get_ext_by_critical(a->extensions, crit, lastpos);
}
X509_EXTENSION *TS_TST_INFO_get_ext(TS_TST_INFO *a, int loc)
{
return X509v3_get_ext(a->extensions, loc);
}
X509_EXTENSION *TS_TST_INFO_delete_ext(TS_TST_INFO *a, int loc)
{
return X509v3_delete_ext(a->extensions, loc);
}
int TS_TST_INFO_add_ext(TS_TST_INFO *a, X509_EXTENSION *ex, int loc)
{
return X509v3_add_ext(&a->extensions, ex, loc) != NULL;
}
void *TS_TST_INFO_get_ext_d2i(TS_TST_INFO *a, int nid, int *crit, int *idx)
{
return X509V3_get_d2i(a->extensions, nid, crit, idx);
}
|
9467.c | // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"
#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_defs.h"
#include "esp_bt_main.h"
#include "esp_bt_main.h"
#include "example_ble_sec_gatts_demo.h"
#define GATTS_TABLE_TAG "SEC_GATTS_DEMO"
#define HEART_PROFILE_NUM 1
#define HEART_PROFILE_APP_IDX 0
#define ESP_HEART_RATE_APP_ID 0x55
#define EXCAMPLE_DEVICE_NAME "ESP_BLE_SECURITY"
#define HEART_RATE_SVC_INST_ID 0
#define GATTS_DEMO_CHAR_VAL_LEN_MAX 0x40
#define ADV_CONFIG_FLAG (1 << 0)
#define SCAN_RSP_CONFIG_FLAG (1 << 1)
static uint8_t adv_config_done = 0;
uint8_t heart_str[] = {0x11,0x22,0x33};
uint16_t heart_rate_handle_table[HRS_IDX_NB];
esp_attr_value_t gatts_demo_char1_val =
{
.attr_max_len = GATTS_DEMO_CHAR_VAL_LEN_MAX,
.attr_len = sizeof(heart_str),
.attr_value = heart_str,
};
static uint8_t test_manufacturer[3]={'E', 'S', 'P'};
static uint8_t sec_service_uuid[16] = {
/* LSB <--------------------------------------------------------------------------------> MSB */
//first uuid, 16bit, [12],[13] is the value
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x18, 0x0D, 0x00, 0x00,
};
// config adv data
static esp_ble_adv_data_t heart_rate_adv_config = {
.set_scan_rsp = false,
.include_txpower = true,
.min_interval = 0x100,
.max_interval = 0x100,
.appearance = 0x00,
.manufacturer_len = 0, //TEST_MANUFACTURER_DATA_LEN,
.p_manufacturer_data = NULL, //&test_manufacturer[0],
.service_data_len = 0,
.p_service_data = NULL,
.service_uuid_len = sizeof(sec_service_uuid),
.p_service_uuid = sec_service_uuid,
.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};
// config scan response data
static esp_ble_adv_data_t heart_rate_scan_rsp_config = {
.set_scan_rsp = true,
.include_name = true,
.manufacturer_len = sizeof(test_manufacturer),
.p_manufacturer_data = test_manufacturer,
};
static esp_ble_adv_params_t heart_rate_adv_params = {
.adv_int_min = 0x100,
.adv_int_max = 0x100,
.adv_type = ADV_TYPE_IND,
.own_addr_type = BLE_ADDR_TYPE_RANDOM,
.channel_map = ADV_CHNL_ALL,
.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};
struct gatts_profile_inst {
esp_gatts_cb_t gatts_cb;
uint16_t gatts_if;
uint16_t app_id;
uint16_t conn_id;
uint16_t service_handle;
esp_gatt_srvc_id_t service_id;
uint16_t char_handle;
esp_bt_uuid_t char_uuid;
esp_gatt_perm_t perm;
esp_gatt_char_prop_t property;
uint16_t descr_handle;
esp_bt_uuid_t descr_uuid;
};
static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
/* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
static struct gatts_profile_inst heart_rate_profile_tab[HEART_PROFILE_NUM] = {
[HEART_PROFILE_APP_IDX] = {
.gatts_cb = gatts_profile_event_handler,
.gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
},
};
/*
* Heart Rate PROFILE ATTRIBUTES
****************************************************************************************
*/
/// Heart Rate Sensor Service
static const uint16_t heart_rate_svc = ESP_GATT_UUID_HEALTH_THERMOM_SVC;
#define CHAR_DECLARATION_SIZE (sizeof(uint8_t))
static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE;
static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE;
static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG;
static const uint8_t char_prop_notify = ESP_GATT_CHAR_PROP_BIT_NOTIFY;
static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ;
static const uint8_t char_prop_read_write = ESP_GATT_CHAR_PROP_BIT_WRITE|ESP_GATT_CHAR_PROP_BIT_READ;
/// Heart Rate Sensor Service - Heart Rate Measurement Characteristic, notify
static const uint16_t heart_rate_meas_uuid = ESP_GATT_HEART_RATE_MEAS;
static const uint8_t heart_measurement_ccc[2] ={ 0x00, 0x00};
/// Heart Rate Sensor Service -Body Sensor Location characteristic, read
static const uint16_t body_sensor_location_uuid = ESP_GATT_BODY_SENSOR_LOCATION;
static const uint8_t body_sensor_loc_val[1] = {0x00};
/// Heart Rate Sensor Service - Heart Rate Control Point characteristic, write&read
static const uint16_t heart_rate_ctrl_point = ESP_GATT_HEART_RATE_CNTL_POINT;
static const uint8_t heart_ctrl_point[1] = {0x00};
/// Full HRS Database Description - Used to add attributes into the database
static const esp_gatts_attr_db_t heart_rate_gatt_db[HRS_IDX_NB] =
{
// Heart Rate Service Declaration
[HRS_IDX_SVC] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ,
sizeof(uint16_t), sizeof(heart_rate_svc), (uint8_t *)&heart_rate_svc}},
// Heart Rate Measurement Characteristic Declaration
[HRS_IDX_HR_MEAS_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_notify}},
// Heart Rate Measurement Characteristic Value
[HRS_IDX_HR_MEAS_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_meas_uuid, ESP_GATT_PERM_READ,
HRPS_HT_MEAS_MAX_LEN,0, NULL}},
// Heart Rate Measurement Characteristic - Client Characteristic Configuration Descriptor
[HRS_IDX_HR_MEAS_NTF_CFG] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ|ESP_GATT_PERM_WRITE,
sizeof(uint16_t),sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},
// Body Sensor Location Characteristic Declaration
[HRS_IDX_BOBY_SENSOR_LOC_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read}},
// Body Sensor Location Characteristic Value
[HRS_IDX_BOBY_SENSOR_LOC_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&body_sensor_location_uuid, ESP_GATT_PERM_READ_ENCRYPTED,
sizeof(uint8_t), sizeof(body_sensor_loc_val), (uint8_t *)body_sensor_loc_val}},
// Heart Rate Control Point Characteristic Declaration
[HRS_IDX_HR_CTNL_PT_CHAR] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read_write}},
// Heart Rate Control Point Characteristic Value
[HRS_IDX_HR_CTNL_PT_VAL] =
{{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_ctrl_point, ESP_GATT_PERM_WRITE_ENCRYPTED|ESP_GATT_PERM_READ_ENCRYPTED,
sizeof(uint8_t), sizeof(heart_ctrl_point), (uint8_t *)heart_ctrl_point}},
};
static char *esp_key_type_to_str(esp_ble_key_type_t key_type)
{
char *key_str = NULL;
switch(key_type) {
case ESP_LE_KEY_NONE:
key_str = "ESP_LE_KEY_NONE";
break;
case ESP_LE_KEY_PENC:
key_str = "ESP_LE_KEY_PENC";
break;
case ESP_LE_KEY_PID:
key_str = "ESP_LE_KEY_PID";
break;
case ESP_LE_KEY_PCSRK:
key_str = "ESP_LE_KEY_PCSRK";
break;
case ESP_LE_KEY_PLK:
key_str = "ESP_LE_KEY_PLK";
break;
case ESP_LE_KEY_LLK:
key_str = "ESP_LE_KEY_LLK";
break;
case ESP_LE_KEY_LENC:
key_str = "ESP_LE_KEY_LENC";
break;
case ESP_LE_KEY_LID:
key_str = "ESP_LE_KEY_LID";
break;
case ESP_LE_KEY_LCSRK:
key_str = "ESP_LE_KEY_LCSRK";
break;
default:
key_str = "INVALID BLE KEY TYPE";
break;
}
return key_str;
}
static void show_bonded_devices(void)
{
int dev_num = esp_ble_get_bond_device_num();
esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num);
esp_ble_get_bond_device_list(&dev_num, dev_list);
ESP_LOGI(GATTS_TABLE_TAG, "Bonded devices number : %d\n", dev_num);
ESP_LOGI(GATTS_TABLE_TAG, "Bonded devices list : %d\n", dev_num);
for (int i = 0; i < dev_num; i++) {
esp_log_buffer_hex(GATTS_TABLE_TAG, (void *)dev_list[i].bd_addr, sizeof(esp_bd_addr_t));
}
free(dev_list);
}
static void __attribute__((unused)) remove_all_bonded_devices(void)
{
int dev_num = esp_ble_get_bond_device_num();
esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num);
esp_ble_get_bond_device_list(&dev_num, dev_list);
for (int i = 0; i < dev_num; i++) {
esp_ble_remove_bond_device(dev_list[i].bd_addr);
}
free(dev_list);
}
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
ESP_LOGV(GATTS_TABLE_TAG, "GAP_EVT, event %d\n", event);
switch (event) {
case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT:
adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
if (adv_config_done == 0){
esp_ble_gap_start_advertising(&heart_rate_adv_params);
}
break;
case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
adv_config_done &= (~ADV_CONFIG_FLAG);
if (adv_config_done == 0){
esp_ble_gap_start_advertising(&heart_rate_adv_params);
}
break;
case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
//advertising start complete event to indicate advertising start successfully or failed
if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
ESP_LOGE(GATTS_TABLE_TAG, "advertising start failed, error status = %x", param->adv_start_cmpl.status);
break;
}
ESP_LOGI(GATTS_TABLE_TAG, "advertising start success");
break;
case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_PASSKEY_REQ_EVT");
//esp_ble_passkey_reply(heart_rate_profile_tab[HEART_PROFILE_APP_IDX].remote_bda, true, 0x00);
break;
case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_OOB_REQ_EVT");
break;
case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_LOCAL_IR_EVT");
break;
case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_LOCAL_ER_EVT");
break;
case ESP_GAP_BLE_NC_REQ_EVT:
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_NC_REQ_EVT");
break;
case ESP_GAP_BLE_SEC_REQ_EVT:
/* send the positive(true) security response to the peer device to accept the security request.
If not accept the security request, should sent the security response with negative(false) accept value*/
esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
break;
case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: ///the app will receive this evt when the IO has Output capability and the peer device IO has Input capability.
///show the passkey number to the user to input it in the peer deivce.
ESP_LOGE(GATTS_TABLE_TAG, "The passkey Notify number:%d", param->ble_security.key_notif.passkey);
break;
case ESP_GAP_BLE_KEY_EVT:
//shows the ble key info share with peer device to the user.
ESP_LOGI(GATTS_TABLE_TAG, "key type = %s", esp_key_type_to_str(param->ble_security.ble_key.key_type));
break;
case ESP_GAP_BLE_AUTH_CMPL_EVT: {
esp_bd_addr_t bd_addr;
memcpy(bd_addr, param->ble_security.auth_cmpl.bd_addr, sizeof(esp_bd_addr_t));
ESP_LOGI(GATTS_TABLE_TAG, "remote BD_ADDR: %08x%04x",\
(bd_addr[0] << 24) + (bd_addr[1] << 16) + (bd_addr[2] << 8) + bd_addr[3],
(bd_addr[4] << 8) + bd_addr[5]);
ESP_LOGI(GATTS_TABLE_TAG, "address type = %d", param->ble_security.auth_cmpl.addr_type);
ESP_LOGI(GATTS_TABLE_TAG, "pair status = %s",param->ble_security.auth_cmpl.success ? "success" : "fail");
show_bonded_devices();
break;
}
case ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT: {
ESP_LOGD(GATTS_TABLE_TAG, "ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT status = %d", param->remove_bond_dev_cmpl.status);
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GAP_BLE_REMOVE_BOND_DEV");
ESP_LOGI(GATTS_TABLE_TAG, "-----ESP_GAP_BLE_REMOVE_BOND_DEV----");
esp_log_buffer_hex(GATTS_TABLE_TAG, (void *)param->remove_bond_dev_cmpl.bd_addr, sizeof(esp_bd_addr_t));
ESP_LOGI(GATTS_TABLE_TAG, "------------------------------------");
break;
}
case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT:
if (param->local_privacy_cmpl.status != ESP_BT_STATUS_SUCCESS){
ESP_LOGE(GATTS_TABLE_TAG, "config local privacy failed, error status = %x", param->local_privacy_cmpl.status);
break;
}
esp_err_t ret = esp_ble_gap_config_adv_data(&heart_rate_adv_config);
if (ret){
ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret);
}else{
adv_config_done |= ADV_CONFIG_FLAG;
}
ret = esp_ble_gap_config_adv_data(&heart_rate_scan_rsp_config);
if (ret){
ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret);
}else{
adv_config_done |= SCAN_RSP_CONFIG_FLAG;
}
break;
default:
break;
}
}
static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
ESP_LOGV(GATTS_TABLE_TAG, "event = %x\n",event);
switch (event) {
case ESP_GATTS_REG_EVT:
esp_ble_gap_set_device_name(EXCAMPLE_DEVICE_NAME);
//generate a resolvable random address
esp_ble_gap_config_local_privacy(true);
esp_ble_gatts_create_attr_tab(heart_rate_gatt_db, gatts_if,
HRS_IDX_NB, HEART_RATE_SVC_INST_ID);
break;
case ESP_GATTS_READ_EVT:
break;
case ESP_GATTS_WRITE_EVT:
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_WRITE_EVT, write value:");
esp_log_buffer_hex(GATTS_TABLE_TAG, param->write.value, param->write.len);
break;
case ESP_GATTS_EXEC_WRITE_EVT:
break;
case ESP_GATTS_MTU_EVT:
break;
case ESP_GATTS_CONF_EVT:
break;
case ESP_GATTS_UNREG_EVT:
break;
case ESP_GATTS_DELETE_EVT:
break;
case ESP_GATTS_START_EVT:
break;
case ESP_GATTS_STOP_EVT:
break;
case ESP_GATTS_CONNECT_EVT:
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_CONNECT_EVT");
/* start security connect with peer device when receive the connect event sent by the master */
esp_ble_set_encryption(param->connect.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM);
break;
case ESP_GATTS_DISCONNECT_EVT:
ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_DISCONNECT_EVT");
/* start advertising again when missing the connect */
esp_ble_gap_start_advertising(&heart_rate_adv_params);
break;
case ESP_GATTS_OPEN_EVT:
break;
case ESP_GATTS_CANCEL_OPEN_EVT:
break;
case ESP_GATTS_CLOSE_EVT:
break;
case ESP_GATTS_LISTEN_EVT:
break;
case ESP_GATTS_CONGEST_EVT:
break;
case ESP_GATTS_CREAT_ATTR_TAB_EVT: {
ESP_LOGI(GATTS_TABLE_TAG, "The number handle = %x",param->add_attr_tab.num_handle);
if (param->create.status == ESP_GATT_OK){
if(param->add_attr_tab.num_handle == HRS_IDX_NB) {
memcpy(heart_rate_handle_table, param->add_attr_tab.handles,
sizeof(heart_rate_handle_table));
esp_ble_gatts_start_service(heart_rate_handle_table[HRS_IDX_SVC]);
}else{
ESP_LOGE(GATTS_TABLE_TAG, "Create attribute table abnormally, num_handle (%d) doesn't equal to HRS_IDX_NB(%d)",
param->add_attr_tab.num_handle, HRS_IDX_NB);
}
}else{
ESP_LOGE(GATTS_TABLE_TAG, " Create attribute table failed, error code = %x", param->create.status);
}
break;
}
default:
break;
}
}
static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param)
{
/* If event is register event, store the gatts_if for each profile */
if (event == ESP_GATTS_REG_EVT) {
if (param->reg.status == ESP_GATT_OK) {
heart_rate_profile_tab[HEART_PROFILE_APP_IDX].gatts_if = gatts_if;
} else {
ESP_LOGI(GATTS_TABLE_TAG, "Reg app failed, app_id %04x, status %d\n",
param->reg.app_id,
param->reg.status);
return;
}
}
do {
int idx;
for (idx = 0; idx < HEART_PROFILE_NUM; idx++) {
if (gatts_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
gatts_if == heart_rate_profile_tab[idx].gatts_if) {
if (heart_rate_profile_tab[idx].gatts_cb) {
heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param);
}
}
}
} while (0);
}
void app_main()
{
esp_err_t ret;
// Initialize NVS.
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ret = esp_bt_controller_init(&bt_cfg);
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s init controller failed", __func__);
return;
}
ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM);
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s enable controller failed", __func__);
return;
}
ESP_LOGI(GATTS_TABLE_TAG, "%s init bluetooth", __func__);
ret = esp_bluedroid_init();
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s init bluetooth failed", __func__);
return;
}
ret = esp_bluedroid_enable();
if (ret) {
ESP_LOGE(GATTS_TABLE_TAG, "%s enable bluetooth failed", __func__);
return;
}
ret = esp_ble_gatts_register_callback(gatts_event_handler);
if (ret){
ESP_LOGE(GATTS_TABLE_TAG, "gatts register error, error code = %x", ret);
return;
}
ret = esp_ble_gap_register_callback(gap_event_handler);
if (ret){
ESP_LOGE(GATTS_TABLE_TAG, "gap register error, error code = %x", ret);
return;
}
ret = esp_ble_gatts_app_register(ESP_HEART_RATE_APP_ID);
if (ret){
ESP_LOGE(GATTS_TABLE_TAG, "gatts app register error, error code = %x", ret);
return;
}
/* set the security iocap & auth_req & key size & init key response key parameters to the stack*/
esp_ble_auth_req_t auth_req = ESP_LE_AUTH_BOND; //bonding with peer device after authentication
esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; //set the IO capability to No output No input
uint8_t key_size = 16; //the key size should be 7~16 bytes
uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));
esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
/* If your BLE device act as a Slave, the init_key means you hope which types of key of the master should distribut to you,
and the response key means which key you can distribut to the Master;
If your BLE device act as a master, the response key means you hope which types of key of the slave should distribut to you,
and the init key means which key you can distribut to the slave. */
esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t));
esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));
/* Just show how to clear all the bonded devices
* Delay 30s, clear all the bonded devices
*
* vTaskDelay(30000 / portTICK_PERIOD_MS);
* remove_all_bonded_devices();
*/
}
|
741759.c | /* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CNIOBoringSSL_md4.h>
#include <stdlib.h>
#include <string.h>
#include "../../internal.h"
#include "../digest/md32_common.h"
uint8_t *MD4(const uint8_t *data, size_t len, uint8_t out[MD4_DIGEST_LENGTH]) {
MD4_CTX ctx;
MD4_Init(&ctx);
MD4_Update(&ctx, data, len);
MD4_Final(out, &ctx);
return out;
}
// Implemented from RFC1186 The MD4 Message-Digest Algorithm.
int MD4_Init(MD4_CTX *md4) {
OPENSSL_memset(md4, 0, sizeof(MD4_CTX));
md4->h[0] = 0x67452301UL;
md4->h[1] = 0xefcdab89UL;
md4->h[2] = 0x98badcfeUL;
md4->h[3] = 0x10325476UL;
return 1;
}
void md4_block_data_order(uint32_t *state, const uint8_t *data, size_t num);
void MD4_Transform(MD4_CTX *c, const uint8_t data[MD4_CBLOCK]) {
md4_block_data_order(c->h, data, 1);
}
int MD4_Update(MD4_CTX *c, const void *data, size_t len) {
crypto_md32_update(&md4_block_data_order, c->h, c->data, MD4_CBLOCK, &c->num,
&c->Nh, &c->Nl, data, len);
return 1;
}
int MD4_Final(uint8_t out[MD4_DIGEST_LENGTH], MD4_CTX *c) {
crypto_md32_final(&md4_block_data_order, c->h, c->data, MD4_CBLOCK, &c->num,
c->Nh, c->Nl, /*is_big_endian=*/0);
CRYPTO_store_u32_le(out, c->h[0]);
CRYPTO_store_u32_le(out + 4, c->h[1]);
CRYPTO_store_u32_le(out + 8, c->h[2]);
CRYPTO_store_u32_le(out + 12, c->h[3]);
return 1;
}
// As pointed out by Wei Dai <[email protected]>, the above can be
// simplified to the code below. Wei attributes these optimizations
// to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
#define F(b, c, d) ((((c) ^ (d)) & (b)) ^ (d))
#define G(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
#define H(b, c, d) ((b) ^ (c) ^ (d))
#define ROTATE(a, n) (((a) << (n)) | ((a) >> (32 - (n))))
#define R0(a, b, c, d, k, s, t) \
do { \
(a) += ((k) + (t) + F((b), (c), (d))); \
(a) = ROTATE(a, s); \
} while (0)
#define R1(a, b, c, d, k, s, t) \
do { \
(a) += ((k) + (t) + G((b), (c), (d))); \
(a) = ROTATE(a, s); \
} while (0)
#define R2(a, b, c, d, k, s, t) \
do { \
(a) += ((k) + (t) + H((b), (c), (d))); \
(a) = ROTATE(a, s); \
} while (0)
void md4_block_data_order(uint32_t *state, const uint8_t *data, size_t num) {
uint32_t A, B, C, D;
uint32_t X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15;
A = state[0];
B = state[1];
C = state[2];
D = state[3];
for (; num--;) {
X0 = CRYPTO_load_u32_le(data);
data += 4;
X1 = CRYPTO_load_u32_le(data);
data += 4;
// Round 0
R0(A, B, C, D, X0, 3, 0);
X2 = CRYPTO_load_u32_le(data);
data += 4;
R0(D, A, B, C, X1, 7, 0);
X3 = CRYPTO_load_u32_le(data);
data += 4;
R0(C, D, A, B, X2, 11, 0);
X4 = CRYPTO_load_u32_le(data);
data += 4;
R0(B, C, D, A, X3, 19, 0);
X5 = CRYPTO_load_u32_le(data);
data += 4;
R0(A, B, C, D, X4, 3, 0);
X6 = CRYPTO_load_u32_le(data);
data += 4;
R0(D, A, B, C, X5, 7, 0);
X7 = CRYPTO_load_u32_le(data);
data += 4;
R0(C, D, A, B, X6, 11, 0);
X8 = CRYPTO_load_u32_le(data);
data += 4;
R0(B, C, D, A, X7, 19, 0);
X9 = CRYPTO_load_u32_le(data);
data += 4;
R0(A, B, C, D, X8, 3, 0);
X10 = CRYPTO_load_u32_le(data);
data += 4;
R0(D, A, B, C, X9, 7, 0);
X11 = CRYPTO_load_u32_le(data);
data += 4;
R0(C, D, A, B, X10, 11, 0);
X12 = CRYPTO_load_u32_le(data);
data += 4;
R0(B, C, D, A, X11, 19, 0);
X13 = CRYPTO_load_u32_le(data);
data += 4;
R0(A, B, C, D, X12, 3, 0);
X14 = CRYPTO_load_u32_le(data);
data += 4;
R0(D, A, B, C, X13, 7, 0);
X15 = CRYPTO_load_u32_le(data);
data += 4;
R0(C, D, A, B, X14, 11, 0);
R0(B, C, D, A, X15, 19, 0);
// Round 1
R1(A, B, C, D, X0, 3, 0x5A827999L);
R1(D, A, B, C, X4, 5, 0x5A827999L);
R1(C, D, A, B, X8, 9, 0x5A827999L);
R1(B, C, D, A, X12, 13, 0x5A827999L);
R1(A, B, C, D, X1, 3, 0x5A827999L);
R1(D, A, B, C, X5, 5, 0x5A827999L);
R1(C, D, A, B, X9, 9, 0x5A827999L);
R1(B, C, D, A, X13, 13, 0x5A827999L);
R1(A, B, C, D, X2, 3, 0x5A827999L);
R1(D, A, B, C, X6, 5, 0x5A827999L);
R1(C, D, A, B, X10, 9, 0x5A827999L);
R1(B, C, D, A, X14, 13, 0x5A827999L);
R1(A, B, C, D, X3, 3, 0x5A827999L);
R1(D, A, B, C, X7, 5, 0x5A827999L);
R1(C, D, A, B, X11, 9, 0x5A827999L);
R1(B, C, D, A, X15, 13, 0x5A827999L);
// Round 2
R2(A, B, C, D, X0, 3, 0x6ED9EBA1L);
R2(D, A, B, C, X8, 9, 0x6ED9EBA1L);
R2(C, D, A, B, X4, 11, 0x6ED9EBA1L);
R2(B, C, D, A, X12, 15, 0x6ED9EBA1L);
R2(A, B, C, D, X2, 3, 0x6ED9EBA1L);
R2(D, A, B, C, X10, 9, 0x6ED9EBA1L);
R2(C, D, A, B, X6, 11, 0x6ED9EBA1L);
R2(B, C, D, A, X14, 15, 0x6ED9EBA1L);
R2(A, B, C, D, X1, 3, 0x6ED9EBA1L);
R2(D, A, B, C, X9, 9, 0x6ED9EBA1L);
R2(C, D, A, B, X5, 11, 0x6ED9EBA1L);
R2(B, C, D, A, X13, 15, 0x6ED9EBA1L);
R2(A, B, C, D, X3, 3, 0x6ED9EBA1L);
R2(D, A, B, C, X11, 9, 0x6ED9EBA1L);
R2(C, D, A, B, X7, 11, 0x6ED9EBA1L);
R2(B, C, D, A, X15, 15, 0x6ED9EBA1L);
A = state[0] += A;
B = state[1] += B;
C = state[2] += C;
D = state[3] += D;
}
}
#undef F
#undef G
#undef H
#undef ROTATE
#undef R0
#undef R1
#undef R2
|
180227.c | /*******************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
#include "device.h"
#include "plib_clk.h"
/*********************************************************************************
Initialize Main Clock (MAINCK)
*********************************************************************************/
static void CLK_MainClockInitialize(void)
{
/* Enable Main Crystal Oscillator */
PMC_REGS->CKGR_MOR = (PMC_REGS->CKGR_MOR & ~CKGR_MOR_MOSCXTST_Msk) | CKGR_MOR_KEY_PASSWD | CKGR_MOR_MOSCXTST(255) | CKGR_MOR_MOSCXTEN_Msk;
/* Wait until the main oscillator clock is ready */
while ( (PMC_REGS->PMC_SR & PMC_SR_MOSCXTS_Msk) != PMC_SR_MOSCXTS_Msk);
/* Main Crystal Oscillator is selected as the Main Clock (MAINCK) source.
Switch Main Clock (MAINCK) to Main Crystal Oscillator clock */
PMC_REGS->CKGR_MOR|= CKGR_MOR_KEY_PASSWD | CKGR_MOR_MOSCSEL_Msk;
/* Wait until MAINCK is switched to Main Crystal Oscillator */
while ( (PMC_REGS->PMC_SR & PMC_SR_MOSCSELS_Msk) != PMC_SR_MOSCSELS_Msk);
/* Enable the RC Oscillator */
PMC_REGS->CKGR_MOR|= CKGR_MOR_KEY_PASSWD | CKGR_MOR_MOSCRCEN_Msk;
/* Wait until the RC oscillator clock is ready. */
while( (PMC_REGS->PMC_SR & PMC_SR_MOSCRCS_Msk) != PMC_SR_MOSCRCS_Msk);
/* Configure the RC Oscillator frequency */
PMC_REGS->CKGR_MOR = (PMC_REGS->CKGR_MOR & ~CKGR_MOR_MOSCRCF_Msk) | CKGR_MOR_KEY_PASSWD | CKGR_MOR_MOSCRCF_12_MHz;
/* Wait until the RC oscillator clock is ready */
while( (PMC_REGS->PMC_SR& PMC_SR_MOSCRCS_Msk) != PMC_SR_MOSCRCS_Msk);
}
/*********************************************************************************
Initialize PLLA (PLLACK)
*********************************************************************************/
static void CLK_PLLAInitialize(void)
{
/* Configure and Enable PLLA */
PMC_REGS->CKGR_PLLAR = CKGR_PLLAR_ONE_Msk | CKGR_PLLAR_PLLACOUNT(0x3f) |
CKGR_PLLAR_MULA(25 - 1) |
CKGR_PLLAR_DIVA(1);
while ( (PMC_REGS->PMC_SR & PMC_SR_LOCKA_Msk) != PMC_SR_LOCKA_Msk);
}
/*********************************************************************************
Initialize UTMI PLL (UPLLCK)
*********************************************************************************/
static void CLK_UTMIPLLInitialize(void)
{
/* Configure Crystal Clock Frequency (12MHz or 16MHz) to select USB PLL (UPLL) multiplication factor
UPLL multiplication factor is x40 to generate 480MHz from 12MHz
UPLL multiplication factor is x30 to generate 480MHz from 16MHz */
UTMI_REGS->UTMI_CKTRIM= UTMI_CKTRIM_FREQ_XTAL12;
/* Enable UPLL and configure UPLL lock time */
PMC_REGS->CKGR_UCKR = CKGR_UCKR_UPLLEN_Msk | CKGR_UCKR_UPLLCOUNT(0x3F);
/* Wait until PLL Lock occurs */
while ((PMC_REGS->PMC_SR & PMC_SR_LOCKU_Msk) != PMC_SR_LOCKU_Msk);
/* UPLL clock frequency is 480MHz (Divider=1) */
PMC_REGS->PMC_MCKR &= (~PMC_MCKR_UPLLDIV2_Msk);
/* Wait until clock is ready */
while ( (PMC_REGS->PMC_SR & PMC_SR_MCKRDY_Msk) != PMC_SR_MCKRDY_Msk);
}
/*********************************************************************************
Initialize Master clock (MCK)
*********************************************************************************/
static void CLK_MasterClockInitialize(void)
{
/* Program PMC_MCKR.PRES and wait for PMC_SR.MCKRDY to be set */
PMC_REGS->PMC_MCKR = (PMC_REGS->PMC_MCKR & ~PMC_MCKR_PRES_Msk) | PMC_MCKR_PRES_CLK_1;
while ((PMC_REGS->PMC_SR & PMC_SR_MCKRDY_Msk) != PMC_SR_MCKRDY_Msk);
/* Program PMC_MCKR.MDIV and Wait for PMC_SR.MCKRDY to be set */
PMC_REGS->PMC_MCKR = (PMC_REGS->PMC_MCKR & ~PMC_MCKR_MDIV_Msk) | PMC_MCKR_MDIV_PCK_DIV2;
while ((PMC_REGS->PMC_SR & PMC_SR_MCKRDY_Msk) != PMC_SR_MCKRDY_Msk);
/* Program PMC_MCKR.CSS and Wait for PMC_SR.MCKRDY to be set */
PMC_REGS->PMC_MCKR = (PMC_REGS->PMC_MCKR & ~PMC_MCKR_CSS_Msk) | PMC_MCKR_CSS_PLLA_CLK;
while ((PMC_REGS->PMC_SR & PMC_SR_MCKRDY_Msk) != PMC_SR_MCKRDY_Msk);
}
/*********************************************************************************
Initialize USB FS clock
*********************************************************************************/
static void CLK_USBClockInitialize ( void )
{
/* Configure Full-Speed USB Clock source and Clock Divider */
PMC_REGS->PMC_USB = PMC_USB_USBDIV(9) | PMC_USB_USBS_Msk;
/* Enable Full-Speed USB Clock Output */
PMC_REGS->PMC_SCER = PMC_SCER_USBCLK_Msk;
}
/*********************************************************************************
Clock Initialize
*********************************************************************************/
void CLOCK_Initialize( void )
{
/* Initialize Main Clock */
CLK_MainClockInitialize();
/* Initialize PLLA */
CLK_PLLAInitialize();
/* Initialize UTMI PLL */
CLK_UTMIPLLInitialize();
/* Initialize Master Clock */
CLK_MasterClockInitialize();
/* Initialize USB Clock */
CLK_USBClockInitialize();
/* Enable Peripheral Clock */
PMC_REGS->PMC_PCER0=0x831c00;
PMC_REGS->PMC_PCER1=0x4;
}
|
874435.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awindham <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/28 22:45:49 by awindham #+# #+# */
/* Updated: 2018/12/01 18:39:25 by awindham ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
char *ft_strcpy(char *dst, const char *src)
{
size_t i;
i = 0;
while ((dst[i] = src[i]))
i++;
return (dst);
}
|
767397.c | /* sqUnixX11.c -- support for display via the X Window System.
*
* Copyright (C) 1996-2008 by Ian Piumarta and other authors/contributors
* listed elsewhere in this file.
* All rights reserved.
*
* This file is part of Unix Squeak.
*
* 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.
*/
/* Author: Ian Piumarta <[email protected]>
*
* Support for more intelligent CLIPBOARD selection handling contributed by:
* Ned Konz <[email protected]>
*
* Support for displays deeper than 8 bits contributed by: Kazuki YASUMATSU
* <[email protected]> <[email protected]>
*
* Support for cursor and keypad editing keys based on code contributed by:
* Stefan Matthias Aust <[email protected]>
*
* Support for intelligent visual class selection contributed by:
* Bill Cattey <[email protected]>
*
* Support for European accented characters in selections, and
* Support for displays shallower than 8 bits contributed, and
* Support for browser plugins, and
* Support for accelerated OpenGL contributed by:
* Bert Freudenberg <[email protected]>
*
* Support for 24bpp TrueColour X display devices contributed by:
* Tim Rowledge <[email protected]>
*
* Support for OSProcess plugin contributed by:
* Dave Lewis <[email protected]> Mon Oct 18 20:36:54 EDT 1999
*/
#include "sq.h"
#include "sqMemoryAccess.h"
#include "sqUnixMain.h"
#include "sqUnixGlobals.h"
#include "sqUnixCharConv.h"
#include "sqaio.h"
#undef HAVE_OPENGL_GL_H /* don't include Quartz OpenGL if configured */
#include "SqDisplay.h"
#if defined(ENABLE_FAST_BLT)
/* XXX referring to plugin variables *requires* BitBitPlugin to be included by VMM as an internal plugin */
# if defined(__arm__)
# include "../../../Cross/plugins/BitBltPlugin/BitBltArm.h"
# else
# error configuration error
# endif
#endif
#if defined(ioMSecs)
# undef ioMSecs
#endif
#define NO_ICON
#define PRINT_PS_FORMS
#define SQ_FORM_FILENAME "squeak-form.ppm"
#undef FULL_UPDATE_ON_EXPOSE
#if 0 /* The following is a pain. Leave it to the command line. */
# undef DEBUG_FOCUS
# undef DEBUG_XIM
# undef DEBUG_CONV
# undef DEBUG_EVENTS
# undef DEBUG_SELECTIONS
# undef DEBUG_BROWSER
# undef DEBUG_WINDOW
# undef DEBUG_VISUAL
#endif
#define USE_XICFONT_OPTION
#undef USE_XICFONT_RESOURCE
#undef USE_XICFONT_DEFAULT
#if defined(HAVE_LIBXEXT)
# define USE_XSHM
#endif
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <locale.h>
#if defined(HAVE_SYS_SELECT_H)
# include <sys/select.h>
#endif
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#define XK_MISCELLANY
#define XK_XKB_KEYS
#include <X11/keysym.h> /* /not/ keysymdef.h */
#if defined(SUGAR)
# include <X11/XF86keysym.h>
#endif
#if defined(USE_XSHM)
# include <sys/ipc.h>
# include <sys/shm.h>
# include <X11/extensions/XShm.h>
#endif
#if defined(HAVE_LIBXRENDER)
# include <X11/extensions/Xrender.h>
#endif
#if !defined(NO_ICON)
# include "squeakIcon.bitmap"
#endif
#if defined(HAVE_DLFCN_H)
# include <dlfcn.h>
#endif
#include <assert.h>
#define isAligned(T, V) (((V) % sizeof(T)) == 0)
#define align(T, V) (((V) / sizeof(T)) * sizeof(T))
/*** Variables -- Imported from Virtual Machine ***/
/*** Variables -- X11 Related ***/
/* name of Squeak windows in Xrm and the WM */
#ifdef PharoVM
# define xResClass "pharo-vm"
# define xResName "Pharo"
#else
# define xResClass "Squeak"
# define xResName "squeak"
#endif
# define VMOPTION(arg) "-"arg
char *displayName= 0; /* name of display, or 0 for $DISPLAY */
Display *stDisplay= null; /* Squeak display */
int isConnectedToXServer=0;/* True when connected to an X server */
int stXfd= -1; /* X connection file descriptor */
Window stParent= null; /* Squeak parent window */
Window stWindow= null; /* Squeak window */
int stWidth= 0;
int stHeight= 0;
int xWidth= 0;
int xHeight= 0;
Visual *stVisual; /* the default visual */
GC stGC; /* graphics context used for rendering */
Colormap stColormap= null; /* Squeak color map */
int scrW= 0;
int scrH= 0;
XImage *stImage= 0; /* ...and it's client-side pixmap */
char *stEmptySelection= ""; /* immutable "empty string" value */
char *stPrimarySelection; /* buffer holding selection */
int stPrimarySelectionSize;/* size of buffer holding selection */
int stOwnsSelection= 0; /* true if we own the X selection */
int stOwnsClipboard= 0; /* true if we own the X clipboard */
int usePrimaryFirst= 0; /* true if we should look to PRIMARY before CLIPBOARD */
Time stSelectionTime; /* Time of setting the selection */
Atom stSelectionName= None; /* None or XdndSelection */
Atom stSelectionType= None; /* type to send selection (multiple types should be supported) */
XColor stColorBlack; /* black pixel value in stColormap */
XColor stColorWhite; /* white pixel value in stColormap */
int savedWindowOrigin= -1; /* initial origin of window */
#define SELECTION_ATOM_COUNT 10
/* http://www.freedesktop.org/standards/clipboards-spec/clipboards.txt */
Atom selectionAtoms[SELECTION_ATOM_COUNT];
char *selectionAtomNames[SELECTION_ATOM_COUNT]= {
"CLIPBOARD",
#define xaClipboard selectionAtoms[0]
"CUT_BUFFER0",
#define xaCutBuffer0 selectionAtoms[1]
"TARGETS",
#define xaTargets selectionAtoms[2]
"MULTIPLE",
#define xaMultiple selectionAtoms[3]
"UTF8_STRING",
#define xaUTF8String selectionAtoms[4]
"COMPOUND_TEXT",
#define xaCompoundText selectionAtoms[5]
"TIMESTAMP",
#define xaTimestamp selectionAtoms[6]
"SQUEAK_SELECTION", /* used for XGetSelectionOwner() data */
#define selectionAtom selectionAtoms[7]
"INCR",
#define xaINCR selectionAtoms[8]
"XdndSelection",
#define xaXdndSelection selectionAtoms[9]
};
Atom wmProtocolsAtom; /* for window deletion messages */
Atom wmDeleteWindowAtom;
#if defined(USE_XSHM)
XShmSegmentInfo stShmInfo; /* shared memory descriptor */
int completions= 0; /* outstanding completion events */
int completionType; /* the type of XShmCompletionEvent */
int useXshm= 0; /* 1 if shared memory is in use */
int asyncUpdate= 0; /* 1 for asynchronous screen updates */
#endif
int mapDelBs= 0; /* 1 to map delete to backspace */
int optMapIndex= 0; /* Option key modifier map index */
int cmdMapIndex= 0; /* Command key modifier map index */
int stDepth= 0;
int stBitsPerPixel= 0;
unsigned int stColors[256];
unsigned int stDownGradingColors[256];
int stHasSameRGBMask16;
int stHasSameRGBMask32;
int stRNMask, stGNMask, stBNMask;
int stRShift, stGShift, stBShift;
char *stDisplayBitmap= 0;
Window browserWindow= 0; /* parent window */
int browserPipes[]= {-1, -1}; /* read/write fd for browser communication */
int headless= 0;
int useXdnd= 1; /* true if we should handle XDND protocol messages */
#if defined(SUGAR)
char *sugarBundleId= 0;
char *sugarActivityId= 0;
#endif
typedef int (*x2sqKey_t)(XKeyEvent *xevt, KeySym *symbolic);
static int x2sqKeyPlain(XKeyEvent *xevt, KeySym *symbolic);
static int x2sqKeyInput(XKeyEvent *xevt, KeySym *symbolic);
static int x2sqKeyCompositionInput(XKeyEvent *xevt, KeySym *symbolic);
static x2sqKey_t x2sqKey= x2sqKeyPlain;
static int multi_key_pressed = 0;
static KeySym multi_key_buffer = 0;
static int compositionInput = 0;
/* #define INIT_INPUT_WHEN_KEY_PRESSED */
/* #define INIT_INPUT_WHEN_FOCUSED_IN */
/* #define INIT_INPUT_WHEN_MAPPED */
#if defined(INIT_INPUT_WHEN_KEY_PRESSED)
# undef INIT_INPUT_WHEN_FOCUSED_IN
# undef INIT_INPUT_WHEN_MAPPED
#elif defined(INIT_INPUT_WHEN_FOCUSED_IN)
# undef INIT_INPUT_WHEN_MAPPED
#elif !defined(INIT_INPUT_WHEN_MAPPED)
# define INIT_INPUT_WHEN_MAPPED
#endif
#if defined(USE_XICFONT_RESOURCE)
# include <X11/Xresource.h>
# define xicFontResClass "XIC.FontSet"
# define xicFontResName "xic.fontSet"
#elif defined(USE_XICFONT_DEFAULT)
# define xicFontDefRes "fontSet"
#endif
#define xicDefaultFont "-*-*-medium-r-normal--*"
#if defined(USE_XICFONT_OPTION)
static char *inputFontStr= xicDefaultFont;
#endif
static XFontSet inputFont= NULL;
static XIMStyle inputStyle;
static XIC inputContext= 0;
static XPoint inputSpot= {0, 0};
static unsigned char inputString[128];
static unsigned char *inputBuf= inputString;
static unsigned char *pendingKey= NULL;
static int inputCount= 0;
/* static int inputSymbol= 0; */
static void initInputI18n();
#if !defined(INIT_INPUT_WHEN_KEY_PRESSED)
static void initInputNone();
static void (*initInput)()= initInputNone;
#endif
#define inBrowser() (-1 != browserPipes[0])
/* window states */
#define WIN_NORMAL 0
#define WIN_CHANGED 1
#define WIN_ZOOMED 2
int windowState= WIN_CHANGED;
#define noteWindowChange() \
{ \
if (windowState == WIN_NORMAL) \
windowState= WIN_CHANGED; \
}
#define recordKeystroke(ignored) 0
#include "sqUnixEvent.c"
#ifdef DEBUG_CONV
# define DCONV_PRINTF(...) printf(__VA_ARGS__)
# define DCONV_FPRINTF(...) fprintf(stderr,__VA_ARGS__)
#else
# define DCONV_PRINTF(...) 0
# define DCONV_FPRINTF(...) 0
#endif
#define SqueakWhite 0
#define SqueakBlack 1
int sleepWhenUnmapped= 0;
int noTitle= 0;
int fullScreen= 0;
int fullScreenDirect= 0;
int iconified= 0;
int withSpy= 0;
/*xxx REMOVE REFS TO THESE IN sqUnixSound*.* */
void feedback(int offset, int pixel) {}
int inModalLoop= 0, dpyPitch= 0, dpyPixels= 0;
/* we are interested in these events...
*/
#define EVENTMASK ButtonPressMask | ButtonReleaseMask | \
KeyPressMask | KeyReleaseMask | PointerMotionMask | \
ExposureMask | VisibilityChangeMask | FocusChangeMask
#define WM_EVENTMASK StructureNotifyMask | FocusChangeMask
/* largest X selection that we will attempt to handle (bytes) */
#define MAX_SELECTION_SIZE 100*1024
/* longest we're prepared to wait for the selection owner to convert it (seconds) */
#define SELECTION_TIMEOUT 3
/* To coordinate default window title with dndLaunchFile */
static char *defaultWindowLabel = shortImageName;
static long launchDropTimeoutMsecs = 1000; /* 1 second default launch drop timeout */
/*** Functions ***/
static void xHandler(int fd, void *data, int flags);
static void npHandler(int fd, void *data, int flags);
static void handleEvent(XEvent *event);
static int handleEvents(void);
static void waitForCompletions(void);
static Time getXTimestamp(void);
static void claimSelection(void);
#if defined(DEBUG_SELECTIONS)
static void printAtomName(Atom atom);
#endif
void setWindowSize(void);
void getMaskbit(unsigned long ul, int *nmask, int *shift);
void initDownGradingColors(void);
void copyReverseImageBytes(int *fromImageData, int *toImageData, int depth, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB);
void copyReverseImageWords(int *fromImageData, int *toImageData, int depth, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB);
#define declareCopyFunction(NAME) \
void NAME (int *fromImageData, int *toImageData, int width, int height, \
int affectedL, int affectedT, int affectedR, int affectedB)
declareCopyFunction(copyImage1To8);
declareCopyFunction(copyImage1To16);
declareCopyFunction(copyImage1To24);
declareCopyFunction(copyImage1To32);
declareCopyFunction(copyImage2To8);
declareCopyFunction(copyImage2To16);
declareCopyFunction(copyImage2To24);
declareCopyFunction(copyImage2To32);
declareCopyFunction(copyImage4To8);
declareCopyFunction(copyImage4To16);
declareCopyFunction(copyImage4To24);
declareCopyFunction(copyImage4To32);
declareCopyFunction(copyImage8To8);
declareCopyFunction(copyImage8To16);
declareCopyFunction(copyImage8To24);
declareCopyFunction(copyImage8To32);
declareCopyFunction(copyImage16To8);
declareCopyFunction(copyImage16To16);
declareCopyFunction(copyImage16To24);
declareCopyFunction(copyImage16To32);
declareCopyFunction(copyImage32To8);
declareCopyFunction(copyImage32To16);
declareCopyFunction(copyImage32To24);
declareCopyFunction(copyImage32To32);
declareCopyFunction(copyImage32To32Same);
#undef declareCopyFunction
static void redrawDisplay(int l, int r, int t, int b);
/* Selection functions */
typedef struct _SelectionChunk
{
unsigned char *data;
size_t size;
struct _SelectionChunk *next;
struct _SelectionChunk *last;
} SelectionChunk;
static int sendSelection(XSelectionRequestEvent *requestEv, int isMultiple);
static void getSelection(void);
static char *getSelectionData(Atom selection, Atom target, size_t *bytes);
static char *getSelectionFrom(Atom source);
static int translateCode(KeySym symbolic, int *modp, XKeyEvent *evt);
#if defined(USE_XSHM)
int XShmGetEventBase(Display *);
#endif
void browserProcessCommand(void); /* see sqUnixMozilla.c */
static inline int min(int x, int y) { return (x < y) ? x : y; }
#if 0
/* Conversion table from X to Squeak (reversible) */
static unsigned char X_to_Squeak[256] =
{
0, 1, 2, 3, 4, 5, 6, 7, /* 0 - 7 */
8, 9, 13, 11, 12, 10, 14, 15, /* 8 - 15 */
16, 17, 18, 19, 20, 21, 22, 23, /* 16 - 23 */
24, 25, 26, 27, 28, 29, 30, 31, /* 24 - 31 */
32, 33, 34, 35, 36, 37, 38, 39, /* 32 - 39 */
40, 41, 42, 43, 44, 45, 46, 47, /* 40 - 47 */
48, 49, 50, 51, 52, 53, 54, 55, /* 48 - 55 */
56, 57, 58, 59, 60, 61, 62, 63, /* 56 - 63 */
64, 65, 66, 67, 68, 69, 70, 71, /* 64 - 71 */
72, 73, 74, 75, 76, 77, 78, 79, /* 72 - 79 */
80, 81, 82, 83, 84, 85, 86, 87, /* 80 - 87 */
88, 89, 90, 91, 92, 93, 94, 95, /* 88 - 95 */
96, 97, 98, 99, 100, 101, 102, 103, /* 96 - 103 */
104, 105, 106, 107, 108, 109, 110, 111, /* 104 - 111 */
112, 113, 114, 115, 116, 117, 118, 119, /* 112 - 119 */
120, 121, 122, 123, 124, 125, 126, 127, /* 120 - 127 */
196, 197, 165, 201, 209, 247, 220, 225, /* 128 - 135 */
224, 226, 228, 227, 198, 176, 170, 248, /* 136 - 143 */
213, 206, 195, 207, 211, 212, 210, 219, /* 144 - 151 */
218, 221, 246, 245, 250, 249, 251, 252, /* 152 - 159 */
160, 193, 162, 163, 223, 180, 182, 164, /* 160 - 167 */
172, 169, 187, 199, 194, 173, 168, 255, /* 168 - 175 */
161, 177, 178, 179, 171, 181, 166, 183, /* 176 - 183 */
184, 185, 188, 200, 186, 189, 202, 192, /* 184 - 191 */
203, 231, 229, 204, 128, 129, 174, 130, /* 192 - 199 */
233, 131, 230, 232, 237, 234, 235, 236, /* 200 - 207 */
208, 132, 241, 238, 239, 205, 133, 215, /* 208 - 215 */
175, 244, 242, 243, 134, 217, 222, 167, /* 216 - 223 */
136, 135, 137, 139, 138, 140, 190, 141, /* 224 - 231 */
143, 142, 144, 145, 147, 146, 148, 149, /* 232 - 239 */
240, 150, 152, 151, 153, 155, 154, 214, /* 240 - 247 */
191, 157, 156, 158, 159, 253, 254, 216, /* 248 - 255 */
};
unsigned char Squeak_to_X[256];
void initCharmap(void)
{
int i;
for(i= 0; i < 256; i++)
Squeak_to_X[X_to_Squeak[i]]= i;
}
void st2ux(unsigned char *string)
{
if (!string) return;
while (*string)
{
*string= Squeak_to_X[*string];
string++;
}
}
void ux2st(unsigned char *string)
{
if (!string) return;
while (*string)
{
*string= X_to_Squeak[*string];
string++;
}
}
#endif
/*** X-related Functions ***/
/* Called prior to forking a squeak session.
*/
int synchronizeXDisplay(void)
{
if (isConnectedToXServer)
XSync(stDisplay, False);
return 0;
}
static Bool timestampPredicate(Display *dpy, XEvent *evt, XPointer arg)
{
return (( (PropertyNotify == evt->type))
&& (stWindow == evt->xproperty.window)
&& (xaTimestamp == evt->xproperty.atom)
&& (PropertyNewValue == evt->xproperty.state))
? True : False;
}
/* answer the real current server time */
static Time getXTimestamp(void)
{
unsigned char dummy;
XEvent evt;
XWindowAttributes xwa;
XGetWindowAttributes(stDisplay, stWindow, &xwa);
XSelectInput(stDisplay, stWindow, xwa.your_event_mask | PropertyChangeMask);
XChangeProperty(stDisplay, stWindow, xaTimestamp, XA_INTEGER, 8, PropModeAppend, &dummy, 0);
XIfEvent(stDisplay, &evt, timestampPredicate, 0);
XSelectInput(stDisplay, stWindow, xwa.your_event_mask);
return evt.xproperty.time;
}
#if defined(DEBUG_VISUAL)
static char *debugVisual(int x)
{
switch (x)
{
case 0: return "StaticGray";
case 1: return "GrayScale";
case 2: return "StaticColor";
case 3: return "PseudoColor";
case 4: return "TrueColor";
case 5: return "DirectColor";
default: return "Invalid";
}
}
#endif
static void noteResize(int w, int h)
{
xWidth= w;
xHeight= h;
#if defined(USE_XSHM)
if (asyncUpdate)
waitForCompletions();
#endif
noteWindowChange();
}
static int resized(void)
{
return ((stWidth != xWidth) || (stHeight != xHeight));
}
/*** selection handling ***/
#if defined(DEBUG_SELECTIONS)
static void dumpSelectionData(const char *data, int n, int newline)
{
if (NULL == data)
fprintf(stderr, "dumpSelectionData: data is NULL\n");
else
{
for (n= min(30, n); n > 0; --n)
{
unsigned char c= (unsigned char)*data++;
fprintf(stderr, (0x20 <= c && c <= 0x7e) ? "%c" : "<%02x>", c);
}
if (newline)
fprintf(stderr, "\n");
}
}
/* this is needed because the atom names must be freed */
static void printAtomName(Atom atom)
{
if (None == atom)
{
fprintf(stderr, "None");
}
else
{
char *atomName= XGetAtomName(stDisplay, atom);
fprintf(stderr, "%s", atomName);
XFree((void *)atomName);
}
}
#endif
static int allocateSelectionBuffer(int count)
{
/*if (count + 1 > stPrimarySelectionSize)*/ /* XXX test removed for dnd out; maybe should be left in? XXX */
{
if (stPrimarySelection != stEmptySelection)
{
free(stPrimarySelection);
stPrimarySelection= stEmptySelection;
stPrimarySelectionSize= 0;
}
if (!(stPrimarySelection= (char *)malloc(count + 1)))
{
fprintf(stderr, "failed to allocate X selection buffer\n");
stPrimarySelection= stEmptySelection;
stPrimarySelectionSize= 0;
return 0;
}
stPrimarySelectionSize= count;
}
return 1;
}
/* answers true if selection could be handled */
static int sendSelection(XSelectionRequestEvent *requestEv, int isMultiple)
{
int xError= 0;
XSelectionEvent notifyEv;
Atom targetProperty= ((None == requestEv->property)
? requestEv->target
: requestEv->property);
/* XSelectionRequestEvent is used for both clipboard and Xdnd. In
* the case of Xdnd, XSelectionEvent is answered asynchronously
* after the image prepares data because target (data type) is
* informed only when the SelectionRequest is sent.
* dndOutSelectionRequest() sends a SQDragRequest event to the image
* for that. Finally, the image calls
* HandMorph>>primitiveDndOutSend: to send the SelectionRequest.
*/
if (xaXdndSelection == requestEv->selection) return 0;
notifyEv.property= targetProperty;
#if defined(DEBUG_SELECTIONS)
fprintf(stderr, "%d selection request sel ", isMultiple);
printAtomName(requestEv->selection);
fprintf(stderr, " prop ");
printAtomName(requestEv->property);
fprintf(stderr, " target ");
printAtomName(requestEv->target);
fprintf(stderr, "\n");
#endif
if ((XA_STRING == requestEv->target) || (xaUTF8String == requestEv->target))
{
int len= strlen(stPrimarySelection);
char *buf= (char *)malloc(len * 3 + 1);
int n;
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "sendSelection: len=%d, sel=", len);
dumpSelectionData(stPrimarySelection, len, 1);
# endif
if (xaUTF8String == requestEv->target)
n= sq2uxUTF8(stPrimarySelection, len, buf, len * 3 + 1, 1);
else
n= sq2uxText(stPrimarySelection, len, buf, len * 3 + 1, 1);
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "sendSelection: n=%d, buf=", n);
dumpSelectionData(buf, n, 1);
# endif
XChangeProperty(requestEv->display, requestEv->requestor,
targetProperty, requestEv->target,
8, PropModeReplace, (const unsigned char *)buf, n);
free(buf);
}
else if ((stSelectionType == requestEv->target) && (None != stSelectionType))
{
/* In case of type other than image/png */
XChangeProperty(requestEv->display, requestEv->requestor,
targetProperty, requestEv->target,
8, PropModeReplace,
(const unsigned char *) stPrimarySelection,
stPrimarySelectionSize);
}
else if (xaTargets == requestEv->target)
{
/* If we don't report COMPOUND_TEXT in this list, KMail (and maybe other
* Qt/KDE apps) don't accept pastes from Squeak. Of course, they'll use
* UTF8_STRING anyway... */
Atom targets[7];
int targetsSize= 6;
targets[0]= xaTargets;
targets[1]= xaMultiple;
targets[2]= xaTimestamp; /* required by ICCCM */
targets[3]= xaUTF8String;
targets[4]= XA_STRING;
targets[5]= xaCompoundText;
if (stSelectionType != None)
{
targetsSize += 1;
targets[6]= stSelectionType;
}
xError= XChangeProperty(requestEv->display, requestEv->requestor,
targetProperty, XA_ATOM,
32, PropModeReplace, (unsigned char *)targets, targetsSize);
}
else if (xaCompoundText == requestEv->target)
{
/* COMPOUND_TEXT is handled here for older clients that don't handle UTF-8 */
XTextProperty textProperty;
char *list[]= { stPrimarySelection, NULL };
if (localeEncoding == sqTextEncoding)
xError= XmbTextListToTextProperty(requestEv->display, list, 1, XCompoundTextStyle, &textProperty);
# if defined(X_HAVE_UTF8_STRING)
else if (uxUTF8Encoding == sqTextEncoding)
xError= Xutf8TextListToTextProperty(requestEv->display, list, 1, XCompoundTextStyle, &textProperty);
# endif
else
{
int len= strlen(stPrimarySelection);
char *buf= (char *)malloc(len * 3 + 1);
list[0]= buf;
sq2uxText(stPrimarySelection, len, buf, len * 3 + 1, 1);
xError= XmbTextListToTextProperty(requestEv->display, list, 1, XCompoundTextStyle, &textProperty);
free(buf);
}
if (Success == xError)
{
xError= XChangeProperty(requestEv->display, requestEv->requestor,
targetProperty, xaCompoundText,
8, PropModeReplace, textProperty.value, textProperty.nitems);
XFree((void *)textProperty.value);
}
else
{
fprintf(stderr, "XmbTextListToTextProperty returns %d\n", xError);
notifyEv.property= None;
}
}
else if (xaTimestamp == requestEv->target)
{
xError= XChangeProperty(requestEv->display, requestEv->requestor,
targetProperty, XA_INTEGER,
32, PropModeReplace, (unsigned char *)&stSelectionTime, 1);
}
else if (xaMultiple == requestEv->target)
{
/* The ICCCM requires MULTIPLE, but I'm not sure who sends it. */
if (None == requestEv->property)
notifyEv.property= None; /* illegal request */
else
{
Atom* multipleAtoms= NULL;
int format;
Atom type;
unsigned long numberOfItems, bytesAfter;
xError= XGetWindowProperty(requestEv->display,
requestEv->requestor,
requestEv->property,
0, 100, False,
AnyPropertyType, /* XA_ATOM */
&type, &format,
&numberOfItems,
&bytesAfter,
(unsigned char **)&multipleAtoms);
if ((xError != Success) || (bytesAfter != 0)
|| (format != 32) || (type == None))
{
notifyEv.property= None;
}
else
{
unsigned long i;
for (i= 0; i < numberOfItems; i+= 2)
{
XSelectionRequestEvent individualRequestEv;
memcpy(&individualRequestEv, requestEv, sizeof(XSelectionRequestEvent));
individualRequestEv.target= multipleAtoms[i];
individualRequestEv.property= multipleAtoms[i+1];
if (individualRequestEv.target == None)
{
multipleAtoms[i+1]= None;
}
else
{
/* call this function recursively for each target/property pair */
if (!sendSelection(&individualRequestEv, i/2 + 1))
{
multipleAtoms[i+1]= None;
}
}
}
}
}
}
else
{
notifyEv.property= None; /* couldn't handle it */
}
#if defined(DEBUG_SELECTIONS)
if (xError == BadAlloc || xError == BadAtom || xError == BadMatch
|| xError == BadValue || xError == BadWindow)
fprintf(stderr, "sendSelection: XChangeProperty err %d\n", xError);
#endif
/* on MULTIPLE requests, we notify only once */
if (!isMultiple)
{
notifyEv.type= SelectionNotify;
notifyEv.display= requestEv->display;
notifyEv.requestor= requestEv->requestor;
notifyEv.selection= requestEv->selection;
notifyEv.target= requestEv->target;
/* notifyEv.property set above */
notifyEv.time= requestEv->time;
notifyEv.send_event= True;
XSendEvent(requestEv->display, requestEv->requestor, False, 0, (XEvent *)¬ifyEv);
XFlush(stDisplay);
}
return notifyEv.property != None;
}
static void getSelection(void)
{
char *data;
if (usePrimaryFirst)
{
data= getSelectionFrom(XA_PRIMARY); /* try PRIMARY first */
if (stEmptySelection == data)
data= getSelectionFrom(xaClipboard); /* then try CLIPBOARD (TODO CUT_BUFFER0?) */
}
else
{
data= getSelectionFrom(xaClipboard); /* try clipboard first */
if (stEmptySelection == data)
data= getSelectionFrom(XA_PRIMARY); /* then try PRIMARY */
}
}
static char *getSelectionFrom(Atom source)
{
char * data= NULL;
size_t bytes= 0;
/* request the selection */
Atom target= textEncodingUTF8 ? xaUTF8String : (localeEncoding ? xaCompoundText : XA_STRING);
data= getSelectionData(source, target, &bytes);
if (bytes == 0)
return stEmptySelection;
/* convert the encoding if necessary */
if (bytes && allocateSelectionBuffer(bytes))
{
if (textEncodingUTF8)
bytes= ux2sqUTF8(data, bytes, stPrimarySelection, bytes + 1, 1);
else if (localeEncoding)
{
char **strList= NULL;
int i, n, s= 0;
XTextProperty textProperty;
textProperty.encoding= xaCompoundText;
textProperty.format= 8;
textProperty.value= data;
textProperty.nitems= bytes;
# if defined(X_HAVE_UTF8_STRING)
if (uxUTF8Encoding == sqTextEncoding)
Xutf8TextPropertyToTextList(stDisplay, &textProperty, &strList, &n);
else
# endif
XmbTextPropertyToTextList(stDisplay, &textProperty, &strList, &n);
for (i= 0; i < n; ++i)
s+= strlen(strList[i]);
if (s > bytes)
{
bytes= min(s, MAX_SELECTION_SIZE - 1);
if (! allocateSelectionBuffer(bytes))
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "no bytes\n");
# endif
goto nobytes;
}
}
if ((localeEncoding == sqTextEncoding)
# if defined(X_HAVE_UTF8_STRING)
|| (uxUTF8Encoding == sqTextEncoding)
# endif
)
{
strcpy(stPrimarySelection, strList[0]);
for (i= 1; i < n; ++i)
strcat(stPrimarySelection, strList[i]);
}
else
{
char *to= stPrimarySelection;
for (i= 0; i < n - 1; ++i)
{
s= strlen(strList[i]);
s= ux2sqText(strList[i], s, to, bytes, 0);
bytes -= s;
to += s;
}
s= strlen(strList[n - 1]);
s= ux2sqText(strList[n - 1], s, to, bytes + 1, 1);
}
if (strList)
XFreeStringList(strList);
/* translate LF -> CR */
for (i= 0; stPrimarySelection[i] != '\0'; ++i)
if ('\n' == stPrimarySelection[i])
stPrimarySelection[i]= '\r';
}
else
bytes= ux2sqText(data, bytes, stPrimarySelection, bytes + 1, 1);
/* wrong type check was omitted */
}
else
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "no bytes\n");
# endif
}
nobytes:
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "selection=");
dumpSelectionData(stPrimarySelection, bytes, 1);
# endif
XFree((void *)data);
return stPrimarySelection;
}
/* Wait specific event to get property change.
* Return 1 if success.
*/
static int waitNotify(XEvent *ev, int (*condition)(XEvent *ev))
{
fd_set fdMask;
/* wait for selection notification, ignoring (most) other events. */
FD_ZERO(&fdMask);
if (stXfd >= 0)
FD_SET(stXfd, &fdMask);
do
{
if (XPending(stDisplay) == 0)
{
int status;
struct timeval timeout= { SELECTION_TIMEOUT, 0 };
while (((status= select(FD_SETSIZE, &fdMask, 0, 0, &timeout)) < 0) && (errno == EINTR))
;
if (status < 0)
{
perror("select(stDisplay)");
return 0; /* stEmptySelection */
}
if (status == 0)
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "getSelection: select() timeout\n");
# endif
if (isConnectedToXServer)
XBell(stDisplay, 0);
return 0;
}
}
XNextEvent(stDisplay, ev);
switch (ev->type)
{
case ConfigureNotify:
noteResize(ev->xconfigure.width, ev->xconfigure.height);
break;
/* this is necessary so that we can supply our own selection when we
are the requestor -- this could (should) be optimised to return the
stored selection value instead! */
case SelectionRequest:
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "getSelection: sending own selection\n");
# endif
sendSelection(&ev->xselectionrequest, 0);
break;
# if defined(USE_XSHM)
default:
if (ev->type == completionType)
--completions;
# endif
}
}
while (!condition(ev));
return 1;
}
static int waitSelectionNotify(XEvent *ev)
{
return ev->type == SelectionNotify;
}
static int waitPropertyNotify(XEvent *ev)
{
return (ev->type == PropertyNotify) && (ev->xproperty.state == PropertyNewValue);
}
/* SelectionChunk functions.
* SelectionChunk remembers (not copies) buffers from selections.
* It is useful to handle partial data transfar with XGetWindowProperty.
*/
static SelectionChunk *newSelectionChunk(void)
{
SelectionChunk * chunk= malloc(sizeof(SelectionChunk));
chunk->data= NULL;
chunk->size= 0;
chunk->next= NULL;
chunk->last=chunk;
return chunk;
}
static void destroySelectionChunk(SelectionChunk *chunk)
{
SelectionChunk * i;
for (i= chunk; i != NULL;) {
SelectionChunk * next= i->next;
XFree(i->data);
free(i);
i= next;
}
}
static void addSelectionChunk(SelectionChunk *chunk, unsigned char *src, size_t size)
{
chunk->last->data= src;
chunk->last->size= size;
chunk->last->next= newSelectionChunk();
chunk->last= chunk->last->next;
}
static size_t sizeSelectionChunk(SelectionChunk *chunk)
{
size_t totalSize= 0;
SelectionChunk * i;
for (i= chunk; i != NULL; i= i->next)
totalSize += i->size;
return totalSize;
}
static void copySelectionChunk(SelectionChunk *chunk, char *dest)
{
SelectionChunk *i;
char *j= dest;
for (i= chunk; i; j+= i->size, i= i->next)
memcpy(j, i->data, i->size);
}
/* get the value of the selection from the containing property */
static size_t getSelectionProperty(SelectionChunk *chunk, Window requestor, Atom property, Atom *actualType)
{
unsigned long bytesAfter= 0, nitems= 0, nread= 0;
unsigned char *data= 0;
size_t size;
int format;
do
{
XGetWindowProperty(stDisplay, requestor, property,
nread, (MAX_SELECTION_SIZE / 4),
True, AnyPropertyType,
actualType, &format, &nitems, &bytesAfter,
&data);
size= nitems * format / 8;
nread += size / 4;
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "getprop type ");
printAtomName(*actualType);
fprintf(stderr, " format %d nitems %ld bytesAfter %ld\ndata=",
format, nitems, bytesAfter);
dumpSelectionData((char *) data, nitems, 1);
# endif
addSelectionChunk(chunk, data, size);
}
while (bytesAfter);
return size;
}
static void getSelectionIncr(SelectionChunk *chunk, Window requestor, Atom property)
{
XEvent ev;
size_t size;
Atom actualType;
do {
fprintf(stderr, "getSelectionIncr: wait next chunk\n");
waitNotify(&ev, waitPropertyNotify);
size= getSelectionProperty(chunk, requestor, property, &actualType);
} while (size > 0);
}
/* Read selection data from the target in the selection,
* or chunk of zero length if unavailable.
* Caller must free the returned data with destroySelectionChunk().
*/
static void getSelectionChunk(SelectionChunk *chunk, Atom selection, Atom target)
{
Time timestamp= getXTimestamp();
XEvent evt;
int success;
Atom actualType;
Window requestor;
Atom property;
XDeleteProperty(stDisplay, stWindow, selectionAtom);
XConvertSelection(stDisplay, selection, target, selectionAtom, stWindow, timestamp);
success= waitNotify(&evt, waitSelectionNotify);
if (success == 0) return;
requestor= evt.xselection.requestor;
property= evt.xselection.property;
/* check if the selection was refused */
if (None == property)
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "getSelection: xselection.property == None\n");
# endif
if (isConnectedToXServer)
XBell(stDisplay, 0);
return;
}
getSelectionProperty(chunk, requestor, property, &actualType);
if (actualType == xaINCR)
{
destroySelectionChunk(chunk);
chunk= newSelectionChunk();
getSelectionIncr(chunk, requestor, property);
}
}
/* Get selection data from the target in the selection.
* Return NULL if there is no selection data.
* Caller must free the return data.
*/
static char *getSelectionData(Atom selection, Atom target, size_t *bytes)
{
char *data;
SelectionChunk *chunk= newSelectionChunk();
getSelectionChunk(chunk, selection, target);
*bytes= sizeSelectionChunk(chunk);
data= malloc(*bytes);
copySelectionChunk(chunk, data);
destroySelectionChunk(chunk);
return data;
}
/* claim ownership of the X selection, providing the given string to requestors */
static void claimSelection(void)
{
Time selectionTime= getXTimestamp();
XSetSelectionOwner(stDisplay, XA_PRIMARY, stWindow, selectionTime);
XSetSelectionOwner(stDisplay, xaClipboard, stWindow, selectionTime);
stSelectionTime= selectionTime;
XFlush(stDisplay);
stOwnsClipboard= (XGetSelectionOwner(stDisplay, xaClipboard) == stWindow);
stOwnsSelection= (XGetSelectionOwner(stDisplay, XA_PRIMARY) == stWindow);
#if defined(DEBUG_SELECTIONS)
fprintf(stderr, "claim selection stOwnsClipboard=%d, stOwnsSelection=%d\n",
stOwnsClipboard, stOwnsSelection);
#endif
}
void initClipboard(void)
{
stPrimarySelection= stEmptySelection;
stPrimarySelectionSize= 0;
stOwnsSelection= 0;
stOwnsClipboard= 0;
stSelectionType= None;
}
static Atom stringToAtom(char *target, size_t size)
{
char *formatString;
Atom result;
formatString= (char *) malloc(size + 1);
memcpy(formatString, target, size);
formatString[size]= 0;
result= XInternAtom(stDisplay, formatString, False);
free(formatString);
return result;
}
/* Prepare to write typed data for the selection; add a 0-terminator
* at end of the data for safety.
*
* selectionName : None (CLIPBOARD and PRIMARY), or XdndSelection
* type : None (various string), or target type ('image/png' etc.)
* data : data
* ndata : size of the data
* typeName : 0 (various string), or target name ('image/png' etc.)
* ntypeName : length of typeName
* isDnd : true if XdndSelection, false if CLIPBOARD or PRIMARY
* isClaiming : true if XGetSelectionOwner is needed
*/
static void display_clipboardWriteWithType(char *data, size_t ndata, char *typeName, size_t nTypeName, int isDnd, int isClaiming)
{
if (allocateSelectionBuffer(ndata))
{
Atom type= stringToAtom(typeName, nTypeName);
stSelectionName= isDnd ? xaXdndSelection : None;
memcpy((void *)stPrimarySelection, data, ndata);
stPrimarySelection[ndata]= '\0';
stSelectionType= type;
if (isClaiming) claimSelection();
}
}
static sqInt display_clipboardSize(void)
{
if (stOwnsClipboard) return 0;
getSelection();
return stPrimarySelectionSize;
}
static sqInt display_clipboardWriteFromAt(sqInt count, sqInt byteArrayIndex, sqInt startIndex)
{
display_clipboardWriteWithType(pointerForOop(byteArrayIndex + startIndex), count, NULL, 0, 0, 1);
return 0;
}
/* Transfer the X selection into the given byte array; optimise local requests. */
/* Call clipboardSize() or clipboardSizeWithType() before this. */
static sqInt display_clipboardReadIntoAt(sqInt count, sqInt byteArrayIndex, sqInt startIndex)
{
int clipSize;
if (!isConnectedToXServer)
return 0;
clipSize= min(count, stPrimarySelectionSize);
#if defined(DEBUG_SELECTIONS)
fprintf(stderr, "clipboard read: %d selectionSize %d\n", count, stPrimarySelectionSize);
#endif
memcpy(pointerForOop(byteArrayIndex + startIndex), (void *)stPrimarySelection, clipSize);
return clipSize;
}
/* A modified copy of fullDisplayUpdate() that redraws only the damaged
* parts of the window according to each expose event on the queue.
* Note: if the format of Form or Bitmap changes, this version of the
* code WILL FAIL! Otherwise it is to be preferred.
*/
static void redrawDisplay(int l, int r, int t, int b)
{
if (displayBits)
ioShowDisplay((sqInt)displayBits, displayWidth, displayHeight, displayDepth,
(sqInt)l, (sqInt)r, (sqInt)t, (sqInt)b);
}
static void getMousePosition(void)
{
Window root, child;
int rootX, rootY, winX, winY;
unsigned int mask;
if (True == XQueryPointer(stDisplay, stWindow, &root, &child,
&rootX, &rootY, &winX, &winY, &mask))
{
mousePosition.x= winX;
mousePosition.y= winY;
/* could update modifiers from mask too, but I can't be bothered... */
}
}
int recode(int charCode)
{
if (charCode >= 128)
{
unsigned char buf[32];
unsigned char out[32];
buf[0]= charCode;
if (convertChars((char *)buf, 1, uxXWinEncoding,
(char *)out, sizeof(out),
sqTextEncoding, 0, 1))
charCode= out[0];
# if DEBUG_KEYBOARD_EVENTS
fprintf(stderr, " 8-bit: %d=%02x [%c->%c]\n", charCode, charCode,
(char *)uxXWinEncoding, (char *)sqTextEncoding);
# endif
}
return charCode;
}
char *setLocale(char *localeName, size_t len)
{
char name[len + 1];
char *locale;
if (inputContext)
{
XIM im= XIMOfIC(inputContext);
XDestroyIC(inputContext);
if (im) XCloseIM(im);
}
strncpy(name, localeName, len);
name[len]= '\0';
if ((locale= setlocale(LC_CTYPE, name)))
{
setLocaleEncoding(locale);
initInputI18n();
return locale;
}
else
{
if (localeEncoding)
{
freeEncoding(localeEncoding);
localeEncoding= NULL;
}
inputContext= 0;
x2sqKey= x2sqKeyPlain;
if (len)
fprintf(stderr, "setlocale() failed for %s\n", name);
else
fprintf(stderr, "setlocale() failed (check values of LC_CTYPE, LANG and LC_ALL)\n");
return NULL;
}
}
int setCompositionFocus(int focus)
{
if (!inputContext)
return 0;
if (focus)
XSetICFocus(inputContext);
else
XUnsetICFocus(inputContext);
return 1;
}
int setCompositionWindowPosition(int x, int y)
{
int ret= 1;
inputSpot.x= x;
inputSpot.y= y;
if (inputContext && (inputStyle & XIMPreeditPosition))
{
XVaNestedList vlist= XVaCreateNestedList(0, XNSpotLocation, &inputSpot, NULL);
# if defined(DEBUG_XIM)
fprintf(stderr, "Set Preedit Spot %d %d\n", x, y);
# endif
if (XSetICValues(inputContext, XNPreeditAttributes, vlist, NULL))
{
fprintf(stderr, "Failed to Set Preedit Spot\n");
ret= 0;
}
XFree(vlist);
}
return ret;
}
static void setInputContextArea(void)
{
XWindowAttributes wa;
XVaNestedList vlist;
XRectangle pa, sa, *rect;
if ((!inputContext) || (inputStyle & XIMPreeditPosition))
return;
if (inputStyle & XIMPreeditArea)
{
XGetWindowAttributes(stDisplay, stWindow, &wa);
# if defined(DEBUG_XIM)
fprintf(stderr, "window geometry %d %d %d %d %d\n", wa.x, wa.y, wa.width, wa.height, wa.border_width);
# endif
wa.width -= wa.border_width * 2;
wa.height -= wa.border_width * 2;
vlist= XVaCreateNestedList(0, XNAreaNeeded, &rect, NULL);
if (XGetICValues(inputContext, XNPreeditAttributes, vlist, NULL))
{
fprintf(stderr, "Failed to Get Needed PreeditArea\n");
pa.x= pa.y= pa.width= pa.height= 0;
}
else
{
pa= *rect;
# if defined(DEBUG_XIM)
fprintf(stderr, "PreeditArea needs %d %d %u %u\n", pa.x, pa.y, pa.width, pa.height);
# endif
}
XFree(vlist);
if (inputStyle & XIMStatusArea)
{
static int minWidth= 0, minHeight= 0;
static XFontSetExtents *extents= NULL;
if (!extents)
{
extents= XExtentsOfFontSet(inputFont);
minWidth= extents->max_logical_extent.width * 3;
minHeight= extents->max_logical_extent.height - extents->max_logical_extent.y;
}
vlist= XVaCreateNestedList(0, XNAreaNeeded, &rect, NULL);
if (XGetICValues(inputContext, XNStatusAttributes, vlist, NULL))
{
fprintf(stderr, "Failed to Get Needed StatusArea\n");
sa.x= sa.y= sa.width= sa.height= 0;
}
else
{
sa= *rect;
# if defined(DEBUG_XIM)
fprintf(stderr, "StatusArea needs %d %d %u %u\n", sa.x, sa.y, sa.width, sa.height);
# endif
}
XFree(vlist);
if (minHeight > sa.height)
pa.height= sa.height= minHeight;
if (minWidth > sa.width)
sa.width= minWidth;
wa.width -= sa.width;
if (wa.width > pa.width)
pa.width= wa.width;
sa.x= wa.border_width;
pa.x= sa.x + sa.width;
sa.y= pa.y= wa.height + wa.border_width - sa.height;
vlist= XVaCreateNestedList(0, XNArea, &sa, NULL);
if (XSetICValues(inputContext, XNStatusAttributes, vlist, NULL))
{
fprintf(stderr, "Failed to Set StatusArea %d %d %u %u\n", sa.x, sa.y, sa.width, sa.height);
}
# if defined(DEBUG_XIM)
else
{
XFree(vlist);
vlist= XVaCreateNestedList(0, XNArea, &rect, NULL);
XGetICValues(inputContext, XNStatusAttributes, vlist, NULL);
fprintf(stderr, "Setted StatusArea %d %d %u %u\n", rect->x, rect->y, rect->width, rect->height);
}
# endif
XFree(vlist);
}
else
{
pa.x= wa.border_width;
pa.y= wa.border_width;
if (wa.width > pa.width)
pa.width= wa.width;
if (wa.height > pa.height)
pa.height= wa.height;
}
vlist= XVaCreateNestedList(0, XNArea, &pa, NULL);
if (XSetICValues(inputContext, XNPreeditAttributes, vlist, NULL))
{
fprintf(stderr, "Failed to Set PreeditArea %d %d %u %u\n", pa.x, pa.y, pa.width, pa.height);
}
XFree(vlist);
}
}
# if !defined(INIT_INPUT_WHEN_KEY_PRESSED)
static void initInputNone(void)
{
/* do nothing */
}
# endif
static void initInputI18n(void)
{
XIM im;
# if !defined(INIT_INPUT_WHEN_KEY_PRESSED)
initInput= initInputNone;
# endif
if (!compositionInput)
return;
x2sqKey= x2sqKeyPlain;
if (XSupportsLocale() != True)
fprintf(stderr, "XSupportsLocale() failed.\n");
else if (!XSetLocaleModifiers(""))
fprintf(stderr, "XSetLocaleModifiers() failed.\n");
else if (!(im= XOpenIM(stDisplay, 0, 0, 0)))
fprintf(stderr, "XOpenIM() failed\n");
else
{
static const XIMStyle pstyle[]= { XIMPreeditPosition, XIMPreeditArea, XIMPreeditNothing, XIMPreeditNone };
static const XIMStyle sstyle[]= { XIMStatusArea, XIMStatusNothing, XIMStatusNone, 0 };
XIMStyles *styles;
int i, j, k;
XVaNestedList vlist;
# if defined(DEBUG_XIM)
static const char const *stylename[]= { "Position", "Area", "Nothing", "None" };
char *locale= XLocaleOfIM(im);
fprintf(stderr, "Locale of im is %s\n", locale);
# endif
XGetIMValues(im, XNQueryInputStyle, &styles, NULL);
for (i= 0; i < styles->count_styles; ++i)
for (j= 0; j < sizeof(pstyle)/sizeof(XIMStyle); ++j)
for (k= 0; k < sizeof(pstyle)/sizeof(XIMStyle); ++k)
{
inputStyle= (pstyle[j] | sstyle[k]);
if (styles->supported_styles[i] == inputStyle)
goto foundStyle;
}
fprintf(stderr, "Preffered XIMStyles are not Supported.\n");
return;
foundStyle:
# if defined(DEBUG_XIM)
fprintf(stderr, "XIMStyle is Preedit%s and Status%s\n", stylename[j], stylename[k + 1]);
# endif
if (!inputFont)
{
char **misscharset, *tmpstr;
# if defined(USE_XICFONT_RESOURCE)
XrmDatabase db;
# endif
# if !defined(USE_XICFONT_OPTION)
# if defined(USE_XICFONT_RESOURCE) || defined(USE_XICFONT_DEFAULT)
char *inputFontStr;
# else
static char const *inputFontStr= xicDefaultFont;
# endif
# else
if (!inputFontStr)
# endif
{
# if defined(USE_XICFONT_RESOURCE)
static int rmInitialized= 0;
inputFontStr= xicDefaultFont;
if (!rmInitialized)
{
XrmInitialize();
rmInitialized= 1;
}
if ((tmpstr= XResourceManagerString(stDisplay)))
{
XrmValue val;
char *type;
db= XrmGetStringDatabase(tmpstr);
if (XrmGetResource(db, xResName "." xicFontResName, xResClass "." xicFontResClass, &type, &val))
inputFontStr= (char*)val.addr;
}
# elif defined(USE_XICFONT_DEFAULT)
inputFontStr= XGetDefault(stDisplay, xResName, xicFontDefRes);
if (!inputFontStr)
inputFontStr= xicDefaultFont;
# endif
}
inputFont= XCreateFontSet(stDisplay, inputFontStr, &misscharset, &k, &tmpstr);
# if defined(USE_XICFONT_RESOURCE)
/* if db is NULL, XrmDestroyDatabase returns immediatelly */
XrmDestroyDatabase(db);
# endif
if (!inputFont)
{
fprintf(stderr, "XCreateFontSet() failed for \"%s\"\n", inputFontStr);
/* XNFontSet is mandatory */
return;
}
}
vlist= XVaCreateNestedList(0,
XNFontSet, inputFont,
XNSpotLocation, &inputSpot,
NULL);
inputContext= XCreateIC(im,
XNInputStyle, inputStyle,
XNClientWindow, stWindow,
XNFocusWindow, stWindow,
XNPreeditAttributes, vlist,
XNStatusAttributes, vlist,
NULL);
XFree(vlist);
if (inputContext)
{
unsigned int mask;
XWindowAttributes xwa;
XGetWindowAttributes(stDisplay, stWindow, &xwa);
XGetICValues(inputContext, XNFilterEvents, &mask, NULL);
XSelectInput(stDisplay, stWindow, mask | xwa.your_event_mask);
# if defined(INIT_INPUT_WHEN_KEY_PRESSED)
setInputContextArea();
# endif
x2sqKey= x2sqKeyCompositionInput;
}
else
fprintf(stderr, "XCreateIC() failed\n");
}
}
/* Try to read keys into string using lookup function.
If buffer overflows, allocate another buffer.
Answer the buffer, that the caller must free if it != string.
*/
static unsigned char *lookupKeys(int (*lookup)(XIC, XKeyPressedEvent*, char*, int, KeySym*, Status*),
XKeyEvent *xevt,
unsigned char *string, int size,
int *count, KeySym *symbolic, Status *status)
{
*count= lookup(inputContext, (XKeyPressedEvent *)xevt, string, size, symbolic, status);
if (*status == XBufferOverflow)
{
unsigned char *buf= (unsigned char*)malloc((size_t)(*count * sizeof(unsigned char)));
if (buf)
*count= lookup(inputContext, (XKeyPressedEvent *)xevt, buf, *count, symbolic, status);
else
fprintf(stderr, "lookupKeys: out of memory\n");
return buf;
}
# if defined(DEBUG_XIM)
fprintf(stderr, "lookupKeys: '%s'\n", string);
# endif
return string;
}
/*
Answer 1 if some keys are still pending.
*/
static int recordPendingKeys(void)
{
if (compositionInput)
{
if (inputCount <= 0) {
if (inputBuf != inputString) {
free(inputBuf);
inputBuf= inputString;
}
return 0;
}
int utf32= 0;
while (inputCount > 0) {
# if defined(DEBUG_XIM)
fprintf(stderr, "%3d pending key 0x%02x\n", inputCount, *pendingKey);
# endif
/* 110x xxxx 10xx xxxx */
if (inputCount >= 2 &&
pendingKey[0] >= 0xc0 && pendingKey[0] <= 0xdf &&
pendingKey[1] >= 0x80 && pendingKey[1] <= 0xbf)
{
utf32= ((pendingKey[0] & 0x1f) << 6) |
(pendingKey[1] & 0x3f);
recordKeyboardEvent(0, EventKeyDown, modifierState, utf32);
recordKeyboardEvent(0, EventKeyChar, modifierState, utf32);
pendingKey += 2;
inputCount -= 2;
}
/* 1110 xxxx 10xx xxxx 10xx xxxx */
else if (inputCount >= 3 &&
pendingKey[0] >= 0xe0 && pendingKey[0] <= 0xef &&
pendingKey[1] >= 0x80 && pendingKey[1] <= 0xbf &&
pendingKey[2] >= 0x80 && pendingKey[2] <= 0xbf)
{
utf32= ((pendingKey[0] & 0x0f) << 12) |
((pendingKey[1] & 0x3f) << 6) |
(pendingKey[2] & 0x3f);
recordKeyboardEvent(0, EventKeyDown, modifierState, utf32);
recordKeyboardEvent(0, EventKeyChar, modifierState, utf32);
pendingKey += 3;
inputCount -= 3;
}
/* 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx */
else if (inputCount >= 4 &&
pendingKey[0] >= 0xf0 && pendingKey[0] <= 0xf7 &&
pendingKey[1] >= 0x80 && pendingKey[1] <= 0xbf &&
pendingKey[2] >= 0x80 && pendingKey[2] <= 0xbf &&
pendingKey[3] >= 0x80 && pendingKey[3] <= 0xbf)
{
utf32= ((pendingKey[0] & 0x07) << 18) |
((pendingKey[1] & 0x3f) << 12) |
((pendingKey[2] & 0x3f) << 6) |
(pendingKey[3] & 0x3f);
recordKeyboardEvent(0, EventKeyDown, modifierState, utf32);
recordKeyboardEvent(0, EventKeyChar, modifierState, utf32);
pendingKey += 4;
inputCount -= 4;
}
else
{
recordKeyboardEvent(*pendingKey, EventKeyDown, modifierState, 0);
recordKeyboardEvent(*pendingKey, EventKeyChar, modifierState, 0);
recordKeystroke(*pendingKey); /* DEPRECATED */
pendingKey++;
inputCount--;
}
}
return 0;
}
else
{
if (inputCount > 0)
{
int i= iebOut - iebIn;
for (i= (i > 0 ? i : IEB_SIZE + i) / 4; i > 0; -- i)
{
# if defined(DEBUG_XIM)
fprintf(stderr, "%3d pending key %2d=0x%02x\n", inputCount, i, *pendingKey);
# endif
recordKeyboardEvent(*pendingKey, EventKeyDown, modifierState, 0);
recordKeyboardEvent(*pendingKey, EventKeyChar, modifierState, 0);
recordKeystroke(*pendingKey); /* DEPRECATED */
++pendingKey;
if (--inputCount == 0) break;
}
return 1;
}
/* inputBuf is allocated by lookupKeys */
if (inputBuf != inputString)
{
free(inputBuf);
inputBuf= inputString;
}
return 0;
}
}
static int xkeysym2ucs4(KeySym keysym);
static int x2sqKeyInput(XKeyEvent *xevt, KeySym *symbolic)
{
static int initialised= 0;
static XIM im= 0;
static XIC ic= 0;
static int lastKey= -1;
if (!initialised)
{
initialised= 1;
if (!setlocale(LC_CTYPE, ""))
{
fprintf(stderr, "setlocale() failed (check values of LC_CTYPE, LANG and LC_ALL)\n");
goto revertInput;
}
if (!(im= XOpenIM(stDisplay, 0, 0, 0)))
{
fprintf(stderr, "XOpenIM() failed\n");
goto revertInput;
}
else
{
if (!(ic= XCreateIC(im, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, stWindow, NULL)))
{
fprintf(stderr, "XCreateIC() failed\n");
goto revertInput;
}
else
{
unsigned int mask;
XWindowAttributes xwa;
XGetWindowAttributes(stDisplay, stWindow, &xwa);
XGetICValues(ic, XNFilterEvents, &mask, NULL);
mask |= xwa.your_event_mask;
XSelectInput(stDisplay, stWindow, mask);
}
}
}
if (KeyPress != xevt->type)
{
int key= lastKey;
lastKey= -1;
return key;
}
DCONV_PRINTF("keycode %u\n", xevt->keycode);
{
char string[128]; /* way too much */
Status status;
int count= XmbLookupString(ic, (XKeyPressedEvent *)xevt, string, sizeof(string), symbolic, &status);
switch (status)
{
case XLookupNone: /* still composing */
DCONV_FPRINTF(stderr, "x2sqKey XLookupNone\n");
return -1;
case XLookupChars:
DCONV_FPRINTF(stderr, "x2sqKey XLookupChars count %d\n", count);
case XLookupBoth:
DCONV_FPRINTF(stderr, "x2sqKey XLookupBoth count %d\n", count);
lastKey= (count ? recode(string[0]) : -1);
DCONV_FPRINTF(stderr, "x2sqKey == %d\n", lastKey);
return lastKey;
case XLookupKeySym:
DCONV_FPRINTF(stderr, "x2sqKey XLookupKeySym\n");
{
int charCode= translateCode(*symbolic, 0, xevt);
DCONV_FPRINTF("SYM %d -> %d\n", symbolic, charCode);
if (charCode < 0)
return -1; /* unknown key */
if ((charCode == 127) && mapDelBs)
charCode= 8;
return lastKey= charCode;
}
default:
fprintf(stderr, "this cannot happen\n");
return lastKey= -1;
}
return lastKey= -1;
}
revertInput:
x2sqKey= x2sqKeyPlain;
return x2sqKey(xevt, symbolic);
}
static int x2sqKeyCompositionInput(XKeyEvent *xevt, KeySym *symbolic)
{
static int lastKey= -1;
# if defined(INIT_INPUT_WHEN_KEY_PRESSED)
if (!inputContext)
{
initInputI18n();
if (!inputContext)
return x2sqKeyPlain(xevt, symbolic);
}
# endif
if (KeyPress != xevt->type)
{
int key= lastKey;
lastKey= -1;
return key;
}
DCONV_FPRINTF(stderr, "keycode %u\n", xevt->keycode);
{
Status status;
int i;
if (localeEncoding == sqTextEncoding)
{
if (!(inputBuf= lookupKeys(XmbLookupString, xevt, inputString, sizeof(inputString), &inputCount, symbolic, &status)))
return lastKey= -1;
}
# if defined(X_HAVE_UTF8_STRING)
else if (uxUTF8Encoding == sqTextEncoding)
{
if (!(inputBuf= lookupKeys(Xutf8LookupString, xevt, inputString, sizeof(inputString), &inputCount, symbolic, &status)))
return lastKey= -1;
}
# endif
else
{
unsigned char aStr[128], *aBuf;
if (!(aBuf= lookupKeys(XmbLookupString, xevt, aStr, sizeof(aStr), &inputCount, symbolic, &status)))
{
fprintf(stderr, "status xmb2: %d\n", status);
return lastKey= -1;
}
if (inputCount > sizeof(inputString))
{
inputBuf= (unsigned char *) malloc((size_t) (inputCount * sizeof(unsigned char)));
if (!inputBuf)
{
fprintf(stderr, "x2sqKeyInput: out of memory\n");
if (aStr != aBuf)
free(aBuf);
return lastKey= -1;
}
}
else
inputBuf= inputString;
inputCount= ux2sqXWin(aBuf, inputCount, inputBuf, inputCount, 0);
if (aStr != aBuf)
free(aBuf);
}
switch (status)
{
case XLookupNone: /* still composing */
DCONV_FPRINTF(stderr, "x2sqKey XLookupNone\n");
return -1;
case XLookupChars:
DCONV_FPRINTF(stderr, "x2sqKey XLookupChars count %d\n", inputCount);
case XLookupBoth:
DCONV_FPRINTF(stderr, "x2sqKey XLookupBoth count %d\n", inputCount);
if (inputCount == 0)
return lastKey= -1;
else if (inputCount == 1)
{
inputCount= 0;
return lastKey= recode(inputBuf[0]);
}
else
{
# if defined(DEBUG_XIM)
int inputSymbol= xkeysym2ucs4(*symbolic);
fprintf(stderr, "x2sqKey string '%s' count %d\n", inputBuf, inputCount);
fprintf(stderr, "x2sqKey symbol 0x%08x => 0x%08x\n", *symbolic, inputSymbol);
# endif
/* record the key events here */
pendingKey= inputBuf;
recordPendingKeys();
/* unclear which is best value for lastKey... */
# if 1
lastKey= (inputCount == 1 ? inputBuf[0] : -1);
# else
lastKey= (inputCount ? inputBuf[0] : -1);
lastKey= (inputCount > 0 ? inputBuf[inputCount - 1] : -1);
# endif
return -1; /* we've already recorded the key events */
}
case XLookupKeySym:
DCONV_FPRINTF(stderr, "x2sqKey XLookupKeySym\n");
{
int charCode;
if (*symbolic == XK_Multi_key)
{
multi_key_pressed= 1;
multi_key_buffer= 0;
DCONV_FPRINTF(stderr, "multi_key was pressed\n");
return -1;
}
charCode= translateCode(*symbolic, 0, xevt);
DCONV_PRINTF("SYM %x -> %d\n", *symbolic, charCode);
if (charCode < 0)
return -1; /* unknown key */
if ((charCode == 127) && mapDelBs)
charCode= 8;
return lastKey= charCode;
}
default:
fprintf(stderr, "this cannot happen\n");
return lastKey= -1;
}
return lastKey= -1;
}
}
#if DEBUG_KEYBOARD_EVENTS
static const char *nameForKeycode(int keycode);
#endif
static int x2sqKeyPlain(XKeyEvent *xevt, KeySym *symbolic)
{
unsigned char buf[32];
int nConv= XLookupString(xevt, (char *)buf, sizeof(buf), symbolic, 0);
int charCode= buf[0];
#if DEBUG_KEYBOARD_EVENTS
int i;
fprintf(stderr, "convert keycode");
for (i = 0; i < nConv; i++) {
if (!i) fprintf(stderr, " [");
fprintf(stderr, "%d(%02x)%c", buf[i], buf[i], i + 1 < nConv ? ',' : ']');
}
fprintf(stderr, " %d(%02x) -> %d(%02x) (keysym %p %s)\n",
xevt->keycode, xevt->keycode, charCode, charCode, symbolic, nameForKeycode(*symbolic));
#endif
if (!nConv && (charCode= translateCode(*symbolic, &modifierState, xevt)) < 0)
return -1; /* unknown key */
if ((charCode == 127) && mapDelBs)
charCode= 8;
return nConv == 0 && (modifierState & (CommandKeyBit+CtrlKeyBit+OptionKeyBit))
? charCode
: recode(charCode);
}
static int xkeysym2ucs4(KeySym keysym)
{
/* Latin 2 Mappings */
static unsigned short const ucs4_01a1_01ff[] = {
0x0104, 0x02d8, 0x0141, 0x0000, 0x013d, 0x015a, 0x0000, /* 0x01a0-0x01a7 */
0x0000, 0x0160, 0x015e, 0x0164, 0x0179, 0x0000, 0x017d, 0x017b, /* 0x01a8-0x01af */
0x0000, 0x0105, 0x02db, 0x0142, 0x0000, 0x013e, 0x015b, 0x02c7, /* 0x01b0-0x01b7 */
0x0000, 0x0161, 0x015f, 0x0165, 0x017a, 0x02dd, 0x017e, 0x017c, /* 0x01b8-0x01bf */
0x0154, 0x0000, 0x0000, 0x0102, 0x0000, 0x0139, 0x0106, 0x0000, /* 0x01c0-0x01c7 */
0x010c, 0x0000, 0x0118, 0x0000, 0x011a, 0x0000, 0x0000, 0x010e, /* 0x01c8-0x01cf */
0x0110, 0x0143, 0x0147, 0x0000, 0x0000, 0x0150, 0x0000, 0x0000, /* 0x01d0-0x01d7 */
0x0158, 0x016e, 0x0000, 0x0170, 0x0000, 0x0000, 0x0162, 0x0000, /* 0x01d8-0x01df */
0x0155, 0x0000, 0x0000, 0x0103, 0x0000, 0x013a, 0x0107, 0x0000, /* 0x01e0-0x01e7 */
0x010d, 0x0000, 0x0119, 0x0000, 0x011b, 0x0000, 0x0000, 0x010f, /* 0x01e8-0x01ef */
0x0111, 0x0144, 0x0148, 0x0000, 0x0000, 0x0151, 0x0000, 0x0000, /* 0x01f0-0x01f7 */
0x0159, 0x016f, 0x0000, 0x0171, 0x0000, 0x0000, 0x0163, 0x02d9 /* 0x01f8-0x01ff */
};
/* Latin 3 Mappings */
static unsigned short const ucs4_02a1_02fe[] = {
0x0126, 0x0000, 0x0000, 0x0000, 0x0000, 0x0124, 0x0000, /* 0x02a0-0x02a7 */
0x0000, 0x0130, 0x0000, 0x011e, 0x0134, 0x0000, 0x0000, 0x0000, /* 0x02a8-0x02af */
0x0000, 0x0127, 0x0000, 0x0000, 0x0000, 0x0000, 0x0125, 0x0000, /* 0x02b0-0x02b7 */
0x0000, 0x0131, 0x0000, 0x011f, 0x0135, 0x0000, 0x0000, 0x0000, /* 0x02b8-0x02bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x010a, 0x0108, 0x0000, /* 0x02c0-0x02c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x02c8-0x02cf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0120, 0x0000, 0x0000, /* 0x02d0-0x02d7 */
0x011c, 0x0000, 0x0000, 0x0000, 0x0000, 0x016c, 0x015c, 0x0000, /* 0x02d8-0x02df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x010b, 0x0109, 0x0000, /* 0x02e0-0x02e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x02e8-0x02ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0121, 0x0000, 0x0000, /* 0x02f0-0x02f7 */
0x011d, 0x0000, 0x0000, 0x0000, 0x0000, 0x016d, 0x015d /* 0x02f8-0x02ff */
};
/* Latin 4 Mappings */
static unsigned short const ucs4_03a2_03fe[] = {
0x0138, 0x0156, 0x0000, 0x0128, 0x013b, 0x0000, /* 0x03a0-0x03a7 */
0x0000, 0x0000, 0x0112, 0x0122, 0x0166, 0x0000, 0x0000, 0x0000, /* 0x03a8-0x03af */
0x0000, 0x0000, 0x0000, 0x0157, 0x0000, 0x0129, 0x013c, 0x0000, /* 0x03b0-0x03b7 */
0x0000, 0x0000, 0x0113, 0x0123, 0x0167, 0x014a, 0x0000, 0x014b, /* 0x03b8-0x03bf */
0x0100, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x012e, /* 0x03c0-0x03c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0116, 0x0000, 0x0000, 0x012a, /* 0x03c8-0x03cf */
0x0000, 0x0145, 0x014c, 0x0136, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x03d0-0x03d7 */
0x0000, 0x0172, 0x0000, 0x0000, 0x0000, 0x0168, 0x016a, 0x0000, /* 0x03d8-0x03df */
0x0101, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x012f, /* 0x03e0-0x03e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0117, 0x0000, 0x0000, 0x012b, /* 0x03e8-0x03ef */
0x0000, 0x0146, 0x014d, 0x0137, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x03f0-0x03f7 */
0x0000, 0x0173, 0x0000, 0x0000, 0x0000, 0x0169, 0x016b /* 0x03f8-0x03ff */
};
/* Katakana Mappings */
static unsigned short const ucs4_04a1_04df[] = {
0x3002, 0x3008, 0x3009, 0x3001, 0x30fb, 0x30f2, 0x30a1, /* 0x04a0-0x04a7 */
0x30a3, 0x30a5, 0x30a7, 0x30a9, 0x30e3, 0x30e5, 0x30e7, 0x30c3, /* 0x04a8-0x04af */
0x30fc, 0x30a2, 0x30a4, 0x30a6, 0x30a8, 0x30aa, 0x30ab, 0x30ad, /* 0x04b0-0x04b7 */
0x30af, 0x30b1, 0x30b3, 0x30b5, 0x30b7, 0x30b9, 0x30bb, 0x30bd, /* 0x04b8-0x04bf */
0x30bf, 0x30c1, 0x30c4, 0x30c6, 0x30c8, 0x30ca, 0x30cb, 0x30cc, /* 0x04c0-0x04c7 */
0x30cd, 0x30ce, 0x30cf, 0x30d2, 0x30d5, 0x30d8, 0x30db, 0x30de, /* 0x04c8-0x04cf */
0x30df, 0x30e0, 0x30e1, 0x30e2, 0x30e4, 0x30e6, 0x30e8, 0x30e9, /* 0x04d0-0x04d7 */
0x30ea, 0x30eb, 0x30ec, 0x30ed, 0x30ef, 0x30f3, 0x309b, 0x309c /* 0x04d8-0x04df */
};
/* Arabic mappings */
static unsigned short const ucs4_0590_05fe[] = {
0x06f0, 0x06f1, 0x06f2, 0x06f3, 0x06f4, 0x06f5, 0x06f6, 0x06f7, /* 0x0590-0x0597 */
0x06f8, 0x06f9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x0598-0x059f */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x066a, 0x0670, 0x0679, /* 0x05a0-0x05a7 */
0x067e, 0x0686, 0x0688, 0x0691, 0x060c, 0x0000, 0x06d4, 0x0000, /* 0x05ac-0x05af */
0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666, 0x0667, /* 0x05b0-0x05b7 */
0x0668, 0x0669, 0x0000, 0x061b, 0x0000, 0x0000, 0x0000, 0x061f, /* 0x05b8-0x05bf */
0x0000, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, /* 0x05c0-0x05c7 */
0x0628, 0x0629, 0x062a, 0x062b, 0x062c, 0x062d, 0x062e, 0x062f, /* 0x05c8-0x05cf */
0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, /* 0x05d0-0x05d7 */
0x0638, 0x0639, 0x063a, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x05d8-0x05df */
0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, /* 0x05e0-0x05e7 */
0x0648, 0x0649, 0x064a, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, /* 0x05e8-0x05ef */
0x0650, 0x0651, 0x0652, 0x0653, 0x0654, 0x0655, 0x0698, 0x06a4, /* 0x05f0-0x05f7 */
0x06a9, 0x06af, 0x06ba, 0x06be, 0x06cc, 0x06d2, 0x06c1 /* 0x05f8-0x05fe */
};
/* Cyrillic mappings */
static unsigned short ucs4_0680_06ff[] = {
0x0492, 0x0496, 0x049a, 0x049c, 0x04a2, 0x04ae, 0x04b0, 0x04b2, /* 0x0680-0x0687 */
0x04b6, 0x04b8, 0x04ba, 0x0000, 0x04d8, 0x04e2, 0x04e8, 0x04ee, /* 0x0688-0x068f */
0x0493, 0x0497, 0x049b, 0x049d, 0x04a3, 0x04af, 0x04b1, 0x04b3, /* 0x0690-0x0697 */
0x04b7, 0x04b9, 0x04bb, 0x0000, 0x04d9, 0x04e3, 0x04e9, 0x04ef, /* 0x0698-0x069f */
0x0000, 0x0452, 0x0453, 0x0451, 0x0454, 0x0455, 0x0456, 0x0457, /* 0x06a0-0x06a7 */
0x0458, 0x0459, 0x045a, 0x045b, 0x045c, 0x0491, 0x045e, 0x045f, /* 0x06a8-0x06af */
0x2116, 0x0402, 0x0403, 0x0401, 0x0404, 0x0405, 0x0406, 0x0407, /* 0x06b0-0x06b7 */
0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x0490, 0x040e, 0x040f, /* 0x06b8-0x06bf */
0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, /* 0x06c0-0x06c7 */
0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, /* 0x06c8-0x06cf */
0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, /* 0x06d0-0x06d7 */
0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a, /* 0x06d8-0x06df */
0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, /* 0x06e0-0x06e7 */
0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, /* 0x06e8-0x06ef */
0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, /* 0x06f0-0x06f7 */
0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a /* 0x06f8-0x06ff */
};
/* Greek mappings */
static unsigned short const ucs4_07a1_07f9[] = {
0x0386, 0x0388, 0x0389, 0x038a, 0x03aa, 0x0000, 0x038c, /* 0x07a0-0x07a7 */
0x038e, 0x03ab, 0x0000, 0x038f, 0x0000, 0x0000, 0x0385, 0x2015, /* 0x07a8-0x07af */
0x0000, 0x03ac, 0x03ad, 0x03ae, 0x03af, 0x03ca, 0x0390, 0x03cc, /* 0x07b0-0x07b7 */
0x03cd, 0x03cb, 0x03b0, 0x03ce, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x07b8-0x07bf */
0x0000, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, /* 0x07c0-0x07c7 */
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, /* 0x07c8-0x07cf */
0x03a0, 0x03a1, 0x03a3, 0x0000, 0x03a4, 0x03a5, 0x03a6, 0x03a7, /* 0x07d0-0x07d7 */
0x03a8, 0x03a9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x07d8-0x07df */
0x0000, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, /* 0x07e0-0x07e7 */
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, /* 0x07e8-0x07ef */
0x03c0, 0x03c1, 0x03c3, 0x03c2, 0x03c4, 0x03c5, 0x03c6, 0x03c7, /* 0x07f0-0x07f7 */
0x03c8, 0x03c9 /* 0x07f8-0x07ff */
};
/* Technical mappings */
static unsigned short const ucs4_08a4_08fe[] = {
0x2320, 0x2321, 0x0000, 0x231c, /* 0x08a0-0x08a7 */
0x231d, 0x231e, 0x231f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08a8-0x08af */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08b0-0x08b7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x2264, 0x2260, 0x2265, 0x222b, /* 0x08b8-0x08bf */
0x2234, 0x0000, 0x221e, 0x0000, 0x0000, 0x2207, 0x0000, 0x0000, /* 0x08c0-0x08c7 */
0x2245, 0x2246, 0x0000, 0x0000, 0x0000, 0x0000, 0x22a2, 0x0000, /* 0x08c8-0x08cf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x221a, 0x0000, /* 0x08d0-0x08d7 */
0x0000, 0x0000, 0x2282, 0x2283, 0x2229, 0x222a, 0x2227, 0x2228, /* 0x08d8-0x08df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08e0-0x08e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08e8-0x08ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0192, 0x0000, /* 0x08f0-0x08f7 */
0x0000, 0x0000, 0x0000, 0x2190, 0x2191, 0x2192, 0x2193 /* 0x08f8-0x08ff */
};
/* Special mappings from the DEC VT100 Special Graphics Character Set */
static unsigned short const ucs4_09df_09f8[] = {
0x2422, /* 0x09d8-0x09df */
0x2666, 0x25a6, 0x2409, 0x240c, 0x240d, 0x240a, 0x0000, 0x0000, /* 0x09e0-0x09e7 */
0x240a, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x2500, /* 0x09e8-0x09ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x251c, 0x2524, 0x2534, 0x252c, /* 0x09f0-0x09f7 */
0x2502 /* 0x09f8-0x09ff */
};
/* Publishing Mappings ? */
static unsigned short const ucs4_0aa1_0afe[] = {
0x2003, 0x2002, 0x2004, 0x2005, 0x2007, 0x2008, 0x2009, /* 0x0aa0-0x0aa7 */
0x200a, 0x2014, 0x2013, 0x0000, 0x0000, 0x0000, 0x2026, 0x2025, /* 0x0aa8-0x0aaf */
0x2153, 0x2154, 0x2155, 0x2156, 0x2157, 0x2158, 0x2159, 0x215a, /* 0x0ab0-0x0ab7 */
0x2105, 0x0000, 0x0000, 0x2012, 0x2039, 0x2024, 0x203a, 0x0000, /* 0x0ab8-0x0abf */
0x0000, 0x0000, 0x0000, 0x215b, 0x215c, 0x215d, 0x215e, 0x0000, /* 0x0ac0-0x0ac7 */
0x0000, 0x2122, 0x2120, 0x0000, 0x25c1, 0x25b7, 0x25cb, 0x25ad, /* 0x0ac8-0x0acf */
0x2018, 0x2019, 0x201c, 0x201d, 0x211e, 0x0000, 0x2032, 0x2033, /* 0x0ad0-0x0ad7 */
0x0000, 0x271d, 0x0000, 0x220e, 0x25c2, 0x2023, 0x25cf, 0x25ac, /* 0x0ad8-0x0adf */
0x25e6, 0x25ab, 0x25ae, 0x25b5, 0x25bf, 0x2606, 0x2022, 0x25aa, /* 0x0ae0-0x0ae7 */
0x25b4, 0x25be, 0x261a, 0x261b, 0x2663, 0x2666, 0x2665, 0x0000, /* 0x0ae8-0x0aef */
0x2720, 0x2020, 0x2021, 0x2713, 0x2612, 0x266f, 0x266d, 0x2642, /* 0x0af0-0x0af7 */
0x2640, 0x2121, 0x2315, 0x2117, 0x2038, 0x201a, 0x201e /* 0x0af8-0x0aff */
};
/* Hebrew Mappings */
static unsigned short const ucs4_0cdf_0cfa[] = {
0x2017, /* 0x0cd8-0x0cdf */
0x05d0, 0x05d1, 0x05d2, 0x05d3, 0x05d4, 0x05d5, 0x05d6, 0x05d7, /* 0x0ce0-0x0ce7 */
0x05d8, 0x05d9, 0x05da, 0x05db, 0x05dc, 0x05dd, 0x05de, 0x05df, /* 0x0ce8-0x0cef */
0x05e0, 0x05e1, 0x05e2, 0x05e3, 0x05e4, 0x05e5, 0x05e6, 0x05e7, /* 0x0cf0-0x0cf7 */
0x05e8, 0x05e9, 0x05ea /* 0x0cf8-0x0cff */
};
/* Thai Mappings */
static unsigned short const ucs4_0da1_0df9[] = {
0x0e01, 0x0e02, 0x0e03, 0x0e04, 0x0e05, 0x0e06, 0x0e07, /* 0x0da0-0x0da7 */
0x0e08, 0x0e09, 0x0e0a, 0x0e0b, 0x0e0c, 0x0e0d, 0x0e0e, 0x0e0f, /* 0x0da8-0x0daf */
0x0e10, 0x0e11, 0x0e12, 0x0e13, 0x0e14, 0x0e15, 0x0e16, 0x0e17, /* 0x0db0-0x0db7 */
0x0e18, 0x0e19, 0x0e1a, 0x0e1b, 0x0e1c, 0x0e1d, 0x0e1e, 0x0e1f, /* 0x0db8-0x0dbf */
0x0e20, 0x0e21, 0x0e22, 0x0e23, 0x0e24, 0x0e25, 0x0e26, 0x0e27, /* 0x0dc0-0x0dc7 */
0x0e28, 0x0e29, 0x0e2a, 0x0e2b, 0x0e2c, 0x0e2d, 0x0e2e, 0x0e2f, /* 0x0dc8-0x0dcf */
0x0e30, 0x0e31, 0x0e32, 0x0e33, 0x0e34, 0x0e35, 0x0e36, 0x0e37, /* 0x0dd0-0x0dd7 */
0x0e38, 0x0e39, 0x0e3a, 0x0000, 0x0000, 0x0000, 0x0e3e, 0x0e3f, /* 0x0dd8-0x0ddf */
0x0e40, 0x0e41, 0x0e42, 0x0e43, 0x0e44, 0x0e45, 0x0e46, 0x0e47, /* 0x0de0-0x0de7 */
0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c, 0x0e4d, 0x0000, 0x0000, /* 0x0de8-0x0def */
0x0e50, 0x0e51, 0x0e52, 0x0e53, 0x0e54, 0x0e55, 0x0e56, 0x0e57, /* 0x0df0-0x0df7 */
0x0e58, 0x0e59 /* 0x0df8-0x0dff */
};
/* Hangul Mappings */
static unsigned short const ucs4_0ea0_0eff[] = {
0x0000, 0x1101, 0x1101, 0x11aa, 0x1102, 0x11ac, 0x11ad, 0x1103, /* 0x0ea0-0x0ea7 */
0x1104, 0x1105, 0x11b0, 0x11b1, 0x11b2, 0x11b3, 0x11b4, 0x11b5, /* 0x0ea8-0x0eaf */
0x11b6, 0x1106, 0x1107, 0x1108, 0x11b9, 0x1109, 0x110a, 0x110b, /* 0x0eb0-0x0eb7 */
0x110c, 0x110d, 0x110e, 0x110f, 0x1110, 0x1111, 0x1112, 0x1161, /* 0x0eb8-0x0ebf */
0x1162, 0x1163, 0x1164, 0x1165, 0x1166, 0x1167, 0x1168, 0x1169, /* 0x0ec0-0x0ec7 */
0x116a, 0x116b, 0x116c, 0x116d, 0x116e, 0x116f, 0x1170, 0x1171, /* 0x0ec8-0x0ecf */
0x1172, 0x1173, 0x1174, 0x1175, 0x11a8, 0x11a9, 0x11aa, 0x11ab, /* 0x0ed0-0x0ed7 */
0x11ac, 0x11ad, 0x11ae, 0x11af, 0x11b0, 0x11b1, 0x11b2, 0x11b3, /* 0x0ed8-0x0edf */
0x11b4, 0x11b5, 0x11b6, 0x11b7, 0x11b8, 0x11b9, 0x11ba, 0x11bb, /* 0x0ee0-0x0ee7 */
0x11bc, 0x11bd, 0x11be, 0x11bf, 0x11c0, 0x11c1, 0x11c2, 0x0000, /* 0x0ee8-0x0eef */
0x0000, 0x0000, 0x1140, 0x0000, 0x0000, 0x1159, 0x119e, 0x0000, /* 0x0ef0-0x0ef7 */
0x11eb, 0x0000, 0x11f9, 0x0000, 0x0000, 0x0000, 0x0000, 0x20a9, /* 0x0ef8-0x0eff */
};
/* Non existing range in keysymdef.h */
static unsigned short ucs4_12a1_12fe[] = {
0x1e02, 0x1e03, 0x0000, 0x0000, 0x0000, 0x1e0a, 0x0000, /* 0x12a0-0x12a7 */
0x1e80, 0x0000, 0x1e82, 0x1e0b, 0x1ef2, 0x0000, 0x0000, 0x0000, /* 0x12a8-0x12af */
0x1e1e, 0x1e1f, 0x0000, 0x0000, 0x1e40, 0x1e41, 0x0000, 0x1e56, /* 0x12b0-0x12b7 */
0x1e81, 0x1e57, 0x1e83, 0x1e60, 0x1ef3, 0x1e84, 0x1e85, 0x1e61, /* 0x12b8-0x12bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12c0-0x12c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12c8-0x12cf */
0x0174, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1e6a, /* 0x12d0-0x12d7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0176, 0x0000, /* 0x12d8-0x12df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12e0-0x12e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12e8-0x12ef */
0x0175, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1e6b, /* 0x12f0-0x12f7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0177 /* 0x12f0-0x12ff */
};
/* Latin 9 Mappings */
static unsigned short const ucs4_13bc_13be[] = {
0x0152, 0x0153, 0x0178 /* 0x13b8-0x13bf */
};
/* Non existing range in keysymdef.h */
static unsigned short ucs4_14a1_14ff[] = {
0x2741, 0x00a7, 0x0589, 0x0029, 0x0028, 0x00bb, 0x00ab, /* 0x14a0-0x14a7 */
0x2014, 0x002e, 0x055d, 0x002c, 0x2013, 0x058a, 0x2026, 0x055c, /* 0x14a8-0x14af */
0x055b, 0x055e, 0x0531, 0x0561, 0x0532, 0x0562, 0x0533, 0x0563, /* 0x14b0-0x14b7 */
0x0534, 0x0564, 0x0535, 0x0565, 0x0536, 0x0566, 0x0537, 0x0567, /* 0x14b8-0x14bf */
0x0538, 0x0568, 0x0539, 0x0569, 0x053a, 0x056a, 0x053b, 0x056b, /* 0x14c0-0x14c7 */
0x053c, 0x056c, 0x053d, 0x056d, 0x053e, 0x056e, 0x053f, 0x056f, /* 0x14c8-0x14cf */
0x0540, 0x0570, 0x0541, 0x0571, 0x0542, 0x0572, 0x0543, 0x0573, /* 0x14d0-0x14d7 */
0x0544, 0x0574, 0x0545, 0x0575, 0x0546, 0x0576, 0x0547, 0x0577, /* 0x14d8-0x14df */
0x0548, 0x0578, 0x0549, 0x0579, 0x054a, 0x057a, 0x054b, 0x057b, /* 0x14e0-0x14e7 */
0x054c, 0x057c, 0x054d, 0x057d, 0x054e, 0x057e, 0x054f, 0x057f, /* 0x14e8-0x14ef */
0x0550, 0x0580, 0x0551, 0x0581, 0x0552, 0x0582, 0x0553, 0x0583, /* 0x14f0-0x14f7 */
0x0554, 0x0584, 0x0555, 0x0585, 0x0556, 0x0586, 0x2019, 0x0027, /* 0x14f8-0x14ff */
};
/* Non existing range in keysymdef.h */
static unsigned short ucs4_15d0_15f6[] = {
0x10d0, 0x10d1, 0x10d2, 0x10d3, 0x10d4, 0x10d5, 0x10d6, 0x10d7, /* 0x15d0-0x15d7 */
0x10d8, 0x10d9, 0x10da, 0x10db, 0x10dc, 0x10dd, 0x10de, 0x10df, /* 0x15d8-0x15df */
0x10e0, 0x10e1, 0x10e2, 0x10e3, 0x10e4, 0x10e5, 0x10e6, 0x10e7, /* 0x15e0-0x15e7 */
0x10e8, 0x10e9, 0x10ea, 0x10eb, 0x10ec, 0x10ed, 0x10ee, 0x10ef, /* 0x15e8-0x15ef */
0x10f0, 0x10f1, 0x10f2, 0x10f3, 0x10f4, 0x10f5, 0x10f6 /* 0x15f0-0x15f7 */
};
/* Non existing range in keysymdef.h */
static unsigned short ucs4_16a0_16f6[] = {
0x0000, 0x0000, 0xf0a2, 0x1e8a, 0x0000, 0xf0a5, 0x012c, 0xf0a7, /* 0x16a0-0x16a7 */
0xf0a8, 0x01b5, 0x01e6, 0x0000, 0x0000, 0x0000, 0x0000, 0x019f, /* 0x16a8-0x16af */
0x0000, 0x017e, 0xf0b2, 0x1e8b, 0x01d1, 0xf0b5, 0x012d, 0xf0b7, /* 0x16b0-0x16b7 */
0xf0b8, 0x01b6, 0x01e7, 0x01d2, 0x0000, 0x0000, 0x0000, 0x0275, /* 0x16b8-0x16bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x018f, 0x0000, /* 0x16c0-0x16c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16c8-0x16cf */
0x0000, 0x1e36, 0xf0d2, 0xf0d3, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16d0-0x16d7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16d8-0x16df */
0x0000, 0x1e37, 0xf0e2, 0xf0e3, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16e0-0x16e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16e8-0x16ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0259 /* 0x16f0-0x16f6 */
};
/* Vietnamesse Mappings */
static unsigned short const ucs4_1e9f_1eff[] = {
0x0303,
0x1ea0, 0x1ea1, 0x1ea2, 0x1ea3, 0x1ea4, 0x1ea5, 0x1ea6, 0x1ea7, /* 0x1ea0-0x1ea7 */
0x1ea8, 0x1ea9, 0x1eaa, 0x1eab, 0x1eac, 0x1ead, 0x1eae, 0x1eaf, /* 0x1ea8-0x1eaf */
0x1eb0, 0x1eb1, 0x1eb2, 0x1eb3, 0x1eb4, 0x1eb5, 0x1eb6, 0x1eb7, /* 0x1eb0-0x1eb7 */
0x1eb8, 0x1eb9, 0x1eba, 0x1ebb, 0x1ebc, 0x1ebd, 0x1ebe, 0x1ebf, /* 0x1eb8-0x1ebf */
0x1ec0, 0x1ec1, 0x1ec2, 0x1ec3, 0x1ec4, 0x1ec5, 0x1ec6, 0x1ec7, /* 0x1ec0-0x1ec7 */
0x1ec8, 0x1ec9, 0x1eca, 0x1ecb, 0x1ecc, 0x1ecd, 0x1ece, 0x1ecf, /* 0x1ec8-0x1ecf */
0x1ed0, 0x1ed1, 0x1ed2, 0x1ed3, 0x1ed4, 0x1ed5, 0x1ed6, 0x1ed7, /* 0x1ed0-0x1ed7 */
0x1ed8, 0x1ed9, 0x1eda, 0x1edb, 0x1edc, 0x1edd, 0x1ede, 0x1edf, /* 0x1ed8-0x1edf */
0x1ee0, 0x1ee1, 0x1ee2, 0x1ee3, 0x1ee4, 0x1ee5, 0x1ee6, 0x1ee7, /* 0x1ee0-0x1ee7 */
0x1ee8, 0x1ee9, 0x1eea, 0x1eeb, 0x1eec, 0x1eed, 0x1eee, 0x1eef, /* 0x1ee8-0x1eef */
0x1ef0, 0x1ef1, 0x0300, 0x0301, 0x1ef4, 0x1ef5, 0x1ef6, 0x1ef7, /* 0x1ef0-0x1ef7 */
0x1ef8, 0x1ef9, 0x01a0, 0x01a1, 0x01af, 0x01b0, 0x0309, 0x0323 /* 0x1ef8-0x1eff */
};
/* Currency */
static unsigned short const ucs4_20a0_20ac[] = {
0x20a0, 0x20a1, 0x20a2, 0x20a3, 0x20a4, 0x20a5, 0x20a6, 0x20a7, /* 0x20a0-0x20a7 */
0x20a8, 0x20a9, 0x20aa, 0x20ab, 0x20ac /* 0x20a8-0x20af */
};
/* Keypad numbers mapping */
static unsigned short const ucs4_ffb0_ffb9[] = { 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36, 0x37, 0x38, 0x39};
/* Keypad operators mapping */
static unsigned short const ucs4_ffaa_ffaf[] = {
0x2a, /* Multiply */
0x2b, /* Add */
0x2c, /* Separator */
0x2d, /* Substract */
0x2e, /* Decimal */
0x2f /* Divide */
};
static unsigned short const sqSpecialKey[] = {
1, /* HOME */
28, /* LEFT */
30, /* UP */
29, /* RIGHT */
31, /* DOWN */
11, /* PRIOR (page up?) */
12, /* NEXT (page down/new page?) */
4, /* END */
1 /* HOME */
};
/* Latin-1 */
if ( (keysym >= 0x0020 && keysym <= 0x007e)
|| (keysym >= 0x00a0 && keysym <= 0x00ff)) return keysym;
/* 24-bit UCS */
if ((keysym & 0xff000000) == 0x01000000) return keysym & 0x00ffffff;
/* control keys with ASCII equivalents */
if (keysym > 0xff00 && keysym < 0xff10) return keysym & 0x001f;
if (keysym > 0xff4f && keysym < 0xff59)
{
return sqSpecialKey[keysym - 0xff50];
}
if (keysym > 0xff58 && keysym < 0xff5f) return keysym & 0x007f; /* could be return 0; */
if (keysym > 0xff94 && keysym < 0xff9d)
{
return sqSpecialKey[keysym - 0xff95];
}
if (keysym == 0xff1b) return keysym & 0x001f;
if (keysym == 0xffff) return keysym & 0x007f;
/* Misc mappings */
if (keysym == XK_Escape)
return keysym & 0x001f;
if (keysym == XK_Delete)
return keysym & 0x007f;
if (keysym == XK_KP_Equal)
return XK_equal;
/* explicitly mapped */
#define map(lo, hi) if (keysym >= 0x##lo && keysym <= 0x##hi) return ucs4_##lo##_##hi[keysym - 0x##lo];
map(01a1, 01ff); map(02a1, 02fe); map(03a2, 03fe); map(04a1, 04df);
map(0590, 05fe); map(0680, 06ff); map(07a1, 07f9); map(08a4, 08fe);
map(09df, 09f8); map(0aa1, 0afe); map(0cdf, 0cfa); map(0da1, 0df9);
map(0ea0, 0eff); map(12a1, 12fe); map(13bc, 13be); map(14a1, 14ff);
map(15d0, 15f6); map(16a0, 16f6); map(1e9f, 1eff); map(20a0, 20ac);
map(ffb0, ffb9);
map(ffaa, ffaf);
#undef map
#if defined(XF86XK_Start)
if (keysym == XF86XK_Start) /* OLPC view source */
{
modifierState |= CommandKeyBit;
return ',';
}
#endif
/* convert to chinese char noe-qwan-doo */
return 0;
}
static int x2sqButton(int button)
{
/* ASSUME: (button >= 1) & (button <= 3) */
static int rybMap[4]= { 0, RedButtonBit, YellowButtonBit, BlueButtonBit };
static int rbyMap[4]= { 0, RedButtonBit, BlueButtonBit, YellowButtonBit };
return (swapBtn ? rbyMap : rybMap)[button];
}
static int x2sqModifier(int state)
{
int mods= 0;
if (optMapIndex || cmdMapIndex)
{
int shift= 1 & (state >> ShiftMapIndex);
int ctrl= 1 & (state >> ControlMapIndex);
int cmd= 1 & (state >> cmdMapIndex);
int opt= 1 & (state >> optMapIndex);
mods= (shift ? ShiftKeyBit : 0)
| (ctrl ? CtrlKeyBit : 0)
| (cmd ? CommandKeyBit : 0)
| (opt ? OptionKeyBit : 0);
# if DEBUG_KEYBOARD_EVENTS || DEBUG_MOUSE_EVENTS
fprintf(stderr, "X mod %x -> Sq mod %x (extended opt=%d cmd=%d)\n", state, mods,
optMapIndex, cmdMapIndex);
# endif
}
else
{
enum { _= 0, S= ShiftKeyBit, C= CtrlKeyBit, O= OptionKeyBit, M= CommandKeyBit };
static char midofiers[32]= { /* ALT=Cmd, META=ignored, C-ALT=Opt, META=ignored */
/* - - - S L - L S */
/* - - - - */ _|_|_|_, _|_|_|S, _|_|_|_, _|_|_|S,
/* - - - C */ _|_|C|_, _|_|C|S, _|_|C|_, _|_|C|S,
/* - - A - */ _|M|_|_, _|M|_|S, _|M|_|_, _|M|_|S,
/* - - A C */ O|_|_|_, O|_|_|S, O|_|_|_, O|_|_|S,
/* - - - S L - L S */
/* M - - - */ _|M|_|_, _|M|_|S, _|M|_|_, _|M|_|S,
/* M - - C */ _|M|C|_, _|M|C|S, _|M|C|_, _|M|C|S,
/* M - A - */ _|M|_|_, _|M|_|S, _|M|_|_, _|M|_|S,
/* M - A C */ O|_|_|_, O|M|_|S, O|M|_|_, O|M|_|S,
};
# if defined(__POWERPC__) || defined(__ppc__)
mods= midofiers[state & 0x1f];
# else
mods= midofiers[state & 0x0f];
# endif
# if DEBUG_KEYBOARD_EVENTS || DEBUG_MOUSE_EVENTS
if (mods)
fprintf(stderr, "X mod %x -> Sq mod %x (default)\n", state & 0xf, mods);
# endif
}
return mods;
}
/* wait for pending completion events to arrive */
static void waitForCompletions(void)
{
#if defined(USE_XSHM)
while (completions > 0)
handleEvents();
#endif
}
#include "sqUnixXdnd.c"
/* Answers the available types (like "image/png") in XdndSelection or
* CLIPBOARD as a NULL-terminated array of strings, or 0 on error.
* The caller must free() the returned array.
*/
static char **display_clipboardGetTypeNames(void)
{
Atom *targets= NULL;
size_t bytes= 0;
char **typeNames= NULL;
Status success= 0;
int nTypeNames= 0;
if (dndAvailable())
dndGetTargets(&targets, &nTypeNames);
else
{
if (stOwnsClipboard) return 0;
targets= (Atom *)getSelectionData(xaClipboard, xaTargets, &bytes);
if (0 == bytes) return 0;
nTypeNames= bytes / sizeof(Atom);
}
typeNames= calloc(nTypeNames + 1, sizeof(char *));
if (!XGetAtomNames(stDisplay, targets, nTypeNames, typeNames)) return 0;
typeNames[nTypeNames]= 0;
return typeNames;
}
/* Read the clipboard data associated with the typeName to
* stPrimarySelection. Answer the size of the data.
*/
static sqInt display_clipboardSizeWithType(char *typeName, int nTypeName)
{
size_t bytes;
Atom type;
int isDnd= 0;
Atom inputSelection;
SelectionChunk *chunk;
isDnd= dndAvailable();
inputSelection= isDnd ? xaXdndSelection : xaClipboard;
if ((!isDnd) && stOwnsClipboard) return 0;
chunk= newSelectionChunk();
type= stringToAtom(typeName, nTypeName);
getSelectionChunk(chunk, inputSelection, type);
bytes= sizeSelectionChunk(chunk);
allocateSelectionBuffer(bytes);
copySelectionChunk(chunk, stPrimarySelection);
destroySelectionChunk(chunk);
if (isDnd) dndHandleEvent(DndInFinished, 0);
return stPrimarySelectionSize;
}
#if DEBUG_KEYBOARD_EVENTS
/*
grep '^#[ ]*define[ ][ ]*XK_.*0x[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][^0-9a-fA-F]' /usr/include/X11/*.h | sed 's/^.*\(XK_[^ ]*\)[ ]*\(0x[0-9a-fA-F]*\).*$/{ "\1", \2 }, /'
*/
typedef struct { char *name; int code; } KeyNameEntry;
static KeyNameEntry codes[] = {
{ "XK_BackSpace", 0xff08 },
{ "XK_Linefeed", 0xff0a },
{ "XK_Return", 0xff0d },
{ "XK_Pause", 0xff13 },
{ "XK_Delete", 0xffff },
{ "XK_Multi_key", 0xff20 },
{ "XK_Kanji", 0xff21 },
{ "XK_Muhenkan", 0xff22 },
{ "XK_Henkan_Mode", 0xff23 },
{ "XK_Henkan", 0xff23 },
{ "XK_Romaji", 0xff24 },
{ "XK_Hiragana", 0xff25 },
{ "XK_Katakana", 0xff26 },
{ "XK_Hiragana_Katakana", 0xff27 },
{ "XK_Zenkaku", 0xff28 },
{ "XK_Hankaku", 0xff29 },
{ "XK_Zenkaku_Hankaku", 0xff2a },
{ "XK_Touroku", 0xff2b },
{ "XK_Massyo", 0xff2c },
{ "XK_Kana_Lock", 0xff2d },
{ "XK_Kana_Shift", 0xff2e },
{ "XK_Eisu_Shift", 0xff2f },
{ "XK_Eisu_toggle", 0xff30 },
{ "XK_Kanji_Bangou", 0xff37 },
{ "XK_Zen_Koho", 0xff3d },
{ "XK_Mae_Koho", 0xff3e },
{ "XK_Left", 0xff51 },
{ "XK_Up", 0xff52 },
{ "XK_Right", 0xff53 },
{ "XK_Down", 0xff54 },
{ "XK_Prior", 0xff55 },
{ "XK_Next", 0xff56 },
{ "XK_End", 0xff57 },
{ "XK_Begin", 0xff58 },
{ "XK_Select", 0xff60 },
{ "XK_Execute", 0xff62 },
{ "XK_Insert", 0xff63 },
{ "XK_Redo", 0xff66 },
{ "XK_Find", 0xff68 },
{ "XK_Cancel", 0xff69 },
{ "XK_Help", 0xff6a },
{ "XK_Mode_switch", 0xff7e },
{ "XK_script_switch", 0xff7e },
{ "XK_KP_Space", 0xff80 },
{ "XK_KP_Enter", 0xff8d },
{ "XK_KP_F1", 0xff91 },
{ "XK_KP_Equal", 0xffbd },
{ "XK_KP_Separator", 0xffac },
{ "XK_Shift_L", 0xffe1 },
{ "XK_Shift_R", 0xffe2 },
{ "XK_Control_L", 0xffe3 },
{ "XK_Control_R", 0xffe4 },
{ "XK_Caps_Lock", 0xffe5 },
{ "XK_Shift_Lock", 0xffe6 },
{ "XK_Meta_L", 0xffe7 },
{ "XK_Meta_R", 0xffe8 },
{ "XK_Alt_L", 0xffe9 },
{ "XK_Alt_R", 0xffea },
{ "XK_Super_L", 0xffeb },
{ "XK_Super_R", 0xffec },
{ "XK_Hyper_L", 0xffed },
{ "XK_Hyper_R", 0xffee },
{ "XK_ISO_Group_Shift", 0xff7e },
{ "XK_space", 0x0020 },
{ "XK_exclam", 0x0021 },
{ "XK_quotedbl", 0x0022 },
{ "XK_numbersign", 0x0023 },
{ "XK_dollar", 0x0024 },
{ "XK_percent", 0x0025 },
{ "XK_ampersand", 0x0026 },
{ "XK_apostrophe", 0x0027 },
{ "XK_quoteright", 0x0027 },
{ "XK_parenleft", 0x0028 },
{ "XK_parenright", 0x0029 },
{ "XK_asterisk", 0x002a },
{ "XK_plus", 0x002b },
{ "XK_comma", 0x002c },
{ "XK_minus", 0x002d },
{ "XK_period", 0x002e },
{ "XK_slash", 0x002f },
{ "XK_0", 0x0030 },
{ "XK_1", 0x0031 },
{ "XK_2", 0x0032 },
{ "XK_3", 0x0033 },
{ "XK_4", 0x0034 },
{ "XK_5", 0x0035 },
{ "XK_6", 0x0036 },
{ "XK_7", 0x0037 },
{ "XK_8", 0x0038 },
{ "XK_9", 0x0039 },
{ "XK_colon", 0x003a },
{ "XK_semicolon", 0x003b },
{ "XK_less", 0x003c },
{ "XK_equal", 0x003d },
{ "XK_greater", 0x003e },
{ "XK_question", 0x003f },
{ "XK_at", 0x0040 },
{ "XK_A", 0x0041 },
{ "XK_B", 0x0042 },
{ "XK_C", 0x0043 },
{ "XK_D", 0x0044 },
{ "XK_E", 0x0045 },
{ "XK_F", 0x0046 },
{ "XK_G", 0x0047 },
{ "XK_H", 0x0048 },
{ "XK_I", 0x0049 },
{ "XK_J", 0x004a },
{ "XK_K", 0x004b },
{ "XK_L", 0x004c },
{ "XK_M", 0x004d },
{ "XK_N", 0x004e },
{ "XK_O", 0x004f },
{ "XK_P", 0x0050 },
{ "XK_Q", 0x0051 },
{ "XK_R", 0x0052 },
{ "XK_S", 0x0053 },
{ "XK_T", 0x0054 },
{ "XK_U", 0x0055 },
{ "XK_V", 0x0056 },
{ "XK_W", 0x0057 },
{ "XK_X", 0x0058 },
{ "XK_Y", 0x0059 },
{ "XK_Z", 0x005a },
{ "XK_bracketleft", 0x005b },
{ "XK_backslash", 0x005c },
{ "XK_bracketright", 0x005d },
{ "XK_asciicircum", 0x005e },
{ "XK_underscore", 0x005f },
{ "XK_grave", 0x0060 },
{ "XK_quoteleft", 0x0060 },
{ "XK_a", 0x0061 },
{ "XK_b", 0x0062 },
{ "XK_c", 0x0063 },
{ "XK_d", 0x0064 },
{ "XK_e", 0x0065 },
{ "XK_f", 0x0066 },
{ "XK_g", 0x0067 },
{ "XK_h", 0x0068 },
{ "XK_i", 0x0069 },
{ "XK_j", 0x006a },
{ "XK_k", 0x006b },
{ "XK_l", 0x006c },
{ "XK_m", 0x006d },
{ "XK_n", 0x006e },
{ "XK_o", 0x006f },
{ "XK_p", 0x0070 },
{ "XK_q", 0x0071 },
{ "XK_r", 0x0072 },
{ "XK_s", 0x0073 },
{ "XK_t", 0x0074 },
{ "XK_u", 0x0075 },
{ "XK_v", 0x0076 },
{ "XK_w", 0x0077 },
{ "XK_x", 0x0078 },
{ "XK_y", 0x0079 },
{ "XK_z", 0x007a },
{ "XK_braceleft", 0x007b },
{ "XK_bar", 0x007c },
{ "XK_braceright", 0x007d },
{ "XK_asciitilde", 0x007e },
{ "XK_nobreakspace", 0x00a0 },
{ "XK_exclamdown", 0x00a1 },
{ "XK_cent", 0x00a2 },
{ "XK_sterling", 0x00a3 },
{ "XK_currency", 0x00a4 },
{ "XK_yen", 0x00a5 },
{ "XK_brokenbar", 0x00a6 },
{ "XK_section", 0x00a7 },
{ "XK_diaeresis", 0x00a8 },
{ "XK_copyright", 0x00a9 },
{ "XK_ordfeminine", 0x00aa },
{ "XK_guillemotleft", 0x00ab },
{ "XK_notsign", 0x00ac },
{ "XK_hyphen", 0x00ad },
{ "XK_registered", 0x00ae },
{ "XK_macron", 0x00af },
{ "XK_degree", 0x00b0 },
{ "XK_plusminus", 0x00b1 },
{ "XK_twosuperior", 0x00b2 },
{ "XK_threesuperior", 0x00b3 },
{ "XK_acute", 0x00b4 },
{ "XK_mu", 0x00b5 },
{ "XK_paragraph", 0x00b6 },
{ "XK_periodcentered", 0x00b7 },
{ "XK_cedilla", 0x00b8 },
{ "XK_onesuperior", 0x00b9 },
{ "XK_masculine", 0x00ba },
{ "XK_guillemotright", 0x00bb },
{ "XK_onequarter", 0x00bc },
{ "XK_onehalf", 0x00bd },
{ "XK_threequarters", 0x00be },
{ "XK_questiondown", 0x00bf },
{ "XK_Agrave", 0x00c0 },
{ "XK_Aacute", 0x00c1 },
{ "XK_Acircumflex", 0x00c2 },
{ "XK_Atilde", 0x00c3 },
{ "XK_Adiaeresis", 0x00c4 },
{ "XK_Aring", 0x00c5 },
{ "XK_AE", 0x00c6 },
{ "XK_Ccedilla", 0x00c7 },
{ "XK_Egrave", 0x00c8 },
{ "XK_Eacute", 0x00c9 },
{ "XK_Ecircumflex", 0x00ca },
{ "XK_Ediaeresis", 0x00cb },
{ "XK_Igrave", 0x00cc },
{ "XK_Iacute", 0x00cd },
{ "XK_Icircumflex", 0x00ce },
{ "XK_Idiaeresis", 0x00cf },
{ "XK_ETH", 0x00d0 },
{ "XK_Eth", 0x00d0 },
{ "XK_Ntilde", 0x00d1 },
{ "XK_Ograve", 0x00d2 },
{ "XK_Oacute", 0x00d3 },
{ "XK_Ocircumflex", 0x00d4 },
{ "XK_Otilde", 0x00d5 },
{ "XK_Odiaeresis", 0x00d6 },
{ "XK_multiply", 0x00d7 },
{ "XK_Oslash", 0x00d8 },
{ "XK_Ooblique", 0x00d8 },
{ "XK_Ugrave", 0x00d9 },
{ "XK_Uacute", 0x00da },
{ "XK_Ucircumflex", 0x00db },
{ "XK_Udiaeresis", 0x00dc },
{ "XK_Yacute", 0x00dd },
{ "XK_THORN", 0x00de },
{ "XK_Thorn", 0x00de },
{ "XK_ssharp", 0x00df },
{ "XK_agrave", 0x00e0 },
{ "XK_aacute", 0x00e1 },
{ "XK_acircumflex", 0x00e2 },
{ "XK_atilde", 0x00e3 },
{ "XK_adiaeresis", 0x00e4 },
{ "XK_aring", 0x00e5 },
{ "XK_ae", 0x00e6 },
{ "XK_ccedilla", 0x00e7 },
{ "XK_egrave", 0x00e8 },
{ "XK_eacute", 0x00e9 },
{ "XK_ecircumflex", 0x00ea },
{ "XK_ediaeresis", 0x00eb },
{ "XK_igrave", 0x00ec },
{ "XK_iacute", 0x00ed },
{ "XK_icircumflex", 0x00ee },
{ "XK_idiaeresis", 0x00ef },
{ "XK_eth", 0x00f0 },
{ "XK_ntilde", 0x00f1 },
{ "XK_ograve", 0x00f2 },
{ "XK_oacute", 0x00f3 },
{ "XK_ocircumflex", 0x00f4 },
{ "XK_otilde", 0x00f5 },
{ "XK_odiaeresis", 0x00f6 },
{ "XK_division", 0x00f7 },
{ "XK_oslash", 0x00f8 },
{ "XK_ooblique", 0x00f8 },
{ "XK_ugrave", 0x00f9 },
{ "XK_uacute", 0x00fa },
{ "XK_ucircumflex", 0x00fb },
{ "XK_udiaeresis", 0x00fc },
{ "XK_yacute", 0x00fd },
{ "XK_thorn", 0x00fe },
{ "XK_ydiaeresis", 0x00ff },
{ "XK_Aogonek", 0x01a1 },
{ "XK_breve", 0x01a2 },
{ "XK_Lstroke", 0x01a3 },
{ "XK_Lcaron", 0x01a5 },
{ "XK_Sacute", 0x01a6 },
{ "XK_Scaron", 0x01a9 },
{ "XK_Scedilla", 0x01aa },
{ "XK_Tcaron", 0x01ab },
{ "XK_Zacute", 0x01ac },
{ "XK_Zcaron", 0x01ae },
{ "XK_Zabovedot", 0x01af },
{ "XK_aogonek", 0x01b1 },
{ "XK_ogonek", 0x01b2 },
{ "XK_lstroke", 0x01b3 },
{ "XK_lcaron", 0x01b5 },
{ "XK_sacute", 0x01b6 },
{ "XK_caron", 0x01b7 },
{ "XK_scaron", 0x01b9 },
{ "XK_scedilla", 0x01ba },
{ "XK_tcaron", 0x01bb },
{ "XK_zacute", 0x01bc },
{ "XK_doubleacute", 0x01bd },
{ "XK_zcaron", 0x01be },
{ "XK_zabovedot", 0x01bf },
{ "XK_Racute", 0x01c0 },
{ "XK_Abreve", 0x01c3 },
{ "XK_Lacute", 0x01c5 },
{ "XK_Cacute", 0x01c6 },
{ "XK_Ccaron", 0x01c8 },
{ "XK_Eogonek", 0x01ca },
{ "XK_Ecaron", 0x01cc },
{ "XK_Dcaron", 0x01cf },
{ "XK_Dstroke", 0x01d0 },
{ "XK_Nacute", 0x01d1 },
{ "XK_Ncaron", 0x01d2 },
{ "XK_Odoubleacute", 0x01d5 },
{ "XK_Rcaron", 0x01d8 },
{ "XK_Uring", 0x01d9 },
{ "XK_Udoubleacute", 0x01db },
{ "XK_Tcedilla", 0x01de },
{ "XK_racute", 0x01e0 },
{ "XK_abreve", 0x01e3 },
{ "XK_lacute", 0x01e5 },
{ "XK_cacute", 0x01e6 },
{ "XK_ccaron", 0x01e8 },
{ "XK_eogonek", 0x01ea },
{ "XK_ecaron", 0x01ec },
{ "XK_dcaron", 0x01ef },
{ "XK_dstroke", 0x01f0 },
{ "XK_nacute", 0x01f1 },
{ "XK_ncaron", 0x01f2 },
{ "XK_odoubleacute", 0x01f5 },
{ "XK_udoubleacute", 0x01fb },
{ "XK_rcaron", 0x01f8 },
{ "XK_uring", 0x01f9 },
{ "XK_tcedilla", 0x01fe },
{ "XK_abovedot", 0x01ff },
{ "XK_Hstroke", 0x02a1 },
{ "XK_Hcircumflex", 0x02a6 },
{ "XK_Iabovedot", 0x02a9 },
{ "XK_Gbreve", 0x02ab },
{ "XK_Jcircumflex", 0x02ac },
{ "XK_hstroke", 0x02b1 },
{ "XK_hcircumflex", 0x02b6 },
{ "XK_idotless", 0x02b9 },
{ "XK_gbreve", 0x02bb },
{ "XK_jcircumflex", 0x02bc },
{ "XK_Cabovedot", 0x02c5 },
{ "XK_Ccircumflex", 0x02c6 },
{ "XK_Gabovedot", 0x02d5 },
{ "XK_Gcircumflex", 0x02d8 },
{ "XK_Ubreve", 0x02dd },
{ "XK_Scircumflex", 0x02de },
{ "XK_cabovedot", 0x02e5 },
{ "XK_ccircumflex", 0x02e6 },
{ "XK_gabovedot", 0x02f5 },
{ "XK_gcircumflex", 0x02f8 },
{ "XK_ubreve", 0x02fd },
{ "XK_scircumflex", 0x02fe },
{ "XK_kra", 0x03a2 },
{ "XK_kappa", 0x03a2 },
{ "XK_Rcedilla", 0x03a3 },
{ "XK_Itilde", 0x03a5 },
{ "XK_Lcedilla", 0x03a6 },
{ "XK_Emacron", 0x03aa },
{ "XK_Gcedilla", 0x03ab },
{ "XK_Tslash", 0x03ac },
{ "XK_rcedilla", 0x03b3 },
{ "XK_itilde", 0x03b5 },
{ "XK_lcedilla", 0x03b6 },
{ "XK_emacron", 0x03ba },
{ "XK_gcedilla", 0x03bb },
{ "XK_tslash", 0x03bc },
{ "XK_ENG", 0x03bd },
{ "XK_eng", 0x03bf },
{ "XK_Amacron", 0x03c0 },
{ "XK_Iogonek", 0x03c7 },
{ "XK_Eabovedot", 0x03cc },
{ "XK_Imacron", 0x03cf },
{ "XK_Ncedilla", 0x03d1 },
{ "XK_Omacron", 0x03d2 },
{ "XK_Kcedilla", 0x03d3 },
{ "XK_Uogonek", 0x03d9 },
{ "XK_Utilde", 0x03dd },
{ "XK_Umacron", 0x03de },
{ "XK_amacron", 0x03e0 },
{ "XK_iogonek", 0x03e7 },
{ "XK_eabovedot", 0x03ec },
{ "XK_imacron", 0x03ef },
{ "XK_ncedilla", 0x03f1 },
{ "XK_omacron", 0x03f2 },
{ "XK_kcedilla", 0x03f3 },
{ "XK_uogonek", 0x03f9 },
{ "XK_utilde", 0x03fd },
{ "XK_umacron", 0x03fe },
{ "XK_OE", 0x13bc },
{ "XK_oe", 0x13bd },
{ "XK_Ydiaeresis", 0x13be },
{ "XK_overline", 0x047e },
{ "XK_kana_fullstop", 0x04a1 },
{ "XK_kana_openingbracket", 0x04a2 },
{ "XK_kana_closingbracket", 0x04a3 },
{ "XK_kana_comma", 0x04a4 },
{ "XK_kana_conjunctive", 0x04a5 },
{ "XK_kana_middledot", 0x04a5 },
{ "XK_kana_WO", 0x04a6 },
{ "XK_kana_a", 0x04a7 },
{ "XK_kana_i", 0x04a8 },
{ "XK_kana_u", 0x04a9 },
{ "XK_kana_e", 0x04aa },
{ "XK_kana_o", 0x04ab },
{ "XK_kana_ya", 0x04ac },
{ "XK_kana_yu", 0x04ad },
{ "XK_kana_yo", 0x04ae },
{ "XK_kana_tsu", 0x04af },
{ "XK_kana_tu", 0x04af },
{ "XK_prolongedsound", 0x04b0 },
{ "XK_kana_A", 0x04b1 },
{ "XK_kana_I", 0x04b2 },
{ "XK_kana_U", 0x04b3 },
{ "XK_kana_E", 0x04b4 },
{ "XK_kana_O", 0x04b5 },
{ "XK_kana_KA", 0x04b6 },
{ "XK_kana_KI", 0x04b7 },
{ "XK_kana_KU", 0x04b8 },
{ "XK_kana_KE", 0x04b9 },
{ "XK_kana_KO", 0x04ba },
{ "XK_kana_SA", 0x04bb },
{ "XK_kana_SHI", 0x04bc },
{ "XK_kana_SU", 0x04bd },
{ "XK_kana_SE", 0x04be },
{ "XK_kana_SO", 0x04bf },
{ "XK_kana_TA", 0x04c0 },
{ "XK_kana_CHI", 0x04c1 },
{ "XK_kana_TI", 0x04c1 },
{ "XK_kana_TSU", 0x04c2 },
{ "XK_kana_TU", 0x04c2 },
{ "XK_kana_TE", 0x04c3 },
{ "XK_kana_TO", 0x04c4 },
{ "XK_kana_NA", 0x04c5 },
{ "XK_kana_NI", 0x04c6 },
{ "XK_kana_NU", 0x04c7 },
{ "XK_kana_NE", 0x04c8 },
{ "XK_kana_NO", 0x04c9 },
{ "XK_kana_HA", 0x04ca },
{ "XK_kana_HI", 0x04cb },
{ "XK_kana_FU", 0x04cc },
{ "XK_kana_HU", 0x04cc },
{ "XK_kana_HE", 0x04cd },
{ "XK_kana_HO", 0x04ce },
{ "XK_kana_MA", 0x04cf },
{ "XK_kana_MI", 0x04d0 },
{ "XK_kana_MU", 0x04d1 },
{ "XK_kana_ME", 0x04d2 },
{ "XK_kana_MO", 0x04d3 },
{ "XK_kana_YA", 0x04d4 },
{ "XK_kana_YU", 0x04d5 },
{ "XK_kana_YO", 0x04d6 },
{ "XK_kana_RA", 0x04d7 },
{ "XK_kana_RI", 0x04d8 },
{ "XK_kana_RU", 0x04d9 },
{ "XK_kana_RE", 0x04da },
{ "XK_kana_RO", 0x04db },
{ "XK_kana_WA", 0x04dc },
{ "XK_kana_N", 0x04dd },
{ "XK_voicedsound", 0x04de },
{ "XK_semivoicedsound", 0x04df },
{ "XK_kana_switch", 0xff7e },
{ "XK_Arabic_comma", 0x05ac },
{ "XK_Arabic_semicolon", 0x05bb },
{ "XK_Arabic_question_mark", 0x05bf },
{ "XK_Arabic_hamza", 0x05c1 },
{ "XK_Arabic_maddaonalef", 0x05c2 },
{ "XK_Arabic_hamzaonalef", 0x05c3 },
{ "XK_Arabic_hamzaonwaw", 0x05c4 },
{ "XK_Arabic_hamzaunderalef", 0x05c5 },
{ "XK_Arabic_hamzaonyeh", 0x05c6 },
{ "XK_Arabic_alef", 0x05c7 },
{ "XK_Arabic_beh", 0x05c8 },
{ "XK_Arabic_tehmarbuta", 0x05c9 },
{ "XK_Arabic_teh", 0x05ca },
{ "XK_Arabic_theh", 0x05cb },
{ "XK_Arabic_jeem", 0x05cc },
{ "XK_Arabic_hah", 0x05cd },
{ "XK_Arabic_khah", 0x05ce },
{ "XK_Arabic_dal", 0x05cf },
{ "XK_Arabic_thal", 0x05d0 },
{ "XK_Arabic_ra", 0x05d1 },
{ "XK_Arabic_zain", 0x05d2 },
{ "XK_Arabic_seen", 0x05d3 },
{ "XK_Arabic_sheen", 0x05d4 },
{ "XK_Arabic_sad", 0x05d5 },
{ "XK_Arabic_dad", 0x05d6 },
{ "XK_Arabic_tah", 0x05d7 },
{ "XK_Arabic_zah", 0x05d8 },
{ "XK_Arabic_ain", 0x05d9 },
{ "XK_Arabic_ghain", 0x05da },
{ "XK_Arabic_tatweel", 0x05e0 },
{ "XK_Arabic_feh", 0x05e1 },
{ "XK_Arabic_qaf", 0x05e2 },
{ "XK_Arabic_kaf", 0x05e3 },
{ "XK_Arabic_lam", 0x05e4 },
{ "XK_Arabic_meem", 0x05e5 },
{ "XK_Arabic_noon", 0x05e6 },
{ "XK_Arabic_ha", 0x05e7 },
{ "XK_Arabic_heh", 0x05e7 },
{ "XK_Arabic_waw", 0x05e8 },
{ "XK_Arabic_alefmaksura", 0x05e9 },
{ "XK_Arabic_yeh", 0x05ea },
{ "XK_Arabic_fathatan", 0x05eb },
{ "XK_Arabic_dammatan", 0x05ec },
{ "XK_Arabic_kasratan", 0x05ed },
{ "XK_Arabic_fatha", 0x05ee },
{ "XK_Arabic_damma", 0x05ef },
{ "XK_Arabic_kasra", 0x05f0 },
{ "XK_Arabic_shadda", 0x05f1 },
{ "XK_Arabic_sukun", 0x05f2 },
{ "XK_Arabic_switch", 0xff7e },
{ "XK_Serbian_dje", 0x06a1 },
{ "XK_Macedonia_gje", 0x06a2 },
{ "XK_Cyrillic_io", 0x06a3 },
{ "XK_Ukrainian_ie", 0x06a4 },
{ "XK_Ukranian_je", 0x06a4 },
{ "XK_Macedonia_dse", 0x06a5 },
{ "XK_Ukrainian_i", 0x06a6 },
{ "XK_Ukranian_i", 0x06a6 },
{ "XK_Ukrainian_yi", 0x06a7 },
{ "XK_Ukranian_yi", 0x06a7 },
{ "XK_Cyrillic_je", 0x06a8 },
{ "XK_Serbian_je", 0x06a8 },
{ "XK_Cyrillic_lje", 0x06a9 },
{ "XK_Serbian_lje", 0x06a9 },
{ "XK_Cyrillic_nje", 0x06aa },
{ "XK_Serbian_nje", 0x06aa },
{ "XK_Serbian_tshe", 0x06ab },
{ "XK_Macedonia_kje", 0x06ac },
{ "XK_Ukrainian_ghe_with_upturn", 0x06ad },
{ "XK_Byelorussian_shortu", 0x06ae },
{ "XK_Cyrillic_dzhe", 0x06af },
{ "XK_Serbian_dze", 0x06af },
{ "XK_numerosign", 0x06b0 },
{ "XK_Serbian_DJE", 0x06b1 },
{ "XK_Macedonia_GJE", 0x06b2 },
{ "XK_Cyrillic_IO", 0x06b3 },
{ "XK_Ukrainian_IE", 0x06b4 },
{ "XK_Ukranian_JE", 0x06b4 },
{ "XK_Macedonia_DSE", 0x06b5 },
{ "XK_Ukrainian_I", 0x06b6 },
{ "XK_Ukranian_I", 0x06b6 },
{ "XK_Ukrainian_YI", 0x06b7 },
{ "XK_Ukranian_YI", 0x06b7 },
{ "XK_Cyrillic_JE", 0x06b8 },
{ "XK_Serbian_JE", 0x06b8 },
{ "XK_Cyrillic_LJE", 0x06b9 },
{ "XK_Serbian_LJE", 0x06b9 },
{ "XK_Cyrillic_NJE", 0x06ba },
{ "XK_Serbian_NJE", 0x06ba },
{ "XK_Serbian_TSHE", 0x06bb },
{ "XK_Macedonia_KJE", 0x06bc },
{ "XK_Ukrainian_GHE_WITH_UPTURN", 0x06bd },
{ "XK_Byelorussian_SHORTU", 0x06be },
{ "XK_Cyrillic_DZHE", 0x06bf },
{ "XK_Serbian_DZE", 0x06bf },
{ "XK_Cyrillic_yu", 0x06c0 },
{ "XK_Cyrillic_a", 0x06c1 },
{ "XK_Cyrillic_be", 0x06c2 },
{ "XK_Cyrillic_tse", 0x06c3 },
{ "XK_Cyrillic_de", 0x06c4 },
{ "XK_Cyrillic_ie", 0x06c5 },
{ "XK_Cyrillic_ef", 0x06c6 },
{ "XK_Cyrillic_ghe", 0x06c7 },
{ "XK_Cyrillic_ha", 0x06c8 },
{ "XK_Cyrillic_i", 0x06c9 },
{ "XK_Cyrillic_shorti", 0x06ca },
{ "XK_Cyrillic_ka", 0x06cb },
{ "XK_Cyrillic_el", 0x06cc },
{ "XK_Cyrillic_em", 0x06cd },
{ "XK_Cyrillic_en", 0x06ce },
{ "XK_Cyrillic_o", 0x06cf },
{ "XK_Cyrillic_pe", 0x06d0 },
{ "XK_Cyrillic_ya", 0x06d1 },
{ "XK_Cyrillic_er", 0x06d2 },
{ "XK_Cyrillic_es", 0x06d3 },
{ "XK_Cyrillic_te", 0x06d4 },
{ "XK_Cyrillic_u", 0x06d5 },
{ "XK_Cyrillic_zhe", 0x06d6 },
{ "XK_Cyrillic_ve", 0x06d7 },
{ "XK_Cyrillic_softsign", 0x06d8 },
{ "XK_Cyrillic_yeru", 0x06d9 },
{ "XK_Cyrillic_ze", 0x06da },
{ "XK_Cyrillic_sha", 0x06db },
{ "XK_Cyrillic_e", 0x06dc },
{ "XK_Cyrillic_shcha", 0x06dd },
{ "XK_Cyrillic_che", 0x06de },
{ "XK_Cyrillic_hardsign", 0x06df },
{ "XK_Cyrillic_YU", 0x06e0 },
{ "XK_Cyrillic_A", 0x06e1 },
{ "XK_Cyrillic_BE", 0x06e2 },
{ "XK_Cyrillic_TSE", 0x06e3 },
{ "XK_Cyrillic_DE", 0x06e4 },
{ "XK_Cyrillic_IE", 0x06e5 },
{ "XK_Cyrillic_EF", 0x06e6 },
{ "XK_Cyrillic_GHE", 0x06e7 },
{ "XK_Cyrillic_HA", 0x06e8 },
{ "XK_Cyrillic_I", 0x06e9 },
{ "XK_Cyrillic_SHORTI", 0x06ea },
{ "XK_Cyrillic_KA", 0x06eb },
{ "XK_Cyrillic_EL", 0x06ec },
{ "XK_Cyrillic_EM", 0x06ed },
{ "XK_Cyrillic_EN", 0x06ee },
{ "XK_Cyrillic_O", 0x06ef },
{ "XK_Cyrillic_PE", 0x06f0 },
{ "XK_Cyrillic_YA", 0x06f1 },
{ "XK_Cyrillic_ER", 0x06f2 },
{ "XK_Cyrillic_ES", 0x06f3 },
{ "XK_Cyrillic_TE", 0x06f4 },
{ "XK_Cyrillic_U", 0x06f5 },
{ "XK_Cyrillic_ZHE", 0x06f6 },
{ "XK_Cyrillic_VE", 0x06f7 },
{ "XK_Cyrillic_SOFTSIGN", 0x06f8 },
{ "XK_Cyrillic_YERU", 0x06f9 },
{ "XK_Cyrillic_ZE", 0x06fa },
{ "XK_Cyrillic_SHA", 0x06fb },
{ "XK_Cyrillic_E", 0x06fc },
{ "XK_Cyrillic_SHCHA", 0x06fd },
{ "XK_Cyrillic_CHE", 0x06fe },
{ "XK_Cyrillic_HARDSIGN", 0x06ff },
{ "XK_Greek_ALPHAaccent", 0x07a1 },
{ "XK_Greek_EPSILONaccent", 0x07a2 },
{ "XK_Greek_ETAaccent", 0x07a3 },
{ "XK_Greek_IOTAaccent", 0x07a4 },
{ "XK_Greek_IOTAdieresis", 0x07a5 },
{ "XK_Greek_IOTAdiaeresis", 0x07a5 },
{ "XK_Greek_OMICRONaccent", 0x07a7 },
{ "XK_Greek_UPSILONaccent", 0x07a8 },
{ "XK_Greek_UPSILONdieresis", 0x07a9 },
{ "XK_Greek_OMEGAaccent", 0x07ab },
{ "XK_Greek_accentdieresis", 0x07ae },
{ "XK_Greek_horizbar", 0x07af },
{ "XK_Greek_alphaaccent", 0x07b1 },
{ "XK_Greek_epsilonaccent", 0x07b2 },
{ "XK_Greek_etaaccent", 0x07b3 },
{ "XK_Greek_iotaaccent", 0x07b4 },
{ "XK_Greek_iotadieresis", 0x07b5 },
{ "XK_Greek_iotaaccentdieresis", 0x07b6 },
{ "XK_Greek_omicronaccent", 0x07b7 },
{ "XK_Greek_upsilonaccent", 0x07b8 },
{ "XK_Greek_upsilondieresis", 0x07b9 },
{ "XK_Greek_upsilonaccentdieresis", 0x07ba },
{ "XK_Greek_omegaaccent", 0x07bb },
{ "XK_Greek_ALPHA", 0x07c1 },
{ "XK_Greek_BETA", 0x07c2 },
{ "XK_Greek_GAMMA", 0x07c3 },
{ "XK_Greek_DELTA", 0x07c4 },
{ "XK_Greek_EPSILON", 0x07c5 },
{ "XK_Greek_ZETA", 0x07c6 },
{ "XK_Greek_ETA", 0x07c7 },
{ "XK_Greek_THETA", 0x07c8 },
{ "XK_Greek_IOTA", 0x07c9 },
{ "XK_Greek_KAPPA", 0x07ca },
{ "XK_Greek_LAMDA", 0x07cb },
{ "XK_Greek_LAMBDA", 0x07cb },
{ "XK_Greek_MU", 0x07cc },
{ "XK_Greek_NU", 0x07cd },
{ "XK_Greek_XI", 0x07ce },
{ "XK_Greek_OMICRON", 0x07cf },
{ "XK_Greek_PI", 0x07d0 },
{ "XK_Greek_RHO", 0x07d1 },
{ "XK_Greek_SIGMA", 0x07d2 },
{ "XK_Greek_TAU", 0x07d4 },
{ "XK_Greek_UPSILON", 0x07d5 },
{ "XK_Greek_PHI", 0x07d6 },
{ "XK_Greek_CHI", 0x07d7 },
{ "XK_Greek_PSI", 0x07d8 },
{ "XK_Greek_OMEGA", 0x07d9 },
{ "XK_Greek_alpha", 0x07e1 },
{ "XK_Greek_beta", 0x07e2 },
{ "XK_Greek_gamma", 0x07e3 },
{ "XK_Greek_delta", 0x07e4 },
{ "XK_Greek_epsilon", 0x07e5 },
{ "XK_Greek_zeta", 0x07e6 },
{ "XK_Greek_eta", 0x07e7 },
{ "XK_Greek_theta", 0x07e8 },
{ "XK_Greek_iota", 0x07e9 },
{ "XK_Greek_kappa", 0x07ea },
{ "XK_Greek_lamda", 0x07eb },
{ "XK_Greek_lambda", 0x07eb },
{ "XK_Greek_mu", 0x07ec },
{ "XK_Greek_nu", 0x07ed },
{ "XK_Greek_xi", 0x07ee },
{ "XK_Greek_omicron", 0x07ef },
{ "XK_Greek_pi", 0x07f0 },
{ "XK_Greek_rho", 0x07f1 },
{ "XK_Greek_sigma", 0x07f2 },
{ "XK_Greek_finalsmallsigma", 0x07f3 },
{ "XK_Greek_tau", 0x07f4 },
{ "XK_Greek_upsilon", 0x07f5 },
{ "XK_Greek_phi", 0x07f6 },
{ "XK_Greek_chi", 0x07f7 },
{ "XK_Greek_psi", 0x07f8 },
{ "XK_Greek_omega", 0x07f9 },
{ "XK_Greek_switch", 0xff7e },
{ "XK_leftradical", 0x08a1 },
{ "XK_topleftradical", 0x08a2 },
{ "XK_horizconnector", 0x08a3 },
{ "XK_topintegral", 0x08a4 },
{ "XK_botintegral", 0x08a5 },
{ "XK_vertconnector", 0x08a6 },
{ "XK_topleftsqbracket", 0x08a7 },
{ "XK_botleftsqbracket", 0x08a8 },
{ "XK_toprightsqbracket", 0x08a9 },
{ "XK_botrightsqbracket", 0x08aa },
{ "XK_topleftparens", 0x08ab },
{ "XK_botleftparens", 0x08ac },
{ "XK_toprightparens", 0x08ad },
{ "XK_botrightparens", 0x08ae },
{ "XK_leftmiddlecurlybrace", 0x08af },
{ "XK_rightmiddlecurlybrace", 0x08b0 },
{ "XK_lessthanequal", 0x08bc },
{ "XK_notequal", 0x08bd },
{ "XK_greaterthanequal", 0x08be },
{ "XK_integral", 0x08bf },
{ "XK_therefore", 0x08c0 },
{ "XK_variation", 0x08c1 },
{ "XK_infinity", 0x08c2 },
{ "XK_nabla", 0x08c5 },
{ "XK_approximate", 0x08c8 },
{ "XK_similarequal", 0x08c9 },
{ "XK_ifonlyif", 0x08cd },
{ "XK_implies", 0x08ce },
{ "XK_identical", 0x08cf },
{ "XK_radical", 0x08d6 },
{ "XK_includedin", 0x08da },
{ "XK_includes", 0x08db },
{ "XK_intersection", 0x08dc },
{ "XK_union", 0x08dd },
{ "XK_logicaland", 0x08de },
{ "XK_logicalor", 0x08df },
{ "XK_partialderivative", 0x08ef },
{ "XK_function", 0x08f6 },
{ "XK_leftarrow", 0x08fb },
{ "XK_uparrow", 0x08fc },
{ "XK_rightarrow", 0x08fd },
{ "XK_downarrow", 0x08fe },
{ "XK_soliddiamond", 0x09e0 },
{ "XK_checkerboard", 0x09e1 },
{ "XK_ht", 0x09e2 },
{ "XK_ff", 0x09e3 },
{ "XK_cr", 0x09e4 },
{ "XK_lf", 0x09e5 },
{ "XK_nl", 0x09e8 },
{ "XK_vt", 0x09e9 },
{ "XK_lowrightcorner", 0x09ea },
{ "XK_uprightcorner", 0x09eb },
{ "XK_upleftcorner", 0x09ec },
{ "XK_lowleftcorner", 0x09ed },
{ "XK_crossinglines", 0x09ee },
{ "XK_horizlinescan1", 0x09ef },
{ "XK_horizlinescan3", 0x09f0 },
{ "XK_horizlinescan5", 0x09f1 },
{ "XK_horizlinescan7", 0x09f2 },
{ "XK_horizlinescan9", 0x09f3 },
{ "XK_leftt", 0x09f4 },
{ "XK_rightt", 0x09f5 },
{ "XK_bott", 0x09f6 },
{ "XK_topt", 0x09f7 },
{ "XK_vertbar", 0x09f8 },
{ "XK_emspace", 0x0aa1 },
{ "XK_enspace", 0x0aa2 },
{ "XK_em3space", 0x0aa3 },
{ "XK_em4space", 0x0aa4 },
{ "XK_digitspace", 0x0aa5 },
{ "XK_punctspace", 0x0aa6 },
{ "XK_thinspace", 0x0aa7 },
{ "XK_hairspace", 0x0aa8 },
{ "XK_emdash", 0x0aa9 },
{ "XK_endash", 0x0aaa },
{ "XK_signifblank", 0x0aac },
{ "XK_ellipsis", 0x0aae },
{ "XK_doubbaselinedot", 0x0aaf },
{ "XK_onethird", 0x0ab0 },
{ "XK_twothirds", 0x0ab1 },
{ "XK_onefifth", 0x0ab2 },
{ "XK_twofifths", 0x0ab3 },
{ "XK_threefifths", 0x0ab4 },
{ "XK_fourfifths", 0x0ab5 },
{ "XK_onesixth", 0x0ab6 },
{ "XK_fivesixths", 0x0ab7 },
{ "XK_careof", 0x0ab8 },
{ "XK_figdash", 0x0abb },
{ "XK_leftanglebracket", 0x0abc },
{ "XK_decimalpoint", 0x0abd },
{ "XK_rightanglebracket", 0x0abe },
{ "XK_oneeighth", 0x0ac3 },
{ "XK_threeeighths", 0x0ac4 },
{ "XK_fiveeighths", 0x0ac5 },
{ "XK_seveneighths", 0x0ac6 },
{ "XK_trademark", 0x0ac9 },
{ "XK_signaturemark", 0x0aca },
{ "XK_leftopentriangle", 0x0acc },
{ "XK_rightopentriangle", 0x0acd },
{ "XK_emopencircle", 0x0ace },
{ "XK_emopenrectangle", 0x0acf },
{ "XK_leftsinglequotemark", 0x0ad0 },
{ "XK_rightsinglequotemark", 0x0ad1 },
{ "XK_leftdoublequotemark", 0x0ad2 },
{ "XK_rightdoublequotemark", 0x0ad3 },
{ "XK_prescription", 0x0ad4 },
{ "XK_minutes", 0x0ad6 },
{ "XK_seconds", 0x0ad7 },
{ "XK_latincross", 0x0ad9 },
{ "XK_filledrectbullet", 0x0adb },
{ "XK_filledlefttribullet", 0x0adc },
{ "XK_filledrighttribullet", 0x0add },
{ "XK_emfilledcircle", 0x0ade },
{ "XK_emfilledrect", 0x0adf },
{ "XK_enopencircbullet", 0x0ae0 },
{ "XK_enopensquarebullet", 0x0ae1 },
{ "XK_openrectbullet", 0x0ae2 },
{ "XK_opentribulletup", 0x0ae3 },
{ "XK_opentribulletdown", 0x0ae4 },
{ "XK_openstar", 0x0ae5 },
{ "XK_enfilledcircbullet", 0x0ae6 },
{ "XK_enfilledsqbullet", 0x0ae7 },
{ "XK_filledtribulletup", 0x0ae8 },
{ "XK_filledtribulletdown", 0x0ae9 },
{ "XK_leftpointer", 0x0aea },
{ "XK_rightpointer", 0x0aeb },
{ "XK_club", 0x0aec },
{ "XK_diamond", 0x0aed },
{ "XK_heart", 0x0aee },
{ "XK_maltesecross", 0x0af0 },
{ "XK_dagger", 0x0af1 },
{ "XK_doubledagger", 0x0af2 },
{ "XK_checkmark", 0x0af3 },
{ "XK_ballotcross", 0x0af4 },
{ "XK_musicalsharp", 0x0af5 },
{ "XK_musicalflat", 0x0af6 },
{ "XK_malesymbol", 0x0af7 },
{ "XK_femalesymbol", 0x0af8 },
{ "XK_telephone", 0x0af9 },
{ "XK_telephonerecorder", 0x0afa },
{ "XK_phonographcopyright", 0x0afb },
{ "XK_caret", 0x0afc },
{ "XK_singlelowquotemark", 0x0afd },
{ "XK_doublelowquotemark", 0x0afe },
{ "XK_leftcaret", 0x0ba3 },
{ "XK_rightcaret", 0x0ba6 },
{ "XK_downcaret", 0x0ba8 },
{ "XK_upcaret", 0x0ba9 },
{ "XK_overbar", 0x0bc0 },
{ "XK_downtack", 0x0bc2 },
{ "XK_upshoe", 0x0bc3 },
{ "XK_downstile", 0x0bc4 },
{ "XK_underbar", 0x0bc6 },
{ "XK_jot", 0x0bca },
{ "XK_quad", 0x0bcc },
{ "XK_uptack", 0x0bce },
{ "XK_circle", 0x0bcf },
{ "XK_upstile", 0x0bd3 },
{ "XK_downshoe", 0x0bd6 },
{ "XK_rightshoe", 0x0bd8 },
{ "XK_leftshoe", 0x0bda },
{ "XK_lefttack", 0x0bdc },
{ "XK_righttack", 0x0bfc },
{ "XK_hebrew_doublelowline", 0x0cdf },
{ "XK_hebrew_aleph", 0x0ce0 },
{ "XK_hebrew_bet", 0x0ce1 },
{ "XK_hebrew_beth", 0x0ce1 },
{ "XK_hebrew_gimel", 0x0ce2 },
{ "XK_hebrew_gimmel", 0x0ce2 },
{ "XK_hebrew_dalet", 0x0ce3 },
{ "XK_hebrew_daleth", 0x0ce3 },
{ "XK_hebrew_he", 0x0ce4 },
{ "XK_hebrew_waw", 0x0ce5 },
{ "XK_hebrew_zain", 0x0ce6 },
{ "XK_hebrew_zayin", 0x0ce6 },
{ "XK_hebrew_chet", 0x0ce7 },
{ "XK_hebrew_het", 0x0ce7 },
{ "XK_hebrew_tet", 0x0ce8 },
{ "XK_hebrew_teth", 0x0ce8 },
{ "XK_hebrew_yod", 0x0ce9 },
{ "XK_hebrew_finalkaph", 0x0cea },
{ "XK_hebrew_kaph", 0x0ceb },
{ "XK_hebrew_lamed", 0x0cec },
{ "XK_hebrew_finalmem", 0x0ced },
{ "XK_hebrew_mem", 0x0cee },
{ "XK_hebrew_finalnun", 0x0cef },
{ "XK_hebrew_nun", 0x0cf0 },
{ "XK_hebrew_samech", 0x0cf1 },
{ "XK_hebrew_samekh", 0x0cf1 },
{ "XK_hebrew_ayin", 0x0cf2 },
{ "XK_hebrew_finalpe", 0x0cf3 },
{ "XK_hebrew_pe", 0x0cf4 },
{ "XK_hebrew_finalzade", 0x0cf5 },
{ "XK_hebrew_finalzadi", 0x0cf5 },
{ "XK_hebrew_zade", 0x0cf6 },
{ "XK_hebrew_zadi", 0x0cf6 },
{ "XK_hebrew_qoph", 0x0cf7 },
{ "XK_hebrew_kuf", 0x0cf7 },
{ "XK_hebrew_resh", 0x0cf8 },
{ "XK_hebrew_shin", 0x0cf9 },
{ "XK_hebrew_taw", 0x0cfa },
{ "XK_hebrew_taf", 0x0cfa },
{ "XK_Hebrew_switch", 0xff7e },
{ "XK_Thai_kokai", 0x0da1 },
{ "XK_Thai_khokhai", 0x0da2 },
{ "XK_Thai_khokhuat", 0x0da3 },
{ "XK_Thai_khokhwai", 0x0da4 },
{ "XK_Thai_khokhon", 0x0da5 },
{ "XK_Thai_khorakhang", 0x0da6 },
{ "XK_Thai_ngongu", 0x0da7 },
{ "XK_Thai_chochan", 0x0da8 },
{ "XK_Thai_choching", 0x0da9 },
{ "XK_Thai_chochang", 0x0daa },
{ "XK_Thai_soso", 0x0dab },
{ "XK_Thai_chochoe", 0x0dac },
{ "XK_Thai_yoying", 0x0dad },
{ "XK_Thai_dochada", 0x0dae },
{ "XK_Thai_topatak", 0x0daf },
{ "XK_Thai_thothan", 0x0db0 },
{ "XK_Thai_thonangmontho", 0x0db1 },
{ "XK_Thai_thophuthao", 0x0db2 },
{ "XK_Thai_nonen", 0x0db3 },
{ "XK_Thai_dodek", 0x0db4 },
{ "XK_Thai_totao", 0x0db5 },
{ "XK_Thai_thothung", 0x0db6 },
{ "XK_Thai_thothahan", 0x0db7 },
{ "XK_Thai_thothong", 0x0db8 },
{ "XK_Thai_nonu", 0x0db9 },
{ "XK_Thai_bobaimai", 0x0dba },
{ "XK_Thai_popla", 0x0dbb },
{ "XK_Thai_phophung", 0x0dbc },
{ "XK_Thai_fofa", 0x0dbd },
{ "XK_Thai_phophan", 0x0dbe },
{ "XK_Thai_fofan", 0x0dbf },
{ "XK_Thai_phosamphao", 0x0dc0 },
{ "XK_Thai_moma", 0x0dc1 },
{ "XK_Thai_yoyak", 0x0dc2 },
{ "XK_Thai_rorua", 0x0dc3 },
{ "XK_Thai_ru", 0x0dc4 },
{ "XK_Thai_loling", 0x0dc5 },
{ "XK_Thai_lu", 0x0dc6 },
{ "XK_Thai_wowaen", 0x0dc7 },
{ "XK_Thai_sosala", 0x0dc8 },
{ "XK_Thai_sorusi", 0x0dc9 },
{ "XK_Thai_sosua", 0x0dca },
{ "XK_Thai_hohip", 0x0dcb },
{ "XK_Thai_lochula", 0x0dcc },
{ "XK_Thai_oang", 0x0dcd },
{ "XK_Thai_honokhuk", 0x0dce },
{ "XK_Thai_paiyannoi", 0x0dcf },
{ "XK_Thai_saraa", 0x0dd0 },
{ "XK_Thai_maihanakat", 0x0dd1 },
{ "XK_Thai_saraaa", 0x0dd2 },
{ "XK_Thai_saraam", 0x0dd3 },
{ "XK_Thai_sarai", 0x0dd4 },
{ "XK_Thai_saraii", 0x0dd5 },
{ "XK_Thai_saraue", 0x0dd6 },
{ "XK_Thai_sarauee", 0x0dd7 },
{ "XK_Thai_sarau", 0x0dd8 },
{ "XK_Thai_sarauu", 0x0dd9 },
{ "XK_Thai_phinthu", 0x0dda },
{ "XK_Thai_baht", 0x0ddf },
{ "XK_Thai_sarae", 0x0de0 },
{ "XK_Thai_saraae", 0x0de1 },
{ "XK_Thai_sarao", 0x0de2 },
{ "XK_Thai_saraaimaimuan", 0x0de3 },
{ "XK_Thai_saraaimaimalai", 0x0de4 },
{ "XK_Thai_lakkhangyao", 0x0de5 },
{ "XK_Thai_maiyamok", 0x0de6 },
{ "XK_Thai_maitaikhu", 0x0de7 },
{ "XK_Thai_maiek", 0x0de8 },
{ "XK_Thai_maitho", 0x0de9 },
{ "XK_Thai_maitri", 0x0dea },
{ "XK_Thai_maichattawa", 0x0deb },
{ "XK_Thai_thanthakhat", 0x0dec },
{ "XK_Thai_nikhahit", 0x0ded },
{ "XK_Thai_leksun", 0x0df0 },
{ "XK_Thai_leknung", 0x0df1 },
{ "XK_Thai_leksong", 0x0df2 },
{ "XK_Thai_leksam", 0x0df3 },
{ "XK_Thai_leksi", 0x0df4 },
{ "XK_Thai_lekha", 0x0df5 },
{ "XK_Thai_lekhok", 0x0df6 },
{ "XK_Thai_lekchet", 0x0df7 },
{ "XK_Thai_lekpaet", 0x0df8 },
{ "XK_Thai_lekkao", 0x0df9 },
{ "XK_Hangul", 0xff31 },
{ "XK_Hangul_Start", 0xff32 },
{ "XK_Hangul_End", 0xff33 },
{ "XK_Hangul_Hanja", 0xff34 },
{ "XK_Hangul_Jamo", 0xff35 },
{ "XK_Hangul_Romaja", 0xff36 },
{ "XK_Hangul_Codeinput", 0xff37 },
{ "XK_Hangul_Jeonja", 0xff38 },
{ "XK_Hangul_Banja", 0xff39 },
{ "XK_Hangul_PreHanja", 0xff3a },
{ "XK_Hangul_PostHanja", 0xff3b },
{ "XK_Hangul_SingleCandidate", 0xff3c },
{ "XK_Hangul_MultipleCandidate", 0xff3d },
{ "XK_Hangul_PreviousCandidate", 0xff3e },
{ "XK_Hangul_Special", 0xff3f },
{ "XK_Hangul_switch", 0xff7e },
{ "XK_Korean_Won", 0x0eff },
{ "XK_EuroSign", 0x20ac },
{ 0, 0 }};
static const char *
nameForKeycode(int keycode)
{ KeyNameEntry *kne;
for (kne = codes; kne->name; kne++)
if (kne->code == keycode)
return kne->name;
return "UNKNOWN CODE";
}
static const char *
nameForKeyboardEvent(XEvent *evt) { return nameForKeycode(evt->xkey.keycode); }
#endif /* DEBUG_EVENTS */
static int mouseWheel2Squeak[4] = {30, 31, 28, 29};
static void handleEvent(XEvent *evt)
{
#if DEBUG_EVENTS
switch (evt->type)
{
case ButtonPress:
fprintf(stderr, "\n(handleEvent)X ButtonPress state 0x%x button %d\n",
evt->xbutton.state, evt->xbutton.button);
break;
case ButtonRelease:
fprintf(stderr, "\n(handleEvent)X ButtonRelease state 0x%x button %d\n",
evt->xbutton.state, evt->xbutton.button);
break;
case KeyPress:
fprintf(stderr, "\n(handleEvent)X KeyPress state 0x%x raw keycode %d\n",
evt->xkey.state, evt->xkey.keycode);
break;
case KeyRelease:
fprintf(stderr, "\n(handleEvent)X KeyRelease state 0x%x raw keycode %d\n",
evt->xkey.state, evt->xkey.keycode);
break;
}
#endif /* DEBUG_EVENTS */
# define noteEventPosition(evt) \
{ \
mousePosition.x= evt.x; \
mousePosition.y= evt.y; \
}
# define noteEventState(evt) \
{ \
noteEventPosition(evt); \
modifierState= x2sqModifier(evt.state); \
}
#if defined(DEBUG_FOCUS)
if ((evt->type != EnterNotify) && (evt->type != LeaveNotify) && (evt->type != MotionNotify))
{
static char *eventName[]= {
"KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease",
"MotionNotify", "EnterNotify", "LeaveNotify", "FocusIn",
"FocusOut", "KeymapNotify", "Expose", "GraphicsExpose",
"NoExpose", "VisibilityNotify", "CreateNotify", "DestroyNotify",
"UnmapNotify", "MapNotify", "MapRequest", "ReparentNotify",
"ConfigureNotify", "ConfigureRequest", "GravityNotify",
"ResizeRequest", "CirculateNotify", "CirculateRequest",
"PropertyNotify", "SelectionClear", "SelectionRequest",
"SelectionNotify", "ColormapNotify", "ClientMessage",
"MappingNotify", "LASTEvent", 0
};
static char *modeName[]= { "Normal", "Grab", "Ungrab", "WhileGrabbed", 0 };
static char *detailName[]= {
"Ancestor", "Virtual", "Inferior", "Nonlinear", "NonlinearVirtual",
"Pointer", "PointerRoot", "DetailNone", 0
};
fprintf(stderr, eventName[evt->type-2]);
if (evt->xany.window == stParent)
fprintf(stderr, " window=stParent");
else if (evt->xany.window == stWindow)
fprintf(stderr, " window=stWindow");
else
fprintf(stderr, " window=%x", evt->xany.window);
if (evt->type == FocusIn || evt->type == FocusOut)
fprintf(stderr, " mode=Notify%s detail=Notify%s\n", modeName[evt->xfocus.mode], detailName[evt->xfocus.detail]);
else
fprintf(stderr, "\n");
}
#endif
if (True == XFilterEvent(evt, 0))
return;
switch (evt->type)
{
case MotionNotify:
noteEventState(evt->xmotion);
recordMouseEvent();
break;
case FocusIn:
if (evt->xfocus.mode == NotifyNormal || evt->xfocus.mode == NotifyUngrab)
{
switch (evt->xfocus.detail)
{
case NotifyNonlinear:
case NotifyInferior:
XSetInputFocus(stDisplay, stWindow, RevertToNone, CurrentTime);
break;
case NotifyAncestor:
# if defined(INIT_INPUT_WHEN_FOCUSED_IN)
initInput();
# endif
if (inputContext)
{
setInputContextArea();
XSetICFocus(inputContext);
}
break;
}
}
break;
case FocusOut:
if (inputContext && (evt->xfocus.mode == NotifyNormal) && (evt->xfocus.detail == NotifyNonlinear))
XUnsetICFocus(inputContext);
break;
#if 0
case EnterNotify:
if (inputContext && evt->xcrossing.focus && !(inputStyle & XIMPreeditPosition))
{
setInputContextArea();
XSetICFocus(inputContext);
}
break;
case LeaveNotify:
if (inputContext && evt->xcrossing.focus && !(inputStyle & XIMPreeditPosition))
XUnsetICFocus(inputContext);
break;
#endif
case ButtonPress:
noteEventState(evt->xbutton);
switch (evt->xbutton.button)
{
case 1: case 2: case 3:
buttonState |= x2sqButton(evt->xbutton.button);
recordMouseEvent();
break;
case 4: case 5: case 6: case 7: /* mouse wheel */
{
int keyCode= mouseWheel2Squeak[evt->xbutton.button - 4];
int modifiers= modifierState ^ CtrlKeyBit;
recordKeyboardEvent(keyCode, EventKeyDown, modifiers, keyCode);
recordKeyboardEvent(keyCode, EventKeyChar, modifiers, keyCode);
recordKeyboardEvent(keyCode, EventKeyUp, modifiers, keyCode);
}
break;
default:
ioBeep();
break;
}
break;
case ButtonRelease:
noteEventState(evt->xbutton);
switch (evt->xbutton.button)
{
case 1: case 2: case 3:
buttonState &= ~x2sqButton(evt->xbutton.button);
recordMouseEvent();
break;
case 4: case 5: case 6: case 7: /* mouse wheel */
break;
default:
ioBeep();
break;
}
break;
case KeyPress:
noteEventState(evt->xkey);
{
KeySym symbolic;
int keyCode= x2sqKey(&evt->xkey, &symbolic);
int ucs4= xkeysym2ucs4(symbolic);
DCONV_FPRINTF(stderr, "symbolic, keyCode, ucs4: %x, %d, %d\n", symbolic, keyCode, ucs4);
DCONV_FPRINTF(stderr, "pressed, buffer: %d, %x\n", multi_key_pressed, multi_key_buffer);
if (multi_key_pressed && multi_key_buffer == 0)
{
switch (ucs4)
{
# define key_case(sym, code) \
case sym: \
multi_key_buffer= (code); \
keyCode= -1; \
ucs4= -1; \
break;
key_case(0x60, 0x0300); /* grave */
key_case(0x27, 0x0301); /* apostrophe */
key_case(0x5e, 0x0302); /* circumflex */
key_case(0x7e, 0x0303); /* tilde */
key_case(0x22, 0x0308); /* double quote */
key_case(0x61, 0x030a); /* a */
# undef key_case
}
}
else
{
switch (symbolic)
{
# define dead_key_case(sym, code, orig) \
case sym: \
if (multi_key_buffer == code) \
{ \
multi_key_buffer= 0; \
keyCode= orig; \
ucs4= orig; \
} \
else \
{ \
multi_key_buffer= (code); \
keyCode= -1; \
ucs4= -1; \
} \
break;
dead_key_case(XK_dead_grave, 0x0300, 0x60);
dead_key_case(XK_dead_acute, 0x0301, 0x27);
dead_key_case(XK_dead_circumflex, 0x0302, 0x5e);
dead_key_case(XK_dead_tilde, 0x0303, 0x7e);
dead_key_case(XK_dead_macron, 0x0304, 0x0304);
dead_key_case(XK_dead_abovedot, 0x0307, 0x0307);
dead_key_case(XK_dead_diaeresis, 0x0308, 0x0308);
dead_key_case(XK_dead_abovering, 0x030A, 0x030A);
dead_key_case(XK_dead_doubleacute, 0x030B, 0x030B);
dead_key_case(XK_dead_caron, 0x030C, 0x030C);
dead_key_case(XK_dead_cedilla, 0x0327, 0x0327);
dead_key_case(XK_dead_ogonek, 0x0328, 0x0328);
dead_key_case(XK_dead_iota, 0x0345, 0x0345);
dead_key_case(XK_dead_voiced_sound, 0x3099, 0x3099);
dead_key_case(XK_dead_semivoiced_sound, 0x309a, 0x309a);
dead_key_case(XK_dead_belowdot, 0x0323, 0x0323);
dead_key_case(XK_dead_hook, 0x0309, 0x0309);
dead_key_case(XK_dead_horn, 0x031b, 0x031b);
# undef dead_key_case
}
if (symbolic != XK_Multi_key)
{
multi_key_pressed= 0;
DCONV_FPRINTF(stderr, "multi_key reset\n");
}
}
DCONV_FPRINTF(stderr, "keyCode, ucs4, multi_key_buffer: %d, %d, %x\n", keyCode, ucs4, multi_key_buffer);
if (keyCode >= 0)
{
recordKeystroke(keyCode); /* DEPRECATED */
if (multi_key_buffer != 0)
recordKeystroke(multi_key_buffer);
}
if ((keyCode >= 0) || (ucs4 > 0))
{
recordKeyboardEvent(keyCode, EventKeyDown, modifierState, ucs4);
if (ucs4) /* only generate a key char event if there's a code. */
recordKeyboardEvent(keyCode, EventKeyChar, modifierState, ucs4);
if (multi_key_buffer != 0)
{
recordKeyboardEvent(multi_key_buffer, EventKeyDown, modifierState, multi_key_buffer);
recordKeyboardEvent(multi_key_buffer, EventKeyChar, modifierState, multi_key_buffer);
multi_key_buffer= 0;
}
}
}
break;
case KeyRelease:
noteEventState(evt->xkey);
{
KeySym symbolic;
int keyCode, ucs4;
if (XPending(stDisplay))
{
XEvent evt2;
XPeekEvent(stDisplay, &evt2);
if ((evt2.type == KeyPress) && (evt2.xkey.keycode == evt->xkey.keycode) && ((evt2.xkey.time - evt->xkey.time < 2)))
break;
}
keyCode= x2sqKey(&evt->xkey, &symbolic);
ucs4= xkeysym2ucs4(symbolic);
if ((keyCode >= 0) || (ucs4 > 0))
recordKeyboardEvent(keyCode, EventKeyUp, modifierState, ucs4);
}
break;
case SelectionClear:
if (xaClipboard == evt->xselectionclear.selection)
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "SelectionClear(xaClipboard)\n");
# endif
stOwnsClipboard= 0;
stOwnsSelection= 0; /* clear both CLIPBOARD and PRIMARY */
usePrimaryFirst= 0;
}
else if (XA_PRIMARY == evt->xselectionclear.selection)
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "SelectionClear(XA_PRIMARY)\n");
# endif
stOwnsSelection= 0; /* but maintain CLIPBOARD if we have it */
}
break;
case SelectionRequest:
sendSelection(&evt->xselectionrequest, 0);
break;
case PropertyNotify:
if (evt->xproperty.atom == xaCutBuffer0)
{
# if defined(DEBUG_SELECTIONS)
fprintf(stderr, "CUT_BUFFER0 changed\n");
# endif
stOwnsClipboard= 0;
usePrimaryFirst= 1;
}
break;
case Expose:
{
XExposeEvent *ex= &evt->xexpose;
# if defined(USE_XSHM)
if (asyncUpdate)
waitForCompletions();
# endif
# if defined(FULL_UPDATE_ON_EXPOSE)
/* ignore it if there are other exposures upstream */
if (ex->count == 0)
fullDisplayUpdate(); /* this makes VM call ioShowDisplay */
# else
redrawDisplay(ex->x, ex->x + ex->width, ex->y, ex->y + ex->height);
# endif /*!FULL_UPDATE_ON_EXPOSE*/
}
break;
# if 0
case VisibilityNotify:
{
static int previousState= VisibilityFullyObscured;
XVisibilityEvent *ex= &evt->xvisibility;
if (ex->state < previusState)
fullDisplayUpdate();
previousState= ex->state;
}
# endif
case MapNotify:
/* The window has just been mapped, possibly for the first
time: update mousePosition (which otherwise may not be
set before the first button event). */
getMousePosition();
noteWindowChange();
fullDisplayUpdate();
# if defined(INIT_INPUT_WHEN_MAPPED)
initInput();
# endif
break;
case UnmapNotify:
{
XEvent ev;
if (sleepWhenUnmapped)
do
{
/* xxx SelectInput() ??? -- need to filter key events? */
XNextEvent(stDisplay, &ev);
handleEvent(&ev);
}
while (ev.type != MapNotify);
getMousePosition();
}
noteWindowChange();
break;
case ConfigureNotify:
noteResize(evt->xconfigure.width, evt->xconfigure.height);
break;
case MappingNotify:
XRefreshKeyboardMapping(&evt->xmapping);
break;
case ClientMessage:
if (wmProtocolsAtom == evt->xclient.message_type && wmDeleteWindowAtom == evt->xclient.data.l[0])
recordWindowEvent(WindowEventClose, 0, 0, 0, 0, 1); /* windowIndex 1 is main window */
break;
# if defined(USE_XSHM)
default:
if (evt->type == completionType)
--completions;
break;
# endif
}
if (useXdnd)
dndHandleEvent(evt->type, evt);
# undef noteEventState
}
int handleEvents(void)
{
if (recordPendingKeys())
return 0;
if (!isConnectedToXServer || !XPending(stDisplay))
return !iebEmptyP();
while (XPending(stDisplay))
{
XEvent evt;
XNextEvent(stDisplay, &evt);
handleEvent(&evt);
}
return 1;
}
static void xHandler(int fd, void *data, int flags)
{
handleEvents(); /* XPending() drains display connection input */
aioHandle(stXfd, xHandler, AIO_RX);
}
static void npHandler(int fd, void *data, int flags)
{
browserProcessCommand();
aioHandle(browserPipes[0], npHandler, AIO_RX);
}
void getMaskbit(unsigned long ul, int *nmask, int *shift)
{
int i;
unsigned long hb;
*nmask= *shift= 0;
hb= 0x8000; hb= (hb<<16); /* hb = 0x80000000UL */
for (i= 31; ((ul & hb) == 0) && i >= 0; --i, ul<<= 1)
;
for (; ((ul & hb) != 0) && i >= 0; --i, ul<<= 1)
(*nmask)++;
*shift= i+1;
}
void initDownGradingColors(void)
{
int r, g, b, i;
if (stVisual->class == PseudoColor)
{
for (r= 0; r < 0x8; r++)
for (g= 0; g < 0x8; g++)
for (b= 0; b < 0x4; b++)
{
int mindiff= 0x7*0x7 + 0x7*0x7 + 0x3*0x3 + 1;
for (i= 0; i < 256; i++)
{
int rdiff, gdiff, bdiff, diff;
rdiff= r - ((stColors[i]>>5) & 0x7);
gdiff= g - ((stColors[i]>>2) & 0x7);
bdiff= b - (stColors[i] & 0x3);
diff= rdiff*rdiff + gdiff*gdiff + bdiff*bdiff;
if (diff < mindiff)
{
mindiff= diff;
stDownGradingColors[(r << 5) + (g << 2) + b]= i;
}
}
}
}
else
for (i= 0; i < 256; i++)
stDownGradingColors[i]=
( ((i >> 5) & ((1 << stRNMask) - 1)) << stRShift)
| (((i >> 2) & ((1 << stGNMask) - 1)) << stGShift)
| (((i >> 0) & ((1 << stBNMask) - 1)) << stBShift);
}
void initColourmap(int index, int red, int green, int blue)
{
if (index >= 256)
return;
if (stVisual->class == TrueColor || stVisual->class == DirectColor)
{
unsigned int r, g, b;
r= red;
g= green;
b= blue;
stColors[index]= (((r>>(16-stRNMask))<<stRShift) |
((g>>(16-stGNMask))<<stGShift) |
((b>>(16-stBNMask))<<stBShift));
}
else
{
XColor color;
color.pixel= index;
color.red= red;
color.green= green;
color.blue= blue;
color.flags= DoRed|DoGreen|DoBlue;
XStoreColor(stDisplay, stColormap, &color);
/* map rgb weight=332 */
stColors[index]= ((((unsigned int)red >>(16-3))<<5) |
(((unsigned int)green>>(16-3))<<2) |
((unsigned int)blue >>(16-2)));
}
}
void initPixmap(void)
{
int count;
XPixmapFormatValues *xpv;
xpv= XListPixmapFormats(stDisplay, &count);
if (xpv)
{
while (--count >= 0)
{
if (stDepth == xpv[count].depth)
stBitsPerPixel= xpv[count].bits_per_pixel;
}
XFree((void *)xpv);
}
if (stBitsPerPixel == 0)
stBitsPerPixel= stDepth;
switch (stVisual->class)
{
case PseudoColor:
if (stBitsPerPixel == 8)
break;
else
{
fprintf(stderr, "Visual class PseudoColor is not supported at depth %d\n", stBitsPerPixel);
exit(1);
return;
}
case TrueColor:
case DirectColor:
getMaskbit(stVisual->red_mask, &stRNMask, &stRShift);
getMaskbit(stVisual->green_mask, &stGNMask, &stGShift);
getMaskbit(stVisual->blue_mask, &stBNMask, &stBShift);
if (stBitsPerPixel == 16)
{
stHasSameRGBMask16= (stVisual->red_mask == (0x1f << 10) &&
stVisual->green_mask == (0x1f << 5) &&
stVisual->blue_mask == (0x1f));
break;
}
else if (stBitsPerPixel == 32)
{
stHasSameRGBMask32= (stVisual->red_mask == (0xff << 16) &&
stVisual->green_mask == (0xff << 8) &&
stVisual->blue_mask == (0xff));
break;
}
else if (stBitsPerPixel == 24)
{
/* nothing to do... */
break;
}
else
{
fprintf(stderr, "Visual class TrueColor is not supported at depth %d\n", stBitsPerPixel);
exit(1);
return;
}
case GrayScale:
case StaticColor:
case StaticGray:
default:
fprintf(stderr, "This visual class is not supported\n");
exit(1);
return;
}
if (stVisual->class == PseudoColor)
stColormap= XCreateColormap(stDisplay, stWindow, stVisual, AllocAll);
/* 1-bit colors (monochrome) */
initColourmap(0, 65535, 65535, 65535); /* white or transparent */
initColourmap(1, 0, 0, 0); /* black */
/* additional colors for 2-bit color */
initColourmap(2, 65535, 65535, 65535); /* opaque white */
initColourmap(3, 32768, 32768, 32768); /* 1/2 gray */
/* additional colors for 4-bit color */
initColourmap( 4, 65535, 0, 0); /* red */
initColourmap( 5, 0, 65535, 0); /* green */
initColourmap( 6, 0, 0, 65535); /* blue */
initColourmap( 7, 0, 65535, 65535); /* cyan */
initColourmap( 8, 65535, 65535, 0); /* yellow */
initColourmap( 9, 65535, 0, 65535); /* magenta */
initColourmap(10, 8192, 8192, 8192); /* 1/8 gray */
initColourmap(11, 16384, 16384, 16384); /* 2/8 gray */
initColourmap(12, 24576, 24576, 24576); /* 3/8 gray */
initColourmap(13, 40959, 40959, 40959); /* 5/8 gray */
initColourmap(14, 49151, 49151, 49151); /* 6/8 gray */
initColourmap(15, 57343, 57343, 57343); /* 7/8 gray */
/* additional colors for 8-bit color */
/* 24 more shades of gray (does not repeat 1/8th increments) */
initColourmap(16, 2048, 2048, 2048); /* 1/32 gray */
initColourmap(17, 4096, 4096, 4096); /* 2/32 gray */
initColourmap(18, 6144, 6144, 6144); /* 3/32 gray */
initColourmap(19, 10240, 10240, 10240); /* 5/32 gray */
initColourmap(20, 12288, 12288, 12288); /* 6/32 gray */
initColourmap(21, 14336, 14336, 14336); /* 7/32 gray */
initColourmap(22, 18432, 18432, 18432); /* 9/32 gray */
initColourmap(23, 20480, 20480, 20480); /* 10/32 gray */
initColourmap(24, 22528, 22528, 22528); /* 11/32 gray */
initColourmap(25, 26624, 26624, 26624); /* 13/32 gray */
initColourmap(26, 28672, 28672, 28672); /* 14/32 gray */
initColourmap(27, 30720, 30720, 30720); /* 15/32 gray */
initColourmap(28, 34815, 34815, 34815); /* 17/32 gray */
initColourmap(29, 36863, 36863, 36863); /* 18/32 gray */
initColourmap(30, 38911, 38911, 38911); /* 19/32 gray */
initColourmap(31, 43007, 43007, 43007); /* 21/32 gray */
initColourmap(32, 45055, 45055, 45055); /* 22/32 gray */
initColourmap(33, 47103, 47103, 47103); /* 23/32 gray */
initColourmap(34, 51199, 51199, 51199); /* 25/32 gray */
initColourmap(35, 53247, 53247, 53247); /* 26/32 gray */
initColourmap(36, 55295, 55295, 55295); /* 27/32 gray */
initColourmap(37, 59391, 59391, 59391); /* 29/32 gray */
initColourmap(38, 61439, 61439, 61439); /* 30/32 gray */
initColourmap(39, 63487, 63487, 63487); /* 31/32 gray */
/* The remainder of color table defines a color cube with six steps
for each primary color. Note that the corners of this cube repeat
previous colors, but simplifies the mapping between RGB colors and
color map indices. This color cube spans indices 40 through 255.
*/
{
int r, g, b;
for (r= 0; r < 6; r++)
for (g= 0; g < 6; g++)
for (b= 0; b < 6; b++)
{
int i= 40 + ((36 * r) + (6 * b) + g);
if (i > 255) error("index out of range in color table compuation");
initColourmap(i, (r * 65535) / 5, (g * 65535) / 5, (b * 65535) / 5);
}
}
stColorWhite.red= stColorWhite.green= stColorWhite.blue= 65535;
stColorBlack.red= stColorBlack.green= stColorBlack.blue= 0;
if (stVisual->class == PseudoColor)
{
XSetWindowColormap(stDisplay, stParent, stColormap);
stColorWhite.pixel= 0;
stColorBlack.pixel= 1;
#if 0
/* initialise the black and white color values for cursor creation */
if (XAllocColor(stDisplay, stColormap, &stColorWhite))
fprintf(stderr, "failed to find white pixel in Squeak colormap\n");
if (XAllocColor(stDisplay, stColormap, &stColorBlack))
fprintf(stderr, "failed to find black pixel in Squeak colormap\n");
#endif
initDownGradingColors();
}
else
{
stColorWhite.pixel= WhitePixel(stDisplay, DefaultScreen(stDisplay));
stColorBlack.pixel= BlackPixel(stDisplay, DefaultScreen(stDisplay));
}
}
static int xError(Display *dpy, XErrorEvent *evt)
{
char buf[1024];
XGetErrorText(dpy, evt->error_code, buf, sizeof(buf));
fprintf(stderr,
"X Error: %s\n"
" Major opcode of failed request: %ld\n"
" Minor opcode of failed request: %ld\n"
" Serial number of failed request: %ld\n",
buf,
(long)evt->request_code,
(long)evt->minor_code,
(long)evt->serial);
return 0;
}
void initWindow(char *displayName)
{
XRectangle windowBounds= { 0, 0, 640, 480 }; /* default window bounds */
int right, bottom;
#ifdef PharoVM
// Some libraries require Xlib multi-threading support. When using
// multi-threading XInitThreads() has to be first Xlib function called.
XInitThreads();
#endif
XSetErrorHandler(xError);
stDisplay= XOpenDisplay(displayName);
if (!stDisplay)
{
fprintf(stderr, "Could not open display `%s'.\n", displayName);
exit(1);
}
/* get screen size */
scrH= (DisplayHeight(stDisplay, DefaultScreen(stDisplay)));
scrW= (DisplayWidth(stDisplay, DefaultScreen(stDisplay)));
if ((scrW % sizeof(void *)) != 0)
scrW= (scrW / sizeof(void *)) * sizeof(void *);
stXfd= ConnectionNumber(stDisplay);
/* find the most suitable Visual */
{
/* preferred visuals in order of decreasing priority */
static int trialVisuals[][2]= {
{ 24, TrueColor },
{ 24, DirectColor },
{ 24, StaticColor },
{ 24, PseudoColor },
{ 16, TrueColor },
{ 16, DirectColor },
{ 16, StaticColor },
{ 16, PseudoColor },
{ 32, TrueColor }, /* 32 has alpha problems when compositing */
{ 32, DirectColor },
{ 32, StaticColor },
{ 32, PseudoColor },
{ 8, PseudoColor },
{ 8, DirectColor },
{ 8, TrueColor },
{ 8, StaticColor },
{ 0, 0 }
};
XVisualInfo viz;
int i;
stVisual= DefaultVisual(stDisplay, DefaultScreen(stDisplay));
stDepth= DefaultDepth(stDisplay, DefaultScreen(stDisplay));
if ((24 == stDepth) || (16 == stDepth))
{
# if defined(DEBUG_VISUAL)
fprintf(stderr, "Using default visual (%d bits).\n", stDepth);
# endif
}
else
{
for (i= 0; trialVisuals[i][0] != 0; ++i)
{
# if defined(DEBUG_VISUAL)
fprintf(stderr, "Trying %d bit %s.\n", trialVisuals[i][0], debugVisual(trialVisuals[i][1]));
# endif
if (XMatchVisualInfo(stDisplay, DefaultScreen(stDisplay), trialVisuals[i][0], trialVisuals[i][1], &viz) != 0)
break;
}
if (trialVisuals [i][0] == 0)
{
# if defined(DEBUG_VISUAL)
fprintf(stderr, "Using default visual (%d bits).\n", stDepth);
# endif
}
else
{
stVisual= viz.visual;
stDepth= trialVisuals[i][0];
}
}
}
if (fullScreen)
{
right= scrW;
bottom= scrH;
}
else
{
int savedWindowSize= getSavedWindowSize();
if (savedWindowSize != 0)
{
right= windowBounds.x + ((unsigned)savedWindowSize >> 16);
bottom= windowBounds.y + (savedWindowSize & 0xFFFF);
}
else
{
right= windowBounds.x + windowBounds.width;
bottom= windowBounds.y + windowBounds.height;
}
}
/* minimum size is 64 x 64 */
right= ( right > (windowBounds.x + 64)) ? right : (windowBounds.x + 64);
bottom= (bottom > (windowBounds.y + 64)) ? bottom : (windowBounds.y + 64);
/* maximum bottom-right is screen bottom-right */
right= ( right <= DisplayWidth(stDisplay, DefaultScreen(stDisplay)))
? right : (DisplayWidth(stDisplay, DefaultScreen(stDisplay)) - 8);
bottom= (bottom <= DisplayHeight(stDisplay, DefaultScreen(stDisplay)))
? bottom : (DisplayHeight(stDisplay, DefaultScreen(stDisplay)) - 8);
windowBounds.width= right - windowBounds.x;
windowBounds.height= bottom - windowBounds.y;
if (windowBounds.width % sizeof(void *))
windowBounds.width= (windowBounds.width / sizeof(void *)) * sizeof(void *);
stWidth= windowBounds.width;
stHeight= windowBounds.height;
/* create the Squeak window */
{
XSetWindowAttributes attributes;
unsigned long valuemask, parentValuemask;
attributes.border_pixel= WhitePixel(stDisplay, DefaultScreen(stDisplay));
attributes.background_pixel= WhitePixel(stDisplay, DefaultScreen(stDisplay));
attributes.event_mask= WM_EVENTMASK;
attributes.backing_store= NotUseful;
if (useXdnd)
attributes.event_mask |= EnterWindowMask;
valuemask= CWEventMask | CWBackingStore | CWBorderPixel | CWBackPixel;
parentValuemask= CWEventMask | CWBackingStore | CWBorderPixel;
/* A visual that is not DefaultVisual requires its own color map.
If visual is PseudoColor, the new color map is made elsewhere. */
if ((stVisual != DefaultVisual(stDisplay, DefaultScreen(stDisplay))) &&
(stVisual->class != PseudoColor))
{
stColormap= XCreateColormap(stDisplay,
RootWindow(stDisplay, DefaultScreen(stDisplay)),
stVisual,
AllocNone);
attributes.colormap= stColormap;
valuemask |= CWColormap;
parentValuemask |= CWColormap;
}
# if defined(DEBUG_BROWSER)
fprintf(stderr, "browser window %d\n", browserWindow);
# endif
if (browserWindow != 0)
{
Window root;
int s;
unsigned int w, h, u;
stParent= browserWindow;
XGetGeometry(stDisplay, stParent, &root, &s, &s, &w, &h, &u, &u);
stWidth= xWidth= w;
stHeight= xHeight= h;
setSavedWindowSize((w << 16) | h);
}
else
{
int s= getSavedWindowSize();
if (s)
{
stWidth= s >> 16;
stHeight= s & 0xffff;
}
stParent= XCreateWindow(stDisplay,
DefaultRootWindow(stDisplay),
windowBounds.x, windowBounds.y,
stWidth, stHeight,
0,
stDepth, InputOutput, stVisual,
parentValuemask, &attributes);
# if defined(SUGAR)
if (sugarBundleId)
XChangeProperty(stDisplay, stParent,
XInternAtom(stDisplay, "_SUGAR_BUNDLE_ID", 0), XA_STRING, 8,
PropModeReplace, (unsigned char *)sugarBundleId, strlen(sugarBundleId));
if (sugarActivityId)
XChangeProperty(stDisplay, stParent,
XInternAtom(stDisplay, "_SUGAR_ACTIVITY_ID", 0), XA_STRING, 8,
PropModeReplace, (unsigned char *)sugarActivityId, strlen(sugarActivityId));
# endif /* defined(SUGAR) */
{ unsigned long pid = getpid();
XChangeProperty(stDisplay, stParent,
XInternAtom(stDisplay, "_NET_WM_PID", 0),
XA_CARDINAL, 32, PropModeReplace,
(unsigned char *)&pid, 1);
}
/* This is needed for PersonalShare, see sqUnixX11PShare.c */
{ Atom normal = XInternAtom(stDisplay, "_NET_WM_WINDOW_TYPE_NORMAL", 0);
XChangeProperty(stDisplay, stParent,
XInternAtom(stDisplay, "_NET_WM_WINDOW_TYPE", 0),
XA_ATOM, 32, PropModeReplace,
(unsigned char *)&normal, 1);
}
}
attributes.event_mask= EVENTMASK;
attributes.backing_store= NotUseful;
stWindow= XCreateWindow(stDisplay, stParent,
0, 0,
stWidth, stHeight,
0,
stDepth, InputOutput, stVisual,
valuemask, &attributes);
}
/* look for property changes on root window to track selection */
XSelectInput(stDisplay, DefaultRootWindow(stDisplay), PropertyChangeMask);
/* set the geometry hints */
if (!browserWindow)
{
XSizeHints *sizeHints= XAllocSizeHints();
sizeHints->min_width= 16;
sizeHints->min_height= 16;
sizeHints->width_inc= sizeof(void *);
sizeHints->height_inc= 1;
sizeHints->win_gravity= NorthWestGravity;
sizeHints->flags= PWinGravity | PResizeInc;
XSetWMNormalHints(stDisplay, stWindow, sizeHints);
XSetWMNormalHints(stDisplay, stParent, sizeHints);
XFree((void *)sizeHints);
}
/* set the window title and resource/class names */
{
XClassHint *classHints= XAllocClassHint();
classHints->res_class= xResClass;
classHints->res_name= xResName;
if (browserWindow == 0)
{
XSetClassHint(stDisplay, stParent, classHints);
XStoreName(stDisplay, stParent, defaultWindowLabel);
}
XFree((void *)classHints);
}
/* tell the WM that we can't be bothered managing focus for ourselves */
{
XWMHints *wmHints= XAllocWMHints();
wmHints->input= True;
wmHints->initial_state= NormalState;
wmHints->flags= InputHint|StateHint;
# if !defined(NO_ICON)
wmHints->icon_pixmap=
XCreateBitmapFromData(stDisplay, DefaultRootWindow(stDisplay),
sqXIcon_bits, sqXIcon_width, sqXIcon_height);
if (wmHints->icon_pixmap != None)
wmHints->flags |= IconPixmapHint;
# endif
if (iconified)
{
wmHints->initial_state= IconicState;
wmHints->flags |= StateHint;
}
XSetWMHints(stDisplay, stParent, wmHints);
XFree((void *)wmHints);
}
/* tell the WM that we do not want to be destroyed from the title bar close button */
{
wmProtocolsAtom= XInternAtom(stDisplay, "WM_PROTOCOLS", False);
wmDeleteWindowAtom= XInternAtom(stDisplay, "WM_DELETE_WINDOW", False);
XSetWMProtocols(stDisplay, stParent, &wmDeleteWindowAtom, 1);
}
/* create a suitable graphics context */
{
XGCValues gcValues;
gcValues.function= GXcopy;
gcValues.line_width= 0;
gcValues.subwindow_mode= ClipByChildren; /* was IncludeInferiors */
gcValues.clip_x_origin= 0;
gcValues.clip_y_origin= 0;
gcValues.clip_mask= None;
gcValues.foreground= SqueakWhite;
gcValues.background= SqueakWhite;
gcValues.fill_style= FillSolid;
stGC= XCreateGC(stDisplay,
stWindow,
GCFunction | GCLineWidth | GCSubwindowMode |
GCClipXOrigin | GCClipYOrigin | GCClipMask |
GCForeground | GCBackground | GCFillStyle,
&gcValues);
}
if (noTitle || fullScreen)
/* naughty, but effective */
XSetTransientForHint(stDisplay, stParent, DefaultRootWindow(stDisplay));
# if defined(USE_XSHM)
if (useXshm)
completionType= XShmGetEventBase(stDisplay) + ShmCompletion;
# endif
XInternAtoms(stDisplay, selectionAtomNames, SELECTION_ATOM_COUNT, False, selectionAtoms);
if (useXdnd)
dndInitialise();
}
void setWindowSize(void)
{
int width, height, maxWidth, maxHeight;
int winSize= getSavedWindowSize();
#if defined(DEBUG_BROWSER)
fprintf(stderr, "browserWindow %d\n", browserWindow);
#endif
if (browserWindow) return;
#if defined(DEBUG_WINDOW)
fprintf(stderr, "savedWindowSize %x (%d %d)\n", winSize, winSize >> 16, winSize & 0xffff);
#endif
if (winSize != 0)
{
width= (unsigned)winSize >> 16;
height= winSize & 0xFFFF;
}
else
{
width= 640;
height= 480;
}
/* minimum size is 64 x 64 */
width= ( width > 64) ? width : 64;
height= (height > 64) ? height : 64;
/* maximum size is screen size */
maxWidth= (DisplayWidth(stDisplay, DefaultScreen(stDisplay)));
maxHeight= (DisplayHeight(stDisplay, DefaultScreen(stDisplay)));
width= ( width <= maxWidth) ? width : maxWidth;
height= (height <= maxHeight) ? height : maxHeight;
if (fullScreen)
{
width= maxWidth;
height= maxHeight;
}
#if defined(DEBUG_WINDOW)
fprintf(stderr, "resize %d %d\n", width, height);
#endif
noteResize(stWidth= width, stHeight= height);
}
/*** Event Recording Functions ***/
/* Support for translateCode. For KeyPress set meta. For KeyRelease clear
* notmeta. Of course this is simplistic and wrong because it doesn't deal
* with left and right versions of the key. e.g. the key sequence
* press left press right lift left lift right will release before lift right.
*/
static inline int
withMetaSet(int code, int meta, int notmeta, int *modStatp, XKeyEvent *evt)
{
if (modStatp)
*modStatp = evt->type == KeyPress
? x2sqModifier(evt->state) | meta
: x2sqModifier(evt->state) & ~notmeta;
return code;
}
static int
translateCode(KeySym symbolic, int *modp, XKeyEvent *evt)
{
switch (symbolic)
{
case XK_Left: return 28;
case XK_Up: return 30;
case XK_Right: return 29;
case XK_Down: return 31;
case XK_Insert: return 5;
case XK_Prior: return 11; /* page up */
case XK_Next: return 12; /* page down */
case XK_Home: return 1;
case XK_End: return 4;
case XK_KP_Left: return 28;
case XK_KP_Up: return 30;
case XK_KP_Right: return 29;
case XK_KP_Down: return 31;
case XK_KP_Insert: return 5;
case XK_KP_Prior: return 11; /* page up */
case XK_KP_Next: return 12; /* page down */
case XK_KP_Home: return 1;
case XK_KP_End: return 4;
/* "aliases" for Sun keyboards */
case XK_R9: return 11; /* page up */
case XK_R15: return 12; /* page down */
case XK_R7: return 1; /* home */
case XK_R13: return 4; /* end */
/* if this is a key down event return the char with ALT/CommandKey set */
case XK_L1: /* stop */
return withMetaSet('.',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L2: /* again */
return withMetaSet('j',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L4: /* undo */
return withMetaSet('z',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L6: /* copy */
return withMetaSet('c',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L8: /* paste */
return withMetaSet('v',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L9: /* find */
return withMetaSet('f',CommandKeyBit,CommandKeyBit,modp,evt);
case XK_L10:/* cut */
return withMetaSet('x',CommandKeyBit,CommandKeyBit,modp,evt);
/* XKB extensions */
# if defined(XK_ISO_Left_Tab)
case XK_ISO_Left_Tab: return 9; /* shift-tab */
# endif
# if defined(XF86XK_Start)
case XF86XK_Start: /* OLPC view source */
return withMetaSet(',',CommandKeyBit,CommandKeyBit,modp,evt);
# endif
# if defined(XK_Control_L)
/* For XK_Shift_L, XK_Shift_R, XK_Caps_Lock & XK_Shift_Lock we can't just
* use the SHIFT metastate since it would generate key codes. We use
* META + SHIFT as these are all meta keys (meta == OptionKeyBit).
*/
case XK_Shift_L:
return withMetaSet(255,OptionKeyBit+ShiftKeyBit,ShiftKeyBit,modp,evt);
case XK_Shift_R:
return withMetaSet(254,OptionKeyBit+ShiftKeyBit,ShiftKeyBit,modp,evt);
case XK_Caps_Lock:
return withMetaSet(253,OptionKeyBit+ShiftKeyBit,ShiftKeyBit,modp,evt);
case XK_Shift_Lock:
return withMetaSet(252,OptionKeyBit+ShiftKeyBit,ShiftKeyBit,modp,evt);
case XK_Control_L:
return withMetaSet(251,OptionKeyBit+CtrlKeyBit,CtrlKeyBit,modp,evt);
case XK_Control_R:
return withMetaSet(250,OptionKeyBit+CtrlKeyBit,CtrlKeyBit,modp,evt);
case XK_Meta_L:
return withMetaSet(249,OptionKeyBit,0,modp,evt);
case XK_Meta_R:
return withMetaSet(248,OptionKeyBit,0,modp,evt);
case XK_Alt_L:
return withMetaSet(247,OptionKeyBit+CommandKeyBit,OptionKeyBit,modp,evt);
case XK_Alt_R:
return withMetaSet(246,OptionKeyBit+CommandKeyBit,OptionKeyBit,modp,evt);
# endif
default:;
}
return -1;
}
/*** I/O Primitives ***/
#if !defined(HAVE_SNPRINTF)
# if defined(HAVE___SNPRINTF) /* Solaris 2.5 */
extern int __snprintf(char *buf, size_t limit, const char *fmt, ...);
# define snprintf __snprintf
# define HAVE_SNPRINTF
# endif
#endif
static sqInt display_ioFormPrint(sqInt bitsIndex, sqInt width, sqInt height, sqInt depth, double hScale, double vScale, sqInt landscapeFlag)
{
# if defined(PRINT_PS_FORMS)
char *bitsAddr= pointerForOop(bitsIndex);
FILE *ppm;
float scale; /* scale to use with pnmtops */
char printCommand[1000];
unsigned int *form32; /* the form data, in 32 bits */
/* convert the form to 32 bits */
typedef void (*copyFn)(int *, int *, int, int, int, int, int, int);
static copyFn copyFns[33]= {
0,
copyImage1To32, /* 1 */
copyImage2To32, /* 2 */
0,
copyImage4To32, /* 4 */
0, 0, 0,
copyImage8To32, /* 8 */
0, 0, 0, 0, 0, 0,
copyImage16To32, /* 15 */
copyImage16To32, /* 16 */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
copyImage32To32 /* 32 */
};
copyFn copy= ((depth > 0) && (depth <= 32)) ? copyFns[depth] : 0;
if (!copy)
{
fprintf(stderr, "ioFormPrint: depth %d not supported\n", depth);
return false;
}
form32= malloc(width * height * 4);
if (!form32)
{
fprintf(stderr, "ioFormPrint: out of memory\n");
return false;
}
copy((int *)bitsAddr, (int *)form32, width, height, 1, 1, width, height);
/* pick a scale. unfortunately, pnmtops requires the same scale
horizontally and vertically */
if (hScale < vScale)
scale= hScale;
else
scale= vScale;
/* assemble the command for printing. pnmtops is part of "netpbm",
a widely-available set of tools that eases image manipulation */
#if defined(HAVE_SNPRINTF)
snprintf(printCommand, sizeof(printCommand),
"pnmtops -scale %f %s | lpr",
scale,
(landscapeFlag ? "-turn" : "-noturn"));
#else /* if your OS is broken then so might be this code */
sprintf(printCommand,
"pnmtops -scale %f %s | lpr",
scale,
(landscapeFlag ? "-turn" : "-noturn"));
#endif
/* open a pipe to print through */
if ((ppm= popen(printCommand, "w")) == 0)
{
free(form32);
return false;
}
/* print the PPM magic number */
fprintf(ppm, "P3\n%d %d 255\n", width, height);
/* write the pixmap */
{
int y;
for (y= 0; y < height; ++y)
{
int x;
for (x= 0; x < width; ++x)
{
int pixel= form32[y*width + x];
int red= (pixel >> 16) & 0xFF;
int green= (pixel >> 8) & 0xFF;
int blue= (pixel >> 0) & 0xFF;
fprintf(ppm, "%d %d %d\n", red, green, blue);
}
}
}
free(form32);
pclose(ppm);
return true;
# else /* !PRINT_PS_FORMS */
/* Write the form as a PPM (Portable PixMap) file, from which it can
be converted into almost any existing graphical format (including
PostScript). See the "netpbm" utilities for a huge collection of
image manipulation tools that understand the PPM format.
Note that "xv" can also read, convert, and do image processing on
PPM files.
The output filename is defined in "sqPlatformSpecific.h". */
FILE *ppm;
int ok= true;
if ((ppm= fopen(SQ_FORM_FILENAME, "wb")) == 0)
return false;
/* PPM magic number and pixmap header */
fprintf(ppm, "P3\n%d %d 65535\n", width, height);
switch (depth)
{
case 8:
{
unsigned char *bits= (unsigned char *) bitsAddr;
int ppw= 32 / depth;
int raster= ((width + ppw - 1) / ppw) * 4;
/* stColors[] is too approximate: query the real colormap */
XColor colors[256];
int i;
for (i= 0; i < 256; ++i) colors[i].pixel= i;
/* all colors in one query reduces server traffic */
XQueryColors(stDisplay, stColormap, colors, 256);
/* write the pixmap */
{
int y;
for (y= 0; y < height; ++y) {
int x;
for (x= 0; x < width; ++x) {
/* everything is backwards (as usual ;) */
int index= y * raster + x;
int byte= 3 - (index & 0x00000003);
int word= index & -4;
int pixel= bits[word + byte];
fprintf(ppm, "%d %d %d\n",
colors[pixel].red, colors[pixel].green, colors[pixel].blue);
}
}
}
break;
} /* case 8 */
default:
fprintf(stderr, "ioFormPrint: depth %d not supported.\n", depth);
ok= false;
break;
} /* switch */
fclose(ppm);
return ok;
# endif /* !PRINT_PS_FORMS */
}
static sqInt display_ioBeep(void)
{
if (isConnectedToXServer)
XBell(stDisplay, 0); /* ring at default volume */
return 0;
}
static sqInt display_ioRelinquishProcessorForMicroseconds(sqInt microSeconds)
{
aioSleepForUsecs(handleEvents() ? 0 : microSeconds);
return 0;
}
static sqInt display_ioProcessEvents(void)
{
LogEventChain((dbgEvtChF,"ioPE."));
handleEvents();
aioPoll(0);
return 0;
}
/* returns the depth of the Squeak window */
static sqInt display_ioScreenDepth(void)
{
Window root;
int x, y;
unsigned int w, h, b, d;
if (!isConnectedToXServer)
return 1;
XGetGeometry(stDisplay, stParent, &root, &x, &y, &w, &h, &b, &d);
return d;
}
static double display_ioScreenScaleFactor(void)
{
return 1.0;
}
/* returns the size of the Squeak window */
static sqInt display_ioScreenSize(void)
{
int winSize= getSavedWindowSize();
if (headless || !isConnectedToXServer)
return winSize ? winSize : ((64 << 16) | 64);
if ((windowState == WIN_ZOOMED) && !resized())
return (scrW << 16) | scrH;
if (resized())
{
windowState= WIN_NORMAL;
# if defined (USE_XSHM)
if (useXshm && !isAligned(void *, xWidth))
{
xWidth= align(void *, xWidth);
if (!browserWindow)
{
XResizeWindow(stDisplay, stParent, xWidth, xHeight);
}
}
# endif
XResizeWindow(stDisplay, stWindow, (stWidth= xWidth), (stHeight= xHeight));
}
return (stWidth << 16) | stHeight; /* w is high 16 bits; h is low 16 bits */
}
static unsigned char swapBits(unsigned char in)
{
unsigned char out= 0;
int i;
for (i= 0; i < 8; i++)
{
out= (out << 1) + (in & 1);
in >>= 1;
}
return out;
}
static int fakeBigCursor()
{
static int fake= -1;
if (-1 == fake)
{
char *value= getenv("SQUEAK_FAKEBIGCURSOR");
fake= value && (atoi(value) > 0);
}
return fake;
}
static sqInt display_ioSetCursorWithMaskBig(sqInt cursorBitsIndex, sqInt cursorMaskIndex, sqInt offsetX, sqInt offsetY);
static sqInt display_ioSetCursorWithMask(sqInt cursorBitsIndex, sqInt cursorMaskIndex, sqInt offsetX, sqInt offsetY)
{
unsigned int *cursorBits= (unsigned int *)pointerForOop(cursorBitsIndex);
unsigned int *cursorMask= (unsigned int *)pointerForOop(cursorMaskIndex);
unsigned char data[32], mask[32]; /* cursors are always 16x16 */
int i;
Cursor cursor;
Pixmap dataPixmap, maskPixmap;
if (!isConnectedToXServer)
return 0;
if (fakeBigCursor())
return display_ioSetCursorWithMaskBig(cursorBitsIndex, cursorMaskIndex, offsetX, offsetY);
if (cursorMaskIndex == null)
cursorMask= cursorBits;
for (i= 0; i < 16; i++)
{
data[i*2+0]= (cursorBits[i] >> 24) & 0xFF;
data[i*2+1]= (cursorBits[i] >> 16) & 0xFF;
mask[i*2+0]= (cursorMask[i] >> 24) & 0xFF;
mask[i*2+1]= (cursorMask[i] >> 16) & 0xFF;
}
/* if (BitmapBitOrder(stDisplay) == LSBFirst)*/
{
/* the bytes are always in the right order: swap only bits within bytes */
char *dp= (char *)data;
char *mp= (char *)mask;
for (i= 0; i < 32; i++)
{
dp[i]= swapBits(dp[i]);
mp[i]= swapBits(mp[i]);
}
}
dataPixmap= XCreateBitmapFromData(stDisplay,
DefaultRootWindow(stDisplay),
(char *)data, 16, 16);
maskPixmap= XCreateBitmapFromData(stDisplay,
DefaultRootWindow(stDisplay),
(char *)mask, 16, 16);
cursor= XCreatePixmapCursor(stDisplay, dataPixmap, maskPixmap,
&stColorBlack, &stColorWhite,
-offsetX, -offsetY);
XFreePixmap(stDisplay, dataPixmap);
XFreePixmap(stDisplay, maskPixmap);
if (cursor != None)
XDefineCursor(stDisplay, stWindow, cursor);
XFreeCursor(stDisplay, cursor);
return 0;
}
static sqInt display_ioSetCursorWithMaskBig(sqInt cursorBitsIndex, sqInt cursorMaskIndex, sqInt offsetX, sqInt offsetY)
{
unsigned int *cursorBits= (unsigned int *)pointerForOop(cursorBitsIndex);
unsigned int *cursorMask= (unsigned int *)pointerForOop(cursorMaskIndex);
unsigned int data[32], mask[32], d, m; /* cursors are rescaled from 16x16 to 32x32*/
int i, j;
Cursor cursor;
Pixmap dataPixmap, maskPixmap;
if (!isConnectedToXServer)
return 0;
if (cursorMaskIndex == null)
cursorMask= cursorBits;
for (i= 0; i < 32; i++)
{
for (j= 0; j < 32; j++)
{
d= (d<<1) | ((cursorBits[i/2] >> (16 + j/2)) & 1);
m= (m<<1) | ((cursorMask[i/2] >> (16 + j/2)) & 1);
}
data[i]= d;
mask[i]= m;
}
dataPixmap= XCreateBitmapFromData(stDisplay,
DefaultRootWindow(stDisplay),
(char *)data, 32, 32);
maskPixmap= XCreateBitmapFromData(stDisplay,
DefaultRootWindow(stDisplay),
(char *)mask, 32, 32);
cursor= XCreatePixmapCursor(stDisplay, dataPixmap, maskPixmap,
&stColorBlack, &stColorWhite,
-offsetX*2, -offsetY*2);
XFreePixmap(stDisplay, dataPixmap);
XFreePixmap(stDisplay, maskPixmap);
if (cursor != None)
XDefineCursor(stDisplay, stWindow, cursor);
XFreeCursor(stDisplay, cursor);
return 0;
}
#if 0
sqInt ioSetCursor(sqInt cursorBitsIndex, sqInt offsetX, sqInt offsetY)
{
/* Deprecated: forward to new version with explicit mask. */
ioSetCursorWithMask(cursorBitsIndex, null, offsetX, offsetY);
return 0;
}
#endif
static sqInt display_ioSetCursorARGB(sqInt cursorBitsIndex, sqInt extentX, sqInt extentY, sqInt offsetX, sqInt offsetY)
{
#if defined(HAVE_LIBXRENDER) && (RENDER_MAJOR > 0 || RENDER_MINOR >= 5)
int eventbase, errorbase;
int major= 0, minor= 0;
XImage *image;
Pixmap pixmap;
GC gc;
XRenderPictFormat *pictformat;
Picture picture;
Cursor cursor;
if (fakeBigCursor())
return 0;
if (!XRenderQueryExtension(stDisplay, &eventbase, &errorbase))
return 0;
XRenderQueryVersion(stDisplay, &major, &minor);
if (!(major > 0 || minor >= 5))
return 0;
image= XCreateImage(stDisplay, DefaultVisual(stDisplay, DefaultScreen(stDisplay)), 32, ZPixmap, 0, (char *)pointerForOop(cursorBitsIndex), extentX, extentY, 32, 0);
pixmap= XCreatePixmap (stDisplay, DefaultRootWindow(stDisplay), extentX, extentY, 32);
gc= XCreateGC(stDisplay, pixmap, 0, 0);
XPutImage(stDisplay, pixmap, gc, image, 0, 0, 0, 0, extentX, extentY);
image->data= 0; /* otherwise XDestroyImage tries to free this */
pictformat= XRenderFindStandardFormat(stDisplay, PictStandardARGB32);
picture= XRenderCreatePicture(stDisplay, pixmap, pictformat, 0, 0);
cursor= XRenderCreateCursor(stDisplay, picture, -offsetX, -offsetY);
XDefineCursor(stDisplay, stWindow, cursor);
XDestroyImage(image);
XFreeGC(stDisplay, gc);
XFreeCursor(stDisplay, cursor);
XRenderFreePicture(stDisplay, picture);
XFreePixmap(stDisplay, pixmap);
return 1;
#else
return 0;
#endif
}
static void overrideRedirect(Display *dpy, Window win, int flag)
{
XSetWindowAttributes attrs;
attrs.override_redirect= flag;
XChangeWindowAttributes(dpy, win, CWOverrideRedirect, &attrs);
}
static void enterFullScreenMode(Window root)
{
XSynchronize(stDisplay, True);
overrideRedirect(stDisplay, stWindow, True);
XReparentWindow(stDisplay, stWindow, root, 0, 0);
#if 1
XResizeWindow(stDisplay, stWindow, scrW, scrH);
#else
XResizeWindow(stDisplay, stParent, scrW, scrH);
#endif
XLowerWindow(stDisplay, stParent);
XRaiseWindow(stDisplay, stWindow);
XSetInputFocus(stDisplay, stWindow, RevertToPointerRoot, CurrentTime);
XSynchronize(stDisplay, False);
}
static void returnFromFullScreenMode()
{
XSynchronize(stDisplay, True);
XRaiseWindow(stDisplay, stParent);
XReparentWindow(stDisplay, stWindow, stParent, 0, 0);
overrideRedirect(stDisplay, stWindow, False);
#if 1
XResizeWindow(stDisplay, stWindow, scrW, scrH);
#else
XResizeWindow(stDisplay, stParent, winW, winH);
#endif
XSetInputFocus(stDisplay, stWindow, RevertToPointerRoot, CurrentTime);
XSynchronize(stDisplay, False);
}
static void sendFullScreenHint(int enable)
{
XEvent xev;
Atom wm_state = XInternAtom(stDisplay, "_NET_WM_STATE", False);
Atom fullscreen = XInternAtom(stDisplay, "_NET_WM_STATE_FULLSCREEN", False);
memset(&xev, 0, sizeof(xev));
xev.type = ClientMessage;
xev.xclient.window = stParent;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = enable; /* 1 enable, 0 disable fullscreen */
xev.xclient.data.l[1] = fullscreen;
xev.xclient.data.l[2] = 0;
XSendEvent(stDisplay, DefaultRootWindow(stDisplay), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
}
static sqInt display_ioSetFullScreen(sqInt fullScreen)
{
int winX, winY;
unsigned int winW, winH;
setFullScreenFlag(fullScreen);
if (!isConnectedToXServer)
return 1;
if (fullScreen)
{
/* setting full-screen mode */
if (savedWindowOrigin == -1)
{
/* EITHER: no previous call, OR: previous call disabled full-screen mode */
Window root;
{
/* need extent only */
unsigned int b, d;
XGetGeometry(stDisplay, stWindow, &root, &winX, &winY, &winW, &winH, &b, &d);
}
/* width must be a multiple of sizeof(void *), or X[Shm]PutImage goes gaga */
if ((winW % sizeof(void *)) != 0)
winW= (winW / sizeof(void *)) * sizeof(void *);
setSavedWindowSize((winW << 16) + (winH & 0xFFFF));
savedWindowOrigin= (winX << 16) + (winY & 0xFFFF);
if (fullScreenDirect)
enterFullScreenMode(root); /* simple window manager, e.g. twm */
else
sendFullScreenHint(1); /* Required for Compiz window manager */
windowState= WIN_ZOOMED;
fullDisplayUpdate();
}
}
else
{
/* reverting to sub-screen mode */
if (savedWindowOrigin != -1)
{ /* previous call enabled full-screen mode */
/* get old window size */
int winSize= getSavedWindowSize();
winW= (unsigned)winSize >> 16;
winH= winSize & 0xFFFF;
/* minimum size is 64 x 64 */
winW= (winW > 64) ? winW : 64;
winH= (winH > 64) ? winH : 64;
/* old origin */
winX= savedWindowOrigin >> 16;
winY= savedWindowOrigin & 0xFFFF;
savedWindowOrigin= -1; /* prevents consecutive full-screen disables */
if (fullScreenDirect)
returnFromFullScreenMode(); /* simple window manager, e.g. twm */
else
sendFullScreenHint(0); /* Required for Compiz window manager */
windowState= WIN_CHANGED;
}
}
/* sync avoids race with ioScreenSize() reading geometry before resize event */
XSync(stDisplay, False);
getMousePosition();
return 1;
}
/*** shared-memory stuff ***/
# if defined(USE_XSHM)
static int shmError(Display *dpy, XErrorEvent *evt)
{
char buf[2048];
XGetErrorText(stDisplay, evt->error_code, buf, sizeof(buf));
fprintf(stderr, "XShmAttach: %s\n", buf);
return 0;
}
#endif
static void *stMalloc(size_t lbs)
{
# if defined(USE_XSHM)
if (useXshm)
{
if ((stShmInfo.shmid= shmget(IPC_PRIVATE, lbs, IPC_CREAT|0777)) == -1)
perror("shmget");
else
{
if ((long)(stShmInfo.shmaddr= (char *)shmat(stShmInfo.shmid, 0, 0)) == -1)
perror("shmat");
else
{
/* temporarily install error handler */
XErrorHandler prev= XSetErrorHandler(shmError);
int result= 0;
stShmInfo.readOnly= False;
result= XShmAttach(stDisplay, &stShmInfo);
XSync(stDisplay, False);
XSetErrorHandler(prev);
if (result)
{
# if defined(__linux__)
/* destroy ID now; segment will be destroyed at exit */
shmctl(stShmInfo.shmid, IPC_RMID, 0);
# endif
return stShmInfo.shmaddr;
}
shmdt(stShmInfo.shmaddr);
}
/* could not attach to allocated shared memory segment */
shmctl(stShmInfo.shmid, IPC_RMID, 0);
}
/* could not allocate shared memory segment */
useXshm= 0;
}
# endif /* USE_XSHM */
return (void *)malloc(lbs);
}
static void stFree(void *addr)
{
#if defined(USE_XSHM)
if (!useXshm)
#endif
{
free(addr);
return;
}
#if defined(USE_XSHM)
shmdt(stShmInfo.shmaddr);
shmctl(stShmInfo.shmid, IPC_RMID, NULL);
#endif
}
#if defined(USE_XSHM)
static void shmExit(void)
{
if (stDisplayBitmap && useXshm)
{
stFree(stDisplayBitmap);
stDisplayBitmap= 0;
}
}
#endif
static XImage *stXCreateImage(Display *display, Visual *visual,
int depth, int format, int flags, char *data,
int width, int height, int bpp, int pad)
{
#if defined(USE_XSHM)
if (!useXshm)
#endif
return XCreateImage(display, visual, depth, format, flags,
data, width, height, bpp, pad);
#if defined(USE_XSHM)
return XShmCreateImage(display, visual, depth, format, data,
&stShmInfo, width, height);
#endif
}
static void stXPutImage(Display *display, Window window, GC gc, XImage *image,
int src_x, int src_y, int dst_x, int dst_y, int w, int h)
{
#if defined(USE_XSHM)
if (!useXshm)
#endif
{
XPutImage(display, window, gc, image, src_x, src_y, dst_x, dst_y, w, h);
return;
}
#if defined(USE_XSHM)
XShmPutImage(display, window, gc, image, src_x, src_y, dst_x, dst_y, w, h, True);
++completions;
if (!asyncUpdate)
waitForCompletions();
#endif
}
static void stXDestroyImage(XImage *image)
{
#if defined(USE_XSHM)
if (useXshm)
XShmDetach(stDisplay, &stShmInfo);
#endif
XDestroyImage(image);
}
#define bytesPerLine(width, depth) ((((width)*(depth) + 31) >> 5) << 2)
#define bytesPerLineRD(width, depth) ((((width)*(depth)) >> 5) << 2)
static sqInt display_ioForceDisplayUpdate(void)
{
#if defined(USE_XSHM)
if (asyncUpdate && isConnectedToXServer)
{
XFlush(stDisplay);
waitForCompletions();
}
#endif
return 0;
}
static sqInt display_ioShowDisplay(sqInt dispBitsIndex, sqInt width, sqInt height, sqInt depth,
sqInt affectedL, sqInt affectedR, sqInt affectedT, sqInt affectedB)
{
static char *stDisplayBits= 0; /* last known oop of the VM's Display */
static sqInt stDisplayWidth= 0; /* ditto width */
static sqInt stDisplayHeight= 0; /* ditto height */
static sqInt stDisplayDepth= 0; /* ditto depth */
char *dispBits= pointerForOop(dispBitsIndex);
int geometryChanged= ((stDisplayBits != dispBits)
|| (stDisplayWidth != width)
|| (stDisplayHeight != height)
|| (stDisplayDepth != depth));
if (stWindow == 0)
return 0;
if ((width < 1) || (height < 1))
return 0;
if (affectedL > width) affectedL= width;
if (affectedR > width) affectedR= width;
if (affectedT > height) affectedT= height;
if (affectedB > height) affectedB= height;
if ((affectedL > affectedR) || (affectedT > affectedB))
return 0;
if (!(depth == 1 || depth == 2 || depth == 4
|| depth == 8 || depth == 16 || depth == 32))
{
fprintf(stderr, "depth %d is not supported\n", depth);
exit(1);
return 0;
}
if (resized())
return 0;
if (geometryChanged)
{
stDisplayBits= dispBits;
stDisplayWidth= width;
stDisplayHeight= height;
stDisplayDepth= depth;
# if defined(USE_XSHM)
if (asyncUpdate)
/* wait for pending updates to complete before freeing the XImage */
waitForCompletions();
# endif
stDisplayBits= dispBits;
if (stImage)
{
stImage->data= 0; /* don't you dare free() Display's Bitmap! */
stXDestroyImage(stImage);
if (stDisplayBitmap)
{
stFree(stDisplayBitmap);
stDisplayBitmap= 0;
}
}
# if !defined(USE_XSHM)
# define useXshm 0
# endif
# if defined(WORDS_BIGENDIAN)
if (!useXshm && depth == stBitsPerPixel &&
(depth != 16 || stHasSameRGBMask16) &&
(depth != 32 || stHasSameRGBMask32))
# else
if (!useXshm && depth == stBitsPerPixel && depth == 32 && stHasSameRGBMask32)
# endif
{
stDisplayBitmap= 0;
}
else
{
stDisplayBitmap= stMalloc(bytesPerLine(width, stBitsPerPixel) * height);
}
# if !defined(USE_XSHM)
# undef useXshm
# endif
stImage= stXCreateImage(stDisplay,
DefaultVisual(stDisplay, DefaultScreen(stDisplay)),
stDepth,
ZPixmap,
0,
(stDisplayBitmap
? stDisplayBitmap
: stDisplayBits),
width,
height,
32,
0);
/* Xlib ignores the following */
# if defined(WORDS_BIGENDIAN)
stImage->byte_order= MSBFirst;
stImage->bitmap_bit_order= MSBFirst;
# else
stImage->byte_order= LSBFirst;
stImage->bitmap_bit_order= LSBFirst;
# endif
/* not really required (since we never call Get/PutPixel), but what the hey */
/*
if (!XInitImage(stImage))
fprintf(stderr, "XInitImage failed (but we don't care)\n");
*/
}
/* this can happen after resizing the window */
if (affectedR > width) affectedR= width;
if (affectedB > height) affectedB= height;
if ((affectedR <= affectedL) || (affectedT >= affectedB))
return 1;
if (depth != stBitsPerPixel)
{
if (depth == 1)
{
if (stBitsPerPixel == 8)
{
copyImage1To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
if (stBitsPerPixel == 16)
{
copyImage1To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stBitsPerPixel == 24)
{
copyImage1To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitsPerPixel == 32 */
{
copyImage1To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
else if (depth == 2)
{
if (stBitsPerPixel == 8)
{
copyImage2To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
if (stBitsPerPixel == 16)
{
copyImage2To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stBitsPerPixel == 24)
{
copyImage2To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitsPerPixel == 32 */
{
copyImage2To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
else if (depth == 4)
{
if (stBitsPerPixel == 8)
{
copyImage4To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
if (stBitsPerPixel == 16)
{
copyImage4To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stBitsPerPixel == 24)
{
copyImage4To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitsPerPixel == 32 */
{
copyImage4To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
else if (depth == 8)
{
if (stBitsPerPixel == 16)
{
copyImage8To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stBitsPerPixel == 24)
{
copyImage8To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitsPerPixel == 32 */
{
copyImage8To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
else if (depth == 16)
{
if (stBitsPerPixel == 8)
{
copyImage16To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if ( stBitsPerPixel == 24)
{
copyImage16To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitsPerPixel == 32 */
{
copyImage16To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
else /* depth == 32 */
{
if (stBitsPerPixel == 8)
{
copyImage32To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stBitsPerPixel == 16)
{
copyImage32To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else /* stBitPerPixel == 24 */
{
copyImage32To24((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
}
else /* depth == stBitsPerPixel */
{
if (depth == 16 && !stHasSameRGBMask16)
{
copyImage16To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (depth == 32 && !stHasSameRGBMask32)
{
copyImage32To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
# if defined(WORDS_BIGENDIAN)
# if defined(USE_XSHM)
else if (useXshm)
{
if (depth == 8)
{
copyImage8To8((int *)dispBits, (int *)stDisplayBitmap,
width, height,affectedL, affectedT, affectedR, affectedB);
}
else if (depth == 16)
{
copyImage16To16((int *)dispBits, (int *)stDisplayBitmap,
width, height,affectedL, affectedT, affectedR, affectedB);
}
else if (depth == 32)
{
copyImage32To32((int *)dispBits, (int *)stDisplayBitmap,
width, height,affectedL, affectedT, affectedR, affectedB);
}
else
{
fprintf(stderr, "shared memory not supported for this depth/byte-order\n");
exit(1);
}
}
# endif
# else /* !WORDS_BIGENDIAN */
else if (depth == 8)
{
copyReverseImageBytes((int *)dispBits, (int *)stDisplayBitmap,
depth, width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (depth == 16)
{
copyReverseImageWords((int *)dispBits, (int *)stDisplayBitmap,
depth, width, height,
affectedL, affectedT, affectedR, affectedB);
}
else if (stDisplayBitmap != 0)
{
/* there is a separate map, so we still need to copy */
if (depth == 32)
{
copyImage32To32Same((int *)dispBits, (int *)stDisplayBitmap,
width, height,
affectedL, affectedT, affectedR, affectedB);
}
}
# endif
}
stXPutImage(stDisplay, stWindow, stGC, stImage,
affectedL, affectedT, /* src_x, src_y */
affectedL, affectedT, /* dst_x, dst_y */
affectedR-affectedL, /* width */
affectedB-affectedT); /* height */
return 0;
}
static sqInt display_ioHasDisplayDepth(sqInt i)
{
switch (i)
{
case 1:
case 2:
case 4:
return stBitsPerPixel == 32;
case 8:
case 16:
case 32:
return true;
}
return false;
}
static sqInt display_ioSetDisplayMode(sqInt width, sqInt height, sqInt depth, sqInt fullscreenFlag)
{
fprintf(stderr, "ioSetDisplayMode(%d, %d, %d, %d)\n",
width, height, depth, fullscreenFlag);
setSavedWindowSize((width << 16) + (height & 0xFFFF));
setFullScreenFlag(fullScreen);
return 0;
}
void copyReverseImageBytes(int *fromImageData, int *toImageData, int depth, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
register int scanLine, firstWord, lastWord;
register int line;
scanLine= bytesPerLine(width, depth);
firstWord= scanLine*affectedT + bytesPerLineRD(affectedL, depth);
lastWord= scanLine*affectedT + bytesPerLine(affectedR, depth);
for (line= affectedT; line < affectedB; line++)
{
register unsigned char *from= (unsigned char *)((long)fromImageData+firstWord);
register unsigned char *limit= (unsigned char *)((long)fromImageData+lastWord);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord);
while (from < limit)
{
to[0]= from[3];
to[1]= from[2];
to[2]= from[1];
to[3]= from[0];
from+= 4;
to+= 4;
}
firstWord+= scanLine;
lastWord+= scanLine;
}
}
void copyReverseImageWords(int *fromImageData, int *toImageData, int depth, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
register int scanLine, firstWord, lastWord;
register int line;
scanLine= bytesPerLine(width, depth);
firstWord= scanLine*affectedT + bytesPerLineRD(affectedL, depth);
lastWord= scanLine*affectedT + bytesPerLine(affectedR, depth);
for (line= affectedT; line < affectedB; line++)
{
register unsigned short *from= (unsigned short *)((long)fromImageData+firstWord);
register unsigned short *limit= (unsigned short *)((long)fromImageData+lastWord);
register unsigned short *to= (unsigned short *)((long)toImageData+firstWord);
while (from < limit)
{
to[0]= from[1];
to[1]= from[0];
from+= 2;
to+= 2;
}
firstWord+= scanLine;
lastWord+= scanLine;
}
}
void copyImage1To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 1 not yet implemented in 8 bpp\n");
exit(1);
}
void copyImage2To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 2 not yet implemented in 8 bpp\n");
exit(1);
}
void copyImage4To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 4 not yet implemented in 8 bpp\n");
exit(1);
}
void copyImage8To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
register int scanLine, firstWord, lastWord;
register int line;
scanLine= bytesPerLine(width, 8);
firstWord= scanLine*affectedT + bytesPerLineRD(affectedL, 8);
lastWord= scanLine*affectedT + bytesPerLine(affectedR, 8);
for (line= affectedT; line < affectedB; line++) {
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord);
while (from < limit)
*to++= *from++;
firstWord+= scanLine;
lastWord+= scanLine;
}
}
void copyImage1To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 1 not yet implemented in 16 bpp\n");
exit(1);
}
void copyImage2To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 2 not yet implemented in 16 bpp\n");
exit(1);
}
void copyImage4To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 4 not yet implemented in 16 bpp\n");
exit(1);
}
void copyImage8To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine8, firstWord8, lastWord8;
int scanLine16, firstWord16;
register int line;
scanLine8= bytesPerLine(width, 8);
firstWord8= scanLine8*affectedT + bytesPerLineRD(affectedL, 8);
lastWord8= scanLine8*affectedT + bytesPerLine(affectedR, 8);
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + (bytesPerLineRD(affectedL, 8) << 1);
for (line= affectedT; line < affectedB; line++)
{
register unsigned char *from= (unsigned char *)((long)fromImageData+firstWord8);
register unsigned char *limit= (unsigned char *)((long)fromImageData+lastWord8);
register unsigned short *to= (unsigned short *)((long)toImageData+firstWord16);
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
to[0]= stColors[from[0]];
to[1]= stColors[from[1]];
to[2]= stColors[from[2]];
to[3]= stColors[from[3]];
# else
to[0]= stColors[from[3]];
to[1]= stColors[from[2]];
to[2]= stColors[from[1]];
to[3]= stColors[from[0]];
# endif
from+= 4;
to+= 4;
}
firstWord8+= scanLine8;
lastWord8+= scanLine8;
firstWord16+= scanLine16;
}
}
void copyImage16To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine16, firstWord16, lastWord16;
int scanLine8, firstWord8;
int line;
#define map16To8(w) (col= (w), stDownGradingColors[ \
(((col >> (10+(5-3))) & 0x7) << 5) | \
(((col >> (5+(5-3))) & 0x7) << 2) | \
((col >> (0+(5-2))) & 0x7)])
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + bytesPerLineRD(affectedL, 16);
lastWord16= scanLine16*affectedT + bytesPerLine(affectedR, 16);
scanLine8= bytesPerLine(width, 8);
firstWord8= scanLine8*affectedT + (bytesPerLineRD(affectedL, 16) >> 1);
for (line= affectedT; line < affectedB; line++)
{
register int col;
register unsigned short *from= (unsigned short *)((long)fromImageData+firstWord16);
register unsigned short *limit= (unsigned short *)((long)fromImageData+lastWord16);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord8);
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
to[0]= map16To8(from[0]);
to[1]= map16To8(from[1]);
# else
to[0]= map16To8(from[1]);
to[1]= map16To8(from[0]);
# endif
from+= 2;
to+= 2;
}
firstWord16+= scanLine16;
lastWord16+= scanLine16;
firstWord8+= scanLine8;
}
#undef map16To8
}
void copyImage1To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine1, firstWord1, firstShift1;
int scanLine32, firstWord32, lastWord32;
int line;
scanLine1= bytesPerLine(width, 1);
firstWord1= scanLine1*affectedT + bytesPerLineRD(affectedL, 1);
firstShift1= 31 - (affectedL & 31);
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLine(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord1);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)toImageData+lastWord32);
register int shift= firstShift1;
while (to < limit)
{
*to= stColors[(*from >> shift) & 1];
to++;
shift--;
if (shift < 0)
{
shift= 31;
from++;
}
}
firstWord1+= scanLine1;
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
}
void copyImage2To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine2, firstWord2, firstShift2;
int scanLine32, firstWord32, lastWord32;
int line;
scanLine2= bytesPerLine(width, 2);
firstWord2= scanLine2*affectedT + bytesPerLineRD(affectedL, 2);
firstShift2= 30 - ((affectedL & 15) * 2);
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLineRD(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord2);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)toImageData+lastWord32);
register int shift= firstShift2;
while (to < limit)
{
*to= stColors[(*from >> shift) & 3];
to++;
shift-= 2;
if (shift < 0)
{
shift= 30;
from++;
}
}
firstWord2+= scanLine2;
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
}
void copyImage4To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine4, firstWord4, firstShift4;
int scanLine32, firstWord32, lastWord32;
int line;
scanLine4= bytesPerLine(width, 4);
firstWord4= scanLine4*affectedT + bytesPerLineRD(affectedL, 4);
firstShift4= 28 - ((affectedL & 7) * 4);
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLineRD(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord4);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)toImageData+lastWord32);
register int shift= firstShift4;
while (to < limit)
{
*to= stColors[(*from >> shift) & 15];
to++;
shift-= 4;
if (shift < 0)
{
shift= 28;
from++;
}
}
firstWord4+= scanLine4;
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
}
void copyImage8To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine8, firstWord8, lastWord8;
int scanLine32, firstWord32;
int line;
scanLine8= bytesPerLine(width, 8);
firstWord8= scanLine8*affectedT + bytesPerLineRD(affectedL, 8);
lastWord8= scanLine8*affectedT + bytesPerLine(affectedR, 8);
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + (bytesPerLineRD(affectedL, 8) << 2);
for (line= affectedT; line < affectedB; line++)
{
register unsigned char *from= (unsigned char *)((long)fromImageData+firstWord8);
register unsigned char *limit= (unsigned char *)((long)fromImageData+lastWord8);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
to[0]= stColors[from[0]];
to[1]= stColors[from[1]];
to[2]= stColors[from[2]];
to[3]= stColors[from[3]];
# else
to[0]= stColors[from[3]];
to[1]= stColors[from[2]];
to[2]= stColors[from[1]];
to[3]= stColors[from[0]];
# endif
from+= 4;
to+= 4;
}
firstWord8+= scanLine8;
lastWord8+= scanLine8;
firstWord32+= scanLine32;
}
}
void copyImage1To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 1 not yet implemented in 24 bpp\n");
exit(1);
}
void copyImage2To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 2 not yet implemented in 24 bpp\n");
exit(1);
}
void copyImage4To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
fprintf(stderr, "depth 4 not yet implemented in 24 bpp\n");
exit(1);
}
void copyImage8To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine8, firstWord8, lastWord8;
int scanLine24, firstWord24;
int line;
scanLine8= bytesPerLine(width, 8);
firstWord8= scanLine8*affectedT + bytesPerLineRD(affectedL, 8);
lastWord8= scanLine8*affectedT + bytesPerLine(affectedR, 8);
scanLine24= bytesPerLine(width, 24);
firstWord24= scanLine24*affectedT + ((affectedL>>2) * 12);
for (line= affectedT; line < affectedB; line++)
{
register unsigned char *from= (unsigned char *)((long)fromImageData+firstWord8);
register unsigned char *limit= (unsigned char *)((long)fromImageData+lastWord8);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord24);
register unsigned int newpix= 0;
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
newpix= stColors[from[0]];
# else
newpix= stColors[from[3]];
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
# if defined(WORDS_BIGENDIAN)
newpix= stColors[from[1]];
# else
newpix= stColors[from[2]];
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
# if defined(WORDS_BIGENDIAN)
newpix= stColors[from[2]];
# else
newpix= stColors[from[1]];
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
# if defined(WORDS_BIGENDIAN)
newpix= stColors[from[3]];
# else
newpix= stColors[from[0]];
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
from+= 4;
}
firstWord8+= scanLine8;
lastWord8+= scanLine8;
firstWord24+= scanLine24;
}
}
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
extern void armSimdConvert_x888_8_LEPacking32_8_wide(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride,
unsigned int halftone, unsigned int halftoneInfo,
unsigned int *colourMap);
extern void armSimdConvert_x888_8_LEPacking32_8_narrow(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride,
unsigned int halftone, unsigned int halftoneInfo,
unsigned int *colourMap);
static void armSimdCopyImage32To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB,
unsigned int *downGradingColors)
{
/* Find image strides in 32-bit words */
unsigned int srcStride= width;
unsigned int dstStride= (width + 3) >> 2;
/* Round affected region out to encompass complete words in both images */
affectedL &= ~3;
affectedR= (affectedR + 3) &~ 3;
width= affectedR - affectedL;
height= affectedB - affectedT;
/* Find first words */
fromImageData += srcStride * affectedT + affectedL;
toImageData += dstStride * affectedT + (affectedL >> 2);
/* Adjust strides to remove number of words read/written */
srcStride -= affectedR - affectedL;
dstStride -= (affectedR - affectedL) >> 2;
/* Work out which width class this operation is. */
if (width > (128 - 32) / 8 && ((-1 ^ (width -(128 - 32) / 8)) & ~(31 / 8)))
armSimdConvert_x888_8_LEPacking32_8_wide(width, height, toImageData, dstStride, fromImageData, srcStride, 0, 0, downGradingColors);
else
armSimdConvert_x888_8_LEPacking32_8_narrow(width, height, toImageData, dstStride, fromImageData, srcStride, 0, 0, downGradingColors);
}
# else
# error configuration error
# endif
#endif
void copyImage32To8(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
armSimdCopyImage32To8(fromImageData, toImageData, width, height, affectedL, affectedT, affectedR, affectedB, stDownGradingColors);
# else
# error configuration error
# endif
#else
int scanLine32, firstWord32, lastWord32;
int scanLine8, firstWord8;
int line;
#define map32To8(w) (col= (w), stDownGradingColors[\
(((col >> (16+(8-3))) & 0x7) << 5) | \
(((col >> ( 8+(8-3))) & 0x7) << 2) | \
((col >> ( 0+(8-2))) & 0x7)])
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
scanLine8= bytesPerLine(width, 8);
firstWord8= scanLine8*affectedT + (bytesPerLineRD(affectedL, 32) >> 2);
for (line= affectedT; line < affectedB; line++)
{
register int col;
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord32);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord8);
while (from < limit)
{
to[0]= map32To8(from[0]);
from++;
to++;
}
firstWord32+= scanLine32;
lastWord32+= scanLine32;
firstWord8+= scanLine8;
}
#undef map32To8
#endif /* !ENABLE_FAST_BLT */
}
void copyImage16To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine16, firstWord16, lastWord16;
int scanLine32, firstWord32;
int line;
int rshift, gshift, bshift;
register unsigned int col;
#if defined(DEBUG)
fprintf(stderr, "copyImg16to32 %p -> %p (%d %d) %d %d %d %d\n",
fromImageData, toImageData, width, height,
affectedL, affectedT, affectedR, affectedB);
#endif
rshift= stRNMask-5 + stRShift;
gshift= stGNMask-5 + stGShift;
bshift= stBNMask-5 + stBShift;
#define map16To32(w) (col= (w), \
(((col >> 10) & 0x1f) << rshift) | \
(((col >> 5) & 0x1f) << gshift) | \
((col & 0x1f) << bshift))
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + bytesPerLineRD(affectedL, 16);
lastWord16= scanLine16*affectedT + bytesPerLine(affectedR, 16);
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + (bytesPerLineRD(affectedL, 16) << 1);
for (line= affectedT; line < affectedB; line++)
{
register unsigned short *from= (unsigned short *)((long)fromImageData+firstWord16);
register unsigned short *limit= (unsigned short *)((long)fromImageData+lastWord16);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
to[0]= map16To32(from[0]);
to[1]= map16To32(from[1]);
# else
to[0]= map16To32(from[1]);
to[1]= map16To32(from[0]);
# endif
from+= 2;
to+= 2;
}
firstWord16+= scanLine16;
lastWord16+= scanLine16;
firstWord32+= scanLine32;
}
#undef map16To32
}
void copyImage16To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine16, firstWord16, lastWord16;
int scanLine24, firstWord24;
int line;
int rshift, gshift, bshift;
register unsigned int col;
rshift= stRNMask-5 + stRShift;
gshift= stGNMask-5 + stGShift;
bshift= stBNMask-5 + stBShift;
#define map16To24(w) (col= (w), \
(((col >> 10) & 0x1f) << rshift) | \
(((col >> 5) & 0x1f) << gshift) | \
((col & 0x1f) << bshift))
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + bytesPerLineRD(affectedL, 16);
lastWord16= scanLine16*affectedT + bytesPerLine(affectedR, 16);
scanLine24= bytesPerLine(width, 24);
firstWord24= scanLine24*affectedT + ((affectedL>>1) * 6);
for (line= affectedT; line < affectedB; line++)
{
register unsigned short *from= (unsigned short *)((long)fromImageData+firstWord16);
register unsigned short *limit= (unsigned short *)((long)fromImageData+lastWord16);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord24);
register unsigned int newpix= 0;
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
newpix= map16To24(from[0]);
# else
newpix= map16To24(from[1]);
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
# if defined(WORDS_BIGENDIAN)
newpix= map16To24(from[1]);
# else
newpix= map16To24(from[0]);
# endif
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
from+= 2;
}
firstWord16+= scanLine16;
lastWord16+= scanLine16;
firstWord24+= scanLine24;
}
#undef map16To24
}
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
extern void armSimdConvert_x888_0565_LEPacking32_16_wide(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride);
extern void armSimdConvert_x888_0565_LEPacking32_16_narrow(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride);
static void armSimdCopyImage32To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
/* Find image strides in 32-bit words */
unsigned int srcStride= width;
unsigned int dstStride= (width + 1) >> 1;
/* Round affected region out to encompass complete words in both images */
affectedL &= ~1;
affectedR += affectedR & 1;
width= affectedR - affectedL;
height= affectedB - affectedT;
/* Find first words */
fromImageData += srcStride * affectedT + affectedL;
toImageData += dstStride * affectedT + (affectedL >> 1);
/* Adjust strides to remove number of words read/written */
srcStride -= affectedR - affectedL;
dstStride -= (affectedR - affectedL) >> 1;
/* Work out which width class this operation is. */
if (width > (128 - 32) / 16 && ((-1 ^ (width - (128 - 32) / 16)) & ~(31 / 16)))
armSimdConvert_x888_0565_LEPacking32_16_wide(width, height, toImageData, dstStride, fromImageData, srcStride);
else
armSimdConvert_x888_0565_LEPacking32_16_narrow(width, height, toImageData, dstStride, fromImageData, srcStride);
}
# else
# error configuration error
# endif
#endif
void copyImage32To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
if (stRNMask == 5 && stRShift == 11 && stGNMask == 6 && stGShift == 5 && stBNMask == 5 && stBShift == 0)
armSimdCopyImage32To16(fromImageData, toImageData, width, height, affectedL, affectedT, affectedR, affectedB);
else
# else
# error configuration error
# endif
#endif
{
int scanLine32, firstWord32, lastWord32;
int scanLine16, firstWord16;
int line;
int rshift, gshift, bshift;
register unsigned int col;
rshift= stRNMask-5 + stRShift;
gshift= stGNMask-5 + stGShift;
bshift= stBNMask-5 + stBShift;
#define map32To16(w) (col= (w), \
(((col >> 19) & 0x1f) << rshift) | \
(((col >> 11) & 0x1f) << gshift) | \
(((col >> 3) & 0x1f) << bshift))
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + (bytesPerLineRD(affectedL, 32) >> 1);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord32);
register unsigned short *to= (unsigned short *)((long)toImageData+firstWord16);
while (from < limit)
{
to[0]= map32To16(from[0]);
from++;
to++;
}
firstWord32+= scanLine32;
lastWord32+= scanLine32;
firstWord16+= scanLine16;
}
#undef map32To16
}
}
void copyImage16To16(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine16, firstWord16, lastWord16;
int line;
int rshift, gshift, bshift;
register unsigned int col;
rshift= stRNMask-5 + stRShift;
gshift= stGNMask-5 + stGShift;
bshift= stBNMask-5 + stBShift;
#define map16To16(w) (col= (w), \
(((col >> 10) & 0x1f) << rshift) | \
(((col >> 5) & 0x1f) << gshift) | \
((col & 0x1f) << bshift))
scanLine16= bytesPerLine(width, 16);
firstWord16= scanLine16*affectedT + bytesPerLineRD(affectedL, 16);
lastWord16= scanLine16*affectedT + bytesPerLine(affectedR, 16);
for (line= affectedT; line < affectedB; line++)
{
register unsigned short *from= (unsigned short *)((long)fromImageData+firstWord16);
register unsigned short *limit= (unsigned short *)((long)fromImageData+lastWord16);
register unsigned short *to= (unsigned short *)((long)toImageData+firstWord16);
while (from < limit)
{
# if defined(WORDS_BIGENDIAN)
to[0]= map16To16(from[0]);
to[1]= map16To16(from[1]);
# else
to[0]= map16To16(from[1]);
to[1]= map16To16(from[0]);
# endif
from+= 2;
to+= 2;
}
firstWord16+= scanLine16;
lastWord16+= scanLine16;
}
#undef map16To16
}
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
extern void armSimdConvert_x888_x888BGR_LEPacking32_32_wide(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride);
extern void armSimdConvert_x888_x888BGR_LEPacking32_32_narrow(unsigned int width, unsigned int height,
unsigned int *dst, unsigned int dstStride,
unsigned int *src, unsigned int srcStride);
static void armSimdCopyImage32To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
unsigned int stride= width;
width= affectedR - affectedL;
height= affectedB - affectedT;
/* Find first words */
fromImageData += stride * affectedT + affectedL;
toImageData += stride * affectedT + affectedL;
/* Adjust stride to remove number of words read/written */
stride -= width;
/* Work out which width class this operation is. */
if (width > (128 - 32) / 32 && (-1 ^ (width - (128 - 32) / 32)))
armSimdConvert_x888_x888BGR_LEPacking32_32_wide(width, height, toImageData, stride, fromImageData, stride);
else
armSimdConvert_x888_x888BGR_LEPacking32_32_narrow(width, height, toImageData, stride, fromImageData, stride);
}
# else
# error configuration error
# endif
#endif
void copyImage32To32(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
#if defined(ENABLE_FAST_BLT)
# if defined(__arm__)
if ((armCpuFeatures & ARM_V6) && stRNMask == 8 && stRShift == 0 && stGNMask == 8 && stGShift == 8 && stBNMask == 8 && stBShift == 16)
armSimdCopyImage32To32(fromImageData, toImageData, width, height, affectedL, affectedT, affectedR, affectedB);
else
# else
# error unsupported use of ENABLE_FAST_BLT
# endif
#endif
{
int scanLine32, firstWord32, lastWord32;
int line;
int rshift, gshift, bshift;
register unsigned int col;
rshift= stRNMask-8 + stRShift;
gshift= stGNMask-8 + stGShift;
bshift= stBNMask-8 + stBShift;
#define map32To32(w) (col= (w), \
(((col >> 16) & 0xff) << rshift) | \
(((col >> 8) & 0xff) << gshift) | \
((col & 0xff) << bshift))
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord32);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
while (from < limit)
{
*to= map32To32(*from);
from++;
to++;
}
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
#undef map32To32
}
}
void copyImage32To32Same(int *fromImageData, int *toImageData,
int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine32, firstWord32, lastWord32;
int line;
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord32);
register unsigned int *to= (unsigned int *)((long)toImageData+firstWord32);
while (from < limit)
{
*to= *from;
from++;
to++;
}
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
}
void copyImage32To24(int *fromImageData, int *toImageData, int width, int height,
int affectedL, int affectedT, int affectedR, int affectedB)
{
int scanLine24, firstWord24;
int scanLine32, firstWord32, lastWord32;
int line;
int rshift, gshift, bshift;
register unsigned int col;
rshift= stRNMask-8 + stRShift;
gshift= stGNMask-8 + stGShift;
bshift= stBNMask-8 + stBShift;
#define map32To24(w) (col= (w), \
(((col >> 16) & 0xff) << rshift) | \
(((col >> 8) & 0xff) << gshift) | \
((col & 0xff) << bshift))
/* offsets for the 24bpp destination */
scanLine24= bytesPerLine(width, 24);
firstWord24= scanLine24*affectedT + (affectedL * 3) /* NOT bytesPerLineRD(affectedL, 24) ! */ ;
/* offsets for the 32bpp source */
scanLine32= bytesPerLine(width, 32);
firstWord32= scanLine32*affectedT + bytesPerLineRD(affectedL, 32);
lastWord32= scanLine32*affectedT + bytesPerLine(affectedR, 32);
for (line= affectedT; line < affectedB; line++)
{
register unsigned int *from= (unsigned int *)((long)fromImageData+firstWord32);
register unsigned int *limit= (unsigned int *)((long)fromImageData+lastWord32);
register unsigned char *to= (unsigned char *)((long)toImageData+firstWord24);
register unsigned int newpix= 0;
while (from < limit)
{
newpix= map32To24(*from);
from++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
newpix= newpix >> 8;
to++;
*to= (unsigned char) (newpix & 0xff);
to++;
}
firstWord24+= scanLine24;
firstWord32+= scanLine32;
lastWord32+= scanLine32;
}
#undef map32To24
}
static void display_winSetName(char *imageName)
{
/* update the window title */
if (isConnectedToXServer)
XStoreName(stDisplay, stParent, imageName);
}
/*** display connection ***/
int openXDisplay(void)
{
/* open the Squeak window. */
if (!isConnectedToXServer)
{
initClipboard();
initWindow(displayName);
initPixmap();
if (!inBrowser())
{
setWindowSize();
XMapWindow(stDisplay, stParent);
XMapWindow(stDisplay, stWindow);
}
else /* if in browser we will be reparented and mapped by plugin */
{
/* tell browser our window */
# if defined(DEBUG_BROWSER)
fprintf(stderr, "browser: sending squeak window = 0x%x\n", stWindow);
# endif
4 == write(browserPipes[1], &stWindow, 4);
# if defined(DEBUG_BROWSER)
fprintf(stderr, "browser: squeak window sent\n");
# endif
/* listen for commands */
aioEnable(browserPipes[0], 0, AIO_EXT);
aioHandle(browserPipes[0], npHandler, AIO_RX);
}
isConnectedToXServer= 1;
aioEnable(stXfd, 0, AIO_EXT);
aioHandle(stXfd, xHandler, AIO_RX);
}
return 0;
}
int forgetXDisplay(void)
{
/* Initialise variables related to the X connection, and
make the existing connection to the X Display invalid
for any further access from this Squeak image. Any socket
connection to the X server is closed, but the server is
not told to terminate any windows or X sessions. This
is used to support fork() for an existing Squeak image,
where the child is expected to continue as a headless
image, and the parent continues its normal execution. */
displayName= 0; /* name of display, or 0 for $DISPLAY */
stDisplay= null; /* Squeak display */
if (isConnectedToXServer)
close(stXfd);
if (stXfd >= 0)
aioDisable(stXfd);
stXfd= -1; /* X connection file descriptor */
stParent= null;
stWindow= null; /* Squeak window */
inputContext= 0;
inputFont= NULL;
isConnectedToXServer= 0;
return 0;
}
int disconnectXDisplay(void)
{
if (isConnectedToXServer)
{
XSync(stDisplay, False);
handleEvents();
XDestroyWindow(stDisplay, stWindow);
if (browserWindow == 0)
XDestroyWindow(stDisplay, stParent);
if (inputContext)
{
XIM im= XIMOfIC(inputContext);
XDestroyIC(inputContext);
if (im) XCloseIM(im);
}
if (inputFont)
XFreeFontSet(stDisplay, inputFont);
XCloseDisplay(stDisplay);
}
forgetXDisplay();
return 0;
}
/*** OpenGL ***/
static void *display_ioGetDisplay(void) { return (void *)stDisplay; }
static void *display_ioGetWindow(void) { return (void *)stWindow; }
#if (!USE_X11_GLX)
static sqInt display_ioGLinitialise(void) { return 0; }
static sqInt display_ioGLcreateRenderer(glRenderer *r, sqInt x, sqInt y, sqInt w, sqInt h, sqInt flags) { return 0; }
static void display_ioGLdestroyRenderer(glRenderer *r) {}
static void display_ioGLswapBuffers(glRenderer *r) {}
static sqInt display_ioGLmakeCurrentRenderer(glRenderer *r) { return 0; }
static void display_ioGLsetBufferRect(glRenderer *r, sqInt x, sqInt y, sqInt w, sqInt h) {}
#else
# include "B3DAcceleratorPlugin.h"
# include "sqOpenGLRenderer.h"
/* Local copy of code in sqOpenGLRenderer.c/.h so as not to conflict with
* B3DAcceleratorPlugin.
*/
#undef DPRINTF3D
#define DPRINTF3D(v,a) do { if ((v) <= verboseLevel) myPrint3Dlog a; } while (0)
static FILE *logfile = 0;
static void
closelog(void)
{ if (logfile) (void)fclose(logfile); }
static int
myPrint3Dlog(char *fmt, ...)
{ va_list args;
if (!logfile) {
char *slash;
char fileName[PATH_MAX+1];
#if !defined(SQUEAK_BUILTIN_PLUGIN)
char *(*getImageName)();
extern struct VirtualMachine *interpreterProxy;
getImageName = interpreterProxy->ioLoadFunctionFrom("getImageName", "");
if (!getImageName)
strcpy(fileName,"./");
else
#endif
strcpy(fileName,getImageName());
slash = strrchr(fileName,'/');
strcpy(slash ? slash + 1 : fileName, "Squeak3D.log");
logfile = fopen(fileName, "at");
if (!logfile) {
perror("fopen Squeak3D.log");
return 0;
}
atexit(closelog);
}
va_start(args,fmt);
vfprintf(logfile, fmt, args);
va_end(args);
if (forceFlush) /* from sqOpenGLRenderer.h */
fflush(logfile);
}
# include <GL/gl.h>
# include <GL/glx.h>
static void printVisual(XVisualInfo* visinfo);
static void listVisuals();
static int visualAttributes[]= {
GLX_STENCIL_SIZE, 0, /* filled in later - must be first item! */
GLX_ALPHA_SIZE, 1, /* filled in later - must be second item! */
GLX_RGBA, /* no indexed colors */
GLX_DOUBLEBUFFER, /* will swap */
GLX_LEVEL, 0, /* frame buffer, not overlay */
GLX_DEPTH_SIZE, 16, /* decent depth */
GLX_AUX_BUFFERS, 0, /* no aux buffers */
GLX_ACCUM_RED_SIZE, 0, /* no accumulation */
GLX_ACCUM_GREEN_SIZE, 0,
GLX_ACCUM_BLUE_SIZE, 0,
GLX_ACCUM_ALPHA_SIZE, 0,
None
};
extern int verboseLevel;
static sqInt display_ioGLinitialise(void) { return 1; }
#define _renderWindow(R) ((R)->drawable)
#define renderWindow(R) ((Window)(R)->drawable)
#define _renderContext(R) ((R)->context)
#define renderContext(R) ((GLXContext)(R)->context)
static sqInt display_ioGLcreateRenderer(glRenderer *r, sqInt x, sqInt y, sqInt w, sqInt h, sqInt flags)
{
XVisualInfo* visinfo= 0;
if (flags & B3D_STENCIL_BUFFER)
visualAttributes[1]= 1;
else
visualAttributes[1]= 0;
_renderWindow(r)= 0;
_renderContext(r)= 0;
DPRINTF3D(3, ("---- Creating new renderer ----\r\r"));
/* sanity checks */
if (w < 0 || h < 0)
{
DPRINTF3D(1, ("Negative extent (%i@%i)!\r", w, h));
goto fail;
}
/* choose visual and create context */
if (verboseLevel >= 3)
listVisuals();
{
visinfo= glXChooseVisual(stDisplay, DefaultScreen(stDisplay), visualAttributes);
if (!visinfo)
{
/* retry without alpha */
visualAttributes[3]= 0;
visinfo= glXChooseVisual(stDisplay, DefaultScreen(stDisplay), visualAttributes);
}
if (!visinfo)
{
DPRINTF3D(1, ("No OpenGL visual found!\r"));
goto fail;
}
DPRINTF3D(3, ("\r#### Selected GLX visual ID 0x%lx ####\r", visinfo->visualid));
if (verboseLevel >= 3)
printVisual(visinfo);
/* create context */
if (!(_renderContext(r)= glXCreateContext(stDisplay, visinfo, 0, GL_TRUE)))
{
DPRINTF3D(1, ("Creating GLX context failed!\r"));
goto fail;
}
DPRINTF3D(3, ("\r#### Created GLX context ####\r" ));
/* create window */
{
XSetWindowAttributes attributes;
unsigned long valuemask= 0;
attributes.colormap= XCreateColormap(stDisplay, DefaultRootWindow(stDisplay),
visinfo->visual, AllocNone);
valuemask |= CWColormap;
attributes.background_pixel= BlackPixel(stDisplay, DefaultScreen(stDisplay));
valuemask |= CWBackPixel;
attributes.border_pixel= 0;
valuemask |= CWBorderPixel;
if (!(_renderWindow(r)= (void *)XCreateWindow(stDisplay, stWindow, x, y, w, h, 0,
visinfo->depth, InputOutput, visinfo->visual,
valuemask, &attributes)))
{
DPRINTF3D(1, ("Failed to create client window\r"));
goto fail;
}
XMapWindow(stDisplay, renderWindow(r));
}
DPRINTF3D(3, ("\r#### Created window ####\r" ));
XFree(visinfo);
visinfo= 0;
}
/* Make the context current */
if (!glXMakeCurrent(stDisplay, renderWindow(r), renderContext(r)))
{
DPRINTF3D(1, ("Failed to make context current\r"));
goto fail;
}
DPRINTF3D(3, ("\r### Renderer created! ###\r"));
return 1;
fail:
DPRINTF3D(1, ("OpenGL initialization failed\r"));
if (visinfo)
XFree(visinfo);
if (renderContext(r))
glXDestroyContext(stDisplay, renderContext(r));
if (renderWindow(r))
XDestroyWindow(stDisplay, renderWindow(r));
return 0;
}
static void display_ioGLdestroyRenderer(glRenderer *r)
{
glXDestroyContext(stDisplay, renderContext(r));
XDestroyWindow(stDisplay, renderWindow(r));
}
static void display_ioGLswapBuffers(glRenderer *r)
{
glXSwapBuffers(stDisplay, renderWindow(r));
}
static sqInt display_ioGLmakeCurrentRenderer(glRenderer *r)
{
if (r)
{
if (!glXMakeCurrent(stDisplay, renderWindow(r), renderContext(r)))
{
DPRINTF3D(1, ("Failed to make context current\r"));
return 0;
}
}
else
glXMakeCurrent(stDisplay, 0, 0);
return 1;
}
static void display_ioGLsetBufferRect(glRenderer *r, sqInt x, sqInt y, sqInt w, sqInt h)
{
XMoveResizeWindow(stDisplay, renderWindow(r), x, y, w, h);
}
/* GLX_CONFIG_CAVEAT might not be supported */
/* but the test below is worded so it does not matter */
# if !defined(GLX_CONFIG_CAVEAT)
# define GLX_CONFIG_CAVEAT 0x20
# define GLX_SLOW_CONFIG 0x8001
# endif
static void printVisual(XVisualInfo* visinfo)
{
int isOpenGL;
glXGetConfig(stDisplay, visinfo, GLX_USE_GL, &isOpenGL);
if (isOpenGL)
{
int slow= 0;
int red, green, blue, alpha, stencil, depth;
glXGetConfig(stDisplay, visinfo, GLX_CONFIG_CAVEAT, &slow);
glXGetConfig(stDisplay, visinfo, GLX_RED_SIZE, &red);
glXGetConfig(stDisplay, visinfo, GLX_GREEN_SIZE, &green);
glXGetConfig(stDisplay, visinfo, GLX_BLUE_SIZE, &blue);
glXGetConfig(stDisplay, visinfo, GLX_ALPHA_SIZE, &alpha);
glXGetConfig(stDisplay, visinfo, GLX_STENCIL_SIZE, &stencil);
glXGetConfig(stDisplay, visinfo, GLX_DEPTH_SIZE, &depth);
if (slow != GLX_SLOW_CONFIG)
DPRINTF3D(3, ("===> OpenGL visual\r"));
else
DPRINTF3D(3, ("---> slow OpenGL visual\r"));
DPRINTF3D(3, ("rgbaBits = %i+%i+%i+%i\r", red, green, blue, alpha));
DPRINTF3D(3, ("stencilBits = %i\r", stencil));
DPRINTF3D(3, ("depthBits = %i\r", depth));
}
glGetError(); /* reset error flag */
}
static void listVisuals(void)
{
XVisualInfo* visinfo;
int nvisuals, i;
visinfo= XGetVisualInfo(stDisplay, VisualNoMask, NULL, &nvisuals);
for (i= 0; i < nvisuals; i++)
{
DPRINTF3D(3, ("#### Checking pixel format (visual ID 0x%lx)\r", visinfo[i].visualid));
printVisual(&visinfo[i]);
}
XFree(visinfo);
}
#endif /* defined(USE_X11_GLX) */
/*** browser plugin (from sqUnixMozilla.c) ***/
sqInt display_primitivePluginBrowserReady(void);
sqInt display_primitivePluginRequestURLStream(void);
sqInt display_primitivePluginRequestURL(void);
sqInt display_primitivePluginPostURL(void);
sqInt display_primitivePluginRequestFileHandle(void);
sqInt display_primitivePluginDestroyRequest(void);
sqInt display_primitivePluginRequestState(void);
/*** host window support ***/
#if (SqDisplayVersionMajor >= 1 && SqDisplayVersionMinor >= 2)
static long display_hostWindowCreate(long w, long h, long x, long y, char *list, long attributeListLength)
{ return 0; }
static long display_hostWindowClose(long index) { return 0; }
static long display_hostWindowCloseAll(void) { return 0; }
static long display_hostWindowShowDisplay(unsigned *dispBitsIndex, long width, long height, long depth,
int affectedL, int affectedR, int affectedT, int affectedB, int windowIndex)
{ return 0; }
/* By convention for HostWindowPlugin, handle 1 refers to the display window */
#define realWindowHandle(handleFromImage) (handleFromImage == 1 ? stParent : handleFromImage)
/* Window struct addresses are not small integers */
#define isWindowHandle(winIdx) ((realWindowHandle(winIdx)) >= 65536)
static long display_ioSizeOfNativeWindow(void *windowHandle);
static long display_hostWindowGetSize(long windowIndex)
{
return isWindowHandle(windowIndex)
? display_ioSizeOfNativeWindow((void *)realWindowHandle(windowIndex))
: -1;
}
/* ioSizeOfWindowSetxy: args are int windowIndex, int w & h for the
* width / height to make the window. Return the actual size the OS
* produced in (width<<16 | height) format or -1 for failure as above. */
static long display_hostWindowSetSize(long windowIndex, long w, long h)
{
XWindowAttributes attrs;
int real_border_width;
if (!isWindowHandle(windowIndex)
|| !XGetWindowAttributes(stDisplay, (Window)realWindowHandle(windowIndex), &attrs))
return -1;
/* At least under Gnome a window's border width in its attributes is zero
* but the relative position of the left-hand edge is the actual border
* width.
*/
real_border_width= attrs.border_width ? attrs.border_width : attrs.x;
return XResizeWindow(stDisplay, (Window)realWindowHandle(windowIndex),
w - 2 * real_border_width,
h - attrs.y - real_border_width)
? display_ioSizeOfNativeWindow((void *)realWindowHandle(windowIndex))
: -1;
}
static long display_ioPositionOfNativeWindow(void *windowHandle);
static long display_hostWindowGetPosition(long windowIndex)
{
return isWindowHandle(windowIndex)
? display_ioPositionOfNativeWindow((void *)realWindowHandle(windowIndex))
: -1;
}
/* ioPositionOfWindowSetxy: args are int windowIndex, int x & y for the
* origin x/y for the window. Return the actual origin the OS
* produced in (left<<16 | top) format or -1 for failure, as above */
static long display_hostWindowSetPosition(long windowIndex, long x, long y)
{
if (!isWindowHandle(windowIndex))
return -1;
return XMoveWindow(stDisplay, (Window)realWindowHandle(windowIndex), x, y)
? display_ioPositionOfNativeWindow((void *)windowIndex)
: -1;
}
static long display_hostWindowSetTitle(long windowIndex, char *newTitle, long sizeOfTitle)
{
if (windowIndex != 1 && windowIndex != stParent && windowIndex != stWindow)
return -1;
XChangeProperty(stDisplay, stParent,
XInternAtom(stDisplay, "_NET_WM_NAME", False),
XInternAtom(stDisplay, "UTF8_STRING", False),
8, PropModeReplace, newTitle, sizeOfTitle);
return 0;
}
static long display_ioSizeOfNativeWindow(void *windowHandle)
{
XWindowAttributes attrs;
int real_border_width;
if (!XGetWindowAttributes(stDisplay, (Window)windowHandle, &attrs))
return -1;
/* At least under Gnome a window's border width in its attributes is zero
* but the relative position of the left-hand edge is the actual border
* width.
*/
real_border_width= attrs.border_width ? attrs.border_width : attrs.x;
return (attrs.width + 2 * real_border_width << 16)
| (attrs.height + attrs.y + real_border_width);
}
static long display_ioPositionOfNativeWindow(void *windowHandle)
{
XWindowAttributes attrs;
Window neglected_child;
int rootx, rooty;
if (!XGetWindowAttributes(stDisplay, (Window)windowHandle, &attrs)
|| !XTranslateCoordinates(stDisplay, (Window)windowHandle, attrs.root,
-attrs.border_width, -attrs.border_width,
&rootx, &rooty, &neglected_child))
return -1;
return (rootx - attrs.x << 16) | (rooty - attrs.y);
}
#endif /* (SqDisplayVersionMajor >= 1 && SqDisplayVersionMinor >= 2) */
static char *display_winSystemName(void) { return "X11"; }
static void display_winInit(void)
{
if (!strcmp(argVec[0], "headlessSqueak"))
headless= 1;
#if defined(USE_XSHM)
{
# if defined(AT_EXIT)
AT_EXIT(shmExit);
AT_EXIT((void(*)(void))ioShutdownAllModules);
# else
# warning: cannot free display bitmap on exit!
# warning: cannot shut down module system on exit!
# endif
}
#endif
/* avoid compiler warning */
(void)recordDragEvent;
}
static void display_winOpen(int argc, char *dropFiles[])
{
#if defined(DEBUG_WINDOW)
int sws= getSavedWindowSize();
fprintf(stderr, "saved window size is %d %d\n", sws >> 16, sws & 0xffff);
#endif
int i, launched = 0;
if (headless) {
forgetXDisplay();
return;
}
openXDisplay();
for (i = 0; i < argc; i++)
if (dndLaunchFile(dropFiles[i]))
launched = 1;
if (launched)
exit(0);
}
static void display_winExit(void)
{
disconnectXDisplay();
}
static long display_winImageFind(char *buf, long len) { return 0; }
static void display_winImageNotFound(void) {}
#if SqDisplayVersionMajor >= 1 && SqDisplayVersionMinor >= 3
/* eem Mar 22 2010 - new code to come up to level of Qwaq host window support
* on Mac & Win32.
* In the following functions "Display" refers to the user area of a window and
* "Window" refers to the entire window including border & title bar.
*/
static long
display_ioSetCursorPositionXY(long x, long y)
{
if (!XWarpPointer(stDisplay, None, DefaultRootWindow(stDisplay),
0, 0, 0, 0, x, y))
return -1;
XFlush(stDisplay);
return 0;
}
/* Return the pixel origin (topleft) of the platform-defined working area
for the screen containing the given window. */
static long
display_ioPositionOfScreenWorkArea(long windowIndex)
{
/* We simply hard-code this. There's no obvious window-manager independent way
* to discover this that doesn't involve creating a window.
* We're also not attempting multi-monitor support; attempting to configure a
* laptop with a second monitor via ATI's "control center" resulted in no
* cursor and no ATI control center once the multi-monitor mode was enabled.
*/
#define NominalMenubarHeight 24 /* e.g. Gnome default */
return (0 << 16) | NominalMenubarHeight;
}
/* Return the pixel extent of the platform-defined working area
for the screen containing the given window. */
static long
display_ioSizeOfScreenWorkArea(long windowIndex)
{
XWindowAttributes attrs;
if (!XGetWindowAttributes(stDisplay, DefaultRootWindow(stDisplay), &attrs))
return -1;
return (attrs.width << 16) | attrs.height;
}
void *display_ioGetWindowHandle() { return (void *)stParent; }
static long
display_ioPositionOfNativeDisplay(void *windowHandle)
{
XWindowAttributes attrs;
Window neglected_child;
int rootx, rooty;
if (!XGetWindowAttributes(stDisplay, (Window)windowHandle, &attrs)
|| !XTranslateCoordinates(stDisplay, (Window)windowHandle, attrs.root,
-attrs.border_width, -attrs.border_width,
&rootx, &rooty, &neglected_child))
return -1;
return (rootx << 16) | rooty;
}
static long
display_ioSizeOfNativeDisplay(void *windowHandle)
{
XWindowAttributes attrs;
int rootx, rooty;
if (!XGetWindowAttributes(stDisplay, (Window)windowHandle, &attrs))
return -1;
return (attrs.width << 16) | attrs.height;
}
#endif /* SqDisplayVersionMajor >= 1 && SqDisplayVersionMinor >= 3 */
SqDisplayDefine(X11);
/*** module ***/
static void display_printUsage(void)
{
printf("\nX11 <option>s:\n");
printf(" "VMOPTION("browserWindow")" <wid> run in window <wid>\n");
printf(" "VMOPTION("browserPipes")" <r> <w> run as Browser plugin using descriptors <r> <w>\n");
printf(" "VMOPTION("cmdmod")" <n> map Mod<n> to the Command key\n");
printf(" "VMOPTION("compositioninput")" enable overlay window for composed characters\n");
printf(" "VMOPTION("display")" <dpy> display on <dpy> (default: $DISPLAY)\n");
printf(" "VMOPTION("fullscreen")" occupy the entire screen\n");
printf(" "VMOPTION("fullscreenDirect")" simple window manager support for fullscreen\n");
#if (USE_X11_GLX)
printf(" "VMOPTION("glxdebug")" <n> set GLX debug verbosity level to <n>\n");
#endif
printf(" "VMOPTION("headless")" run in headless (no window) mode\n");
printf(" "VMOPTION("iconic")" start up iconified\n");
printf(" "VMOPTION("lazy")" go to sleep when main window unmapped\n");
printf(" "VMOPTION("mapdelbs")" map Delete key onto Backspace\n");
printf(" "VMOPTION("nointl")" disable international keyboard support\n");
printf(" "VMOPTION("notitle")" disable the " xResName " window title bar\n");
printf(" "VMOPTION("title")" <t> use t as the " xResName " window title instead of the image name\n");
printf(" "VMOPTION("ldtoms")" <n> launch drop timeout milliseconds\n");
printf(" "VMOPTION("noxdnd")" disable X drag-and-drop protocol support\n");
printf(" "VMOPTION("optmod")" <n> map Mod<n> to the Option key\n");
#if defined(SUGAR)
printf(" "VMOPTION("sugarBundleId")" <id> set window property _SUGAR_BUNDLE_ID to <id>\n");
printf(" "VMOPTION("sugarActivityId")" <id> set window property _SUGAR_ACTIVITY_ID to <id>\n");
#endif
printf(" "VMOPTION("swapbtn")" swap yellow (middle) and blue (right) buttons\n");
printf(" "VMOPTION("xasync")" don't serialize display updates\n");
#if defined(USE_XICFONT_OPTION)
printf(" "VMOPTION("xicfont")" <f> use font set <f> for the input context overlay\n");
#endif
printf(" "VMOPTION("xshm")" use X shared memory extension\n");
}
static void display_printUsageNotes(void)
{
printf(" Using `unix:0' for <dpy> may improve local display performance.\n");
printf(" "VMOPTION("xshm")" only works when " xResName " is running on the X server host.\n");
}
static void display_parseEnvironment(void)
{
char *ev= 0;
if (getenv("LC_CTYPE") || getenv("LC_ALL"))
x2sqKey= x2sqKeyInput;
if (localeEncoding)
{
if (getenv("SQUEAK_COMPOSITIONINPUT"))
{
compositionInput= 1;
initInput= initInputI18n;
x2sqKey= x2sqKeyCompositionInput;
}
}
if (getenv("SQUEAK_LAZY")) sleepWhenUnmapped= 1;
if (getenv("SQUEAK_SPY")) withSpy= 1;
#if !defined (INIT_INPUT_WHEN_KEY_PRESSED)
if (getenv("SQUEAK_NOINTL")) initInput= initInputNone;
#else
if (getenv("SQUEAK_NOINTL")) x2sqKey= x2sqKeyPlain;
#endif
if (getenv("SQUEAK_NOTITLE")) noTitle= 1;
if (getenv("SQUEAK_NOXDND")) useXdnd= 0;
if (getenv("SQUEAK_FULLSCREEN")) fullScreen= 1;
if (getenv("SQUEAK_FULLSCREEN_DIRECT")) fullScreenDirect= 1;
if (getenv("SQUEAK_ICONIC")) iconified= 1;
if (getenv("SQUEAK_MAPDELBS")) mapDelBs= 1;
if (getenv("SQUEAK_SWAPBTN")) swapBtn= 1;
if ((ev= getenv("SQUEAK_OPTMOD"))) optMapIndex= Mod1MapIndex + atoi(ev) - 1;
if ((ev= getenv("SQUEAK_CMDMOD"))) cmdMapIndex= Mod1MapIndex + atoi(ev) - 1;
#if defined(USE_XSHM)
if (getenv("SQUEAK_XSHM")) useXshm= 1;
if (getenv("SQUEAK_XASYNC")) asyncUpdate= 1;
#endif
}
static int display_parseArgument(int argc, char **argv)
{
int n= 1;
char *arg= argv[0];
if (!strcmp(arg, VMOPTION("headless"))) headless= 1;
#if defined(USE_XSHM)
else if (!strcmp(arg, VMOPTION("xshm"))) useXshm= 1;
else if (!strcmp(arg, VMOPTION("xasync"))) asyncUpdate= 1;
#else
else if (!strcmp(arg, VMOPTION("xshm")) ||
!strcmp(arg, VMOPTION("xasync"))) fprintf(stderr, "ignoring %s (not supported by this VM)\n", arg);
#endif
else if (!strcmp(arg, VMOPTION("lazy"))) sleepWhenUnmapped= 1;
else if (!strcmp(arg, VMOPTION("notitle"))) noTitle= 1;
else if (!strcmp(arg, VMOPTION("mapdelbs"))) mapDelBs= 1;
else if (!strcmp(arg, VMOPTION("swapbtn"))) swapBtn= 1;
else if (!strcmp(arg, VMOPTION("fullscreen"))) fullScreen= 1;
else if (!strcmp(arg, VMOPTION("fullscreenDirect"))) fullScreenDirect= 1;
else if (!strcmp(arg, VMOPTION("iconic"))) iconified= 1;
#if !defined (INIT_INPUT_WHEN_KEY_PRESSED)
else if (!strcmp(arg, VMOPTION("nointl"))) initInput= initInputNone;
#else
else if (!strcmp(arg, VMOPTION("nointl"))) x2sqKey= x2sqKeyPlain;
#endif
else if (!strcmp(arg, VMOPTION("compositioninput")))
{
compositionInput= 1;
x2sqKey= x2sqKeyCompositionInput;
initInput= initInputI18n;
}
else if (!strcmp(arg, VMOPTION("noxdnd"))) useXdnd= 0;
else if (argv[1]) /* option requires an argument */
{
n= 2;
if (!strcmp(arg, VMOPTION("display"))) displayName= argv[1];
else if (!strcmp(arg, VMOPTION("optmod"))) optMapIndex= Mod1MapIndex + atoi(argv[1]) - 1;
else if (!strcmp(arg, VMOPTION("cmdmod"))) cmdMapIndex= Mod1MapIndex + atoi(argv[1]) - 1;
# if defined(SUGAR)
else if (!strcmp(arg, VMOPTION("sugarBundleId"))) sugarBundleId= argv[1];
else if (!strcmp(arg, VMOPTION("sugarActivityId"))) sugarActivityId= argv[1];
# endif
# if defined(USE_XICFONT_OPTION)
else if (!strcmp(arg, VMOPTION("xicfont"))) inputFontStr= argv[1];
# endif
else if (!strcmp(arg, VMOPTION("browserWindow")))
{
sscanf(argv[1], "%lu", (unsigned long *)&browserWindow);
if (browserWindow == 0)
{
fprintf(stderr, "Error: invalid argument for `-browserWindow'\n");
exit(1);
}
}
else if (!strcmp(arg, VMOPTION("browserPipes")))
{
if (!argv[2]) return 0;
sscanf(argv[1], "%i", &browserPipes[0]);
sscanf(argv[2], "%i", &browserPipes[1]);
/* receive browserWindow */
# if defined(DEBUG_BROWSER)
fprintf(stderr, "browser: reading window\n");
# endif
if (sizeof(browserWindow) !=
read(browserPipes[0], (void *)&browserWindow, sizeof(browserWindow)))
{
perror("reading browserWindow");
exit(1);
}
# if defined(DEBUG_BROWSER)
fprintf(stderr, "browser: window = 0x%x\n", browserWindow);
# endif
return 3;
}
# if (USE_X11_GLX)
else if (!strcmp(arg, VMOPTION("glxdebug")))
{
sscanf(argv[1], "%d", &verboseLevel);
}
# endif
else if (!strcmp(arg, VMOPTION("title"))) defaultWindowLabel = argv[1];
else if (!strcmp(arg, VMOPTION("ldtoms"))) launchDropTimeoutMsecs = atol(argv[1]);
else
n= 0; /* not recognised */
}
else
n= 0;
return n;
}
static void *display_makeInterface(void) { return &display_X11_itf; }
#include "SqModule.h"
SqModuleDefine(display, X11);
|
853373.c | /*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- 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.
*====================================================================*/
/*
* dnabasic.c
*
* Dna creation, destruction, copy, clone, etc.
* L_DNA *l_dnaCreate()
* L_DNA *l_dnaCreateFromIArray()
* L_DNA *l_dnaCreateFromDArray()
* L_DNA *l_dnaMakeSequence()
* void *l_dnaDestroy()
* L_DNA *l_dnaCopy()
* L_DNA *l_dnaClone()
* l_int32 l_dnaEmpty()
*
* Dna: add/remove number and extend array
* l_int32 l_dnaAddNumber()
* static l_int32 l_dnaExtendArray()
* l_int32 l_dnaInsertNumber()
* l_int32 l_dnaRemoveNumber()
* l_int32 l_dnaReplaceNumber()
*
* Dna accessors
* l_int32 l_dnaGetCount()
* l_int32 l_dnaSetCount()
* l_int32 l_dnaGetIValue()
* l_int32 l_dnaGetDValue()
* l_int32 l_dnaSetValue()
* l_int32 l_dnaShiftValue()
* l_int32 *l_dnaGetIArray()
* l_float64 *l_dnaGetDArray()
* l_int32 l_dnaGetRefcount()
* l_int32 l_dnaChangeRefcount()
* l_int32 l_dnaGetParameters()
* l_int32 l_dnaSetParameters()
* l_int32 l_dnaCopyParameters()
*
* Serialize Dna for I/O
* L_DNA *l_dnaRead()
* L_DNA *l_dnaReadStream()
* l_int32 l_dnaWrite()
* l_int32 l_dnaWriteStream()
*
* Dnaa creation, destruction
* L_DNAA *l_dnaaCreate()
* void *l_dnaaDestroy()
*
* Add Dna to Dnaa
* l_int32 l_dnaaAddDna()
* l_int32 l_dnaaExtendArray()
*
* Dnaa accessors
* l_int32 l_dnaaGetCount()
* l_int32 l_dnaaGetDnaCount()
* l_int32 l_dnaaGetNumberCount()
* L_DNA *l_dnaaGetDna()
* L_DNA *l_dnaaReplaceDna()
* l_int32 l_dnaaGetValue()
* l_int32 l_dnaaAddNumber()
*
* Serialize Dnaa for I/O
* L_DNAA *l_dnaaRead()
* L_DNAA *l_dnaaReadStream()
* l_int32 l_dnaaWrite()
* l_int32 l_dnaaWriteStream()
*
* Other Dna functions
* L_DNA *l_dnaMakeDelta()
* NUMA *l_dnaConvertToNuma()
* L_DNA *numaConvertToDna()
* l_int32 *l_dnaJoin()
*
* (1) The Dna is a struct holding an array of doubles. It can also
* be used to store l_int32 values, up to the full precision
* of int32. Use it whenever integers larger than a few million
* need to be stored.
*
* (2) Always use the accessors in this file, never the fields directly.
*
* (3) Storing and retrieving numbers:
*
* * to append a new number to the array, use l_dnaAddNumber(). If
* the number is an int, it will will automatically be converted
* to l_float64 and stored.
*
* * to reset a value stored in the array, use l_dnaSetValue().
*
* * to increment or decrement a value stored in the array,
* use l_dnaShiftValue().
*
* * to obtain a value from the array, use either l_dnaGetIValue()
* or l_dnaGetDValue(), depending on whether you are retrieving
* an integer or a float. This avoids doing an explicit cast,
* such as
* (a) return a l_float64 and cast it to an l_int32
* (b) cast the return directly to (l_float64 *) to
* satisfy the function prototype, as in
* l_dnaGetDValue(da, index, (l_float64 *)&ival); [ugly!]
*
* (4) int <--> double conversions:
*
* Conversions go automatically from l_int32 --> l_float64,
* without loss of precision. You must cast (l_int32)
* to go from l_float64 --> l_int32 because you're truncating
* to the integer value.
*
* (5) As with other arrays in leptonica, the l_dna has both an allocated
* size and a count of the stored numbers. When you add a number, it
* goes on the end of the array, and causes a realloc if the array
* is already filled. However, in situations where you want to
* add numbers randomly into an array, such as when you build a
* histogram, you must set the count of stored numbers in advance.
* This is done with l_dnaSetCount(). If you set a count larger
* than the allocated array, it does a realloc to the size requested.
*
* (6) In situations where the data in a l_dna correspond to a function
* y(x), the values can be either at equal spacings in x or at
* arbitrary spacings. For the former, we can represent all x values
* by two parameters: startx (corresponding to y[0]) and delx
* for the change in x for adjacent values y[i] and y[i+1].
* startx and delx are initialized to 0.0 and 1.0, rsp.
* For arbitrary spacings, we use a second l_dna, and the two
* l_dnas are typically denoted dnay and dnax.
*/
#include <string.h>
#include <math.h>
#include "allheaders.h"
static const l_int32 INITIAL_PTR_ARRAYSIZE = 50; /* n'importe quoi */
/* Static functions */
static l_int32 l_dnaExtendArray(L_DNA *da);
static l_int32 l_dnaaExtendArray(L_DNAA *daa);
/*--------------------------------------------------------------------------*
* Dna creation, destruction, copy, clone, etc. *
*--------------------------------------------------------------------------*/
/*!
* l_dnaCreate()
*
* Input: size of number array to be alloc'd (0 for default)
* Return: da, or null on error
*/
L_DNA *
l_dnaCreate(l_int32 n)
{
L_DNA *da;
PROCNAME("l_dnaCreate");
if (n <= 0)
n = INITIAL_PTR_ARRAYSIZE;
if ((da = (L_DNA *)CALLOC(1, sizeof(L_DNA))) == NULL)
return (L_DNA *)ERROR_PTR("da not made", procName, NULL);
if ((da->array = (l_float64 *)CALLOC(n, sizeof(l_float64))) == NULL)
return (L_DNA *)ERROR_PTR("double array not made", procName, NULL);
da->nalloc = n;
da->n = 0;
da->refcount = 1;
da->startx = 0.0;
da->delx = 1.0;
return da;
}
/*!
* l_dnaCreateFromIArray()
*
* Input: iarray (integer)
* size (of the array)
* Return: da, or null on error
*
* Notes:
* (1) We can't insert this int array into the l_dna, because a l_dna
* takes a double array. So this just copies the data from the
* input array into the l_dna. The input array continues to be
* owned by the caller.
*/
L_DNA *
l_dnaCreateFromIArray(l_int32 *iarray,
l_int32 size)
{
l_int32 i;
L_DNA *da;
PROCNAME("l_dnaCreateFromIArray");
if (!iarray)
return (L_DNA *)ERROR_PTR("iarray not defined", procName, NULL);
if (size <= 0)
return (L_DNA *)ERROR_PTR("size must be > 0", procName, NULL);
da = l_dnaCreate(size);
for (i = 0; i < size; i++)
l_dnaAddNumber(da, iarray[i]);
return da;
}
/*!
* l_dnaCreateFromDArray()
*
* Input: da (float)
* size (of the array)
* copyflag (L_INSERT or L_COPY)
* Return: da, or null on error
*
* Notes:
* (1) With L_INSERT, ownership of the input array is transferred
* to the returned l_dna, and all @size elements are considered
* to be valid.
*/
L_DNA *
l_dnaCreateFromDArray(l_float64 *darray,
l_int32 size,
l_int32 copyflag)
{
l_int32 i;
L_DNA *da;
PROCNAME("l_dnaCreateFromDArray");
if (!darray)
return (L_DNA *)ERROR_PTR("darray not defined", procName, NULL);
if (size <= 0)
return (L_DNA *)ERROR_PTR("size must be > 0", procName, NULL);
if (copyflag != L_INSERT && copyflag != L_COPY)
return (L_DNA *)ERROR_PTR("invalid copyflag", procName, NULL);
da = l_dnaCreate(size);
if (copyflag == L_INSERT) {
if (da->array) FREE(da->array);
da->array = darray;
da->n = size;
} else { /* just copy the contents */
for (i = 0; i < size; i++)
l_dnaAddNumber(da, darray[i]);
}
return da;
}
/*!
* l_dnaMakeSequence()
*
* Input: startval
* increment
* size (of sequence)
* Return: l_dna of sequence of evenly spaced values, or null on error
*/
L_DNA *
l_dnaMakeSequence(l_float64 startval,
l_float64 increment,
l_int32 size)
{
l_int32 i;
l_float64 val;
L_DNA *da;
PROCNAME("l_dnaMakeSequence");
if ((da = l_dnaCreate(size)) == NULL)
return (L_DNA *)ERROR_PTR("da not made", procName, NULL);
for (i = 0; i < size; i++) {
val = startval + i * increment;
l_dnaAddNumber(da, val);
}
return da;
}
/*!
* l_dnaDestroy()
*
* Input: &da (<to be nulled if it exists>)
* Return: void
*
* Notes:
* (1) Decrements the ref count and, if 0, destroys the l_dna.
* (2) Always nulls the input ptr.
*/
void
l_dnaDestroy(L_DNA **pda)
{
L_DNA *da;
PROCNAME("l_dnaDestroy");
if (pda == NULL) {
L_WARNING("ptr address is NULL\n", procName);
return;
}
if ((da = *pda) == NULL)
return;
/* Decrement the ref count. If it is 0, destroy the l_dna. */
l_dnaChangeRefcount(da, -1);
if (l_dnaGetRefcount(da) <= 0) {
if (da->array)
FREE(da->array);
FREE(da);
}
*pda = NULL;
return;
}
/*!
* l_dnaCopy()
*
* Input: da
* Return: copy of l_dna, or null on error
*/
L_DNA *
l_dnaCopy(L_DNA *da)
{
l_int32 i;
L_DNA *dac;
PROCNAME("l_dnaCopy");
if (!da)
return (L_DNA *)ERROR_PTR("da not defined", procName, NULL);
if ((dac = l_dnaCreate(da->nalloc)) == NULL)
return (L_DNA *)ERROR_PTR("dac not made", procName, NULL);
dac->startx = da->startx;
dac->delx = da->delx;
for (i = 0; i < da->n; i++)
l_dnaAddNumber(dac, da->array[i]);
return dac;
}
/*!
* l_dnaClone()
*
* Input: da
* Return: ptr to same l_dna, or null on error
*/
L_DNA *
l_dnaClone(L_DNA *da)
{
PROCNAME("l_dnaClone");
if (!da)
return (L_DNA *)ERROR_PTR("da not defined", procName, NULL);
l_dnaChangeRefcount(da, 1);
return da;
}
/*!
* l_dnaEmpty()
*
* Input: da
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This does not change the allocation of the array.
* It just clears the number of stored numbers, so that
* the array appears to be empty.
*/
l_int32
l_dnaEmpty(L_DNA *da)
{
PROCNAME("l_dnaEmpty");
if (!da)
return ERROR_INT("da not defined", procName, 1);
da->n = 0;
return 0;
}
/*--------------------------------------------------------------------------*
* Dna: add/remove number and extend array *
*--------------------------------------------------------------------------*/
/*!
* l_dnaAddNumber()
*
* Input: da
* val (float or int to be added; stored as a float)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaAddNumber(L_DNA *da,
l_float64 val)
{
l_int32 n;
PROCNAME("l_dnaAddNumber");
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaGetCount(da);
if (n >= da->nalloc)
l_dnaExtendArray(da);
da->array[n] = val;
da->n++;
return 0;
}
/*!
* l_dnaExtendArray()
*
* Input: da
* Return: 0 if OK, 1 on error
*/
static l_int32
l_dnaExtendArray(L_DNA *da)
{
PROCNAME("l_dnaExtendArray");
if (!da)
return ERROR_INT("da not defined", procName, 1);
if ((da->array = (l_float64 *)reallocNew((void **)&da->array,
sizeof(l_float64) * da->nalloc,
2 * sizeof(l_float64) * da->nalloc)) == NULL)
return ERROR_INT("new ptr array not returned", procName, 1);
da->nalloc *= 2;
return 0;
}
/*!
* l_dnaInsertNumber()
*
* Input: da
* index (location in da to insert new value)
* val (float64 or integer to be added)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) This shifts da[i] --> da[i + 1] for all i >= index,
* and then inserts val as da[index].
* (2) It should not be used repeatedly on large arrays,
* because the function is O(n).
*
*/
l_int32
l_dnaInsertNumber(L_DNA *da,
l_int32 index,
l_float64 val)
{
l_int32 i, n;
PROCNAME("l_dnaInsertNumber");
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaGetCount(da);
if (index < 0 || index > n)
return ERROR_INT("index not in {0...n}", procName, 1);
if (n >= da->nalloc)
l_dnaExtendArray(da);
for (i = n; i > index; i--)
da->array[i] = da->array[i - 1];
da->array[index] = val;
da->n++;
return 0;
}
/*!
* l_dnaRemoveNumber()
*
* Input: da
* index (element to be removed)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) This shifts da[i] --> da[i - 1] for all i > index.
* (2) It should not be used repeatedly on large arrays,
* because the function is O(n).
*/
l_int32
l_dnaRemoveNumber(L_DNA *da,
l_int32 index)
{
l_int32 i, n;
PROCNAME("l_dnaRemoveNumber");
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaGetCount(da);
if (index < 0 || index >= n)
return ERROR_INT("index not in {0...n - 1}", procName, 1);
for (i = index + 1; i < n; i++)
da->array[i - 1] = da->array[i];
da->n--;
return 0;
}
/*!
* l_dnaReplaceNumber()
*
* Input: da
* index (element to be replaced)
* val (new value to replace old one)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaReplaceNumber(L_DNA *da,
l_int32 index,
l_float64 val)
{
l_int32 n;
PROCNAME("l_dnaReplaceNumber");
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaGetCount(da);
if (index < 0 || index >= n)
return ERROR_INT("index not in {0...n - 1}", procName, 1);
da->array[index] = val;
return 0;
}
/*----------------------------------------------------------------------*
* Dna accessors *
*----------------------------------------------------------------------*/
/*!
* l_dnaGetCount()
*
* Input: da
* Return: count, or 0 if no numbers or on error
*/
l_int32
l_dnaGetCount(L_DNA *da)
{
PROCNAME("l_dnaGetCount");
if (!da)
return ERROR_INT("da not defined", procName, 0);
return da->n;
}
/*!
* l_dnaSetCount()
*
* Input: da
* newcount
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) If newcount <= da->nalloc, this resets da->n.
* Using newcount = 0 is equivalent to l_dnaEmpty().
* (2) If newcount > da->nalloc, this causes a realloc
* to a size da->nalloc = newcount.
* (3) All the previously unused values in da are set to 0.0.
*/
l_int32
l_dnaSetCount(L_DNA *da,
l_int32 newcount)
{
PROCNAME("l_dnaSetCount");
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (newcount > da->nalloc) {
if ((da->array = (l_float64 *)reallocNew((void **)&da->array,
sizeof(l_float64) * da->nalloc,
sizeof(l_float64) * newcount)) == NULL)
return ERROR_INT("new ptr array not returned", procName, 1);
da->nalloc = newcount;
}
da->n = newcount;
return 0;
}
/*!
* l_dnaGetDValue()
*
* Input: da
* index (into l_dna)
* &val (<return> double value; 0.0 on error)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) Caller may need to check the function return value to
* decide if a 0.0 in the returned ival is valid.
*/
l_int32
l_dnaGetDValue(L_DNA *da,
l_int32 index,
l_float64 *pval)
{
PROCNAME("l_dnaGetDValue");
if (!pval)
return ERROR_INT("&val not defined", procName, 1);
*pval = 0.0;
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (index < 0 || index >= da->n)
return ERROR_INT("index not valid", procName, 1);
*pval = da->array[index];
return 0;
}
/*!
* l_dnaGetIValue()
*
* Input: da
* index (into l_dna)
* &ival (<return> integer value; 0 on error)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) Caller may need to check the function return value to
* decide if a 0 in the returned ival is valid.
*/
l_int32
l_dnaGetIValue(L_DNA *da,
l_int32 index,
l_int32 *pival)
{
l_float64 val;
PROCNAME("l_dnaGetIValue");
if (!pival)
return ERROR_INT("&ival not defined", procName, 1);
*pival = 0;
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (index < 0 || index >= da->n)
return ERROR_INT("index not valid", procName, 1);
val = da->array[index];
*pival = (l_int32)(val + L_SIGN(val) * 0.5);
return 0;
}
/*!
* l_dnaSetValue()
*
* Input: da
* index (to element to be set)
* val (to set element)
* Return: 0 if OK; 1 on error
*/
l_int32
l_dnaSetValue(L_DNA *da,
l_int32 index,
l_float64 val)
{
PROCNAME("l_dnaSetValue");
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (index < 0 || index >= da->n)
return ERROR_INT("index not valid", procName, 1);
da->array[index] = val;
return 0;
}
/*!
* l_dnaShiftValue()
*
* Input: da
* index (to element to change relative to the current value)
* diff (increment if diff > 0 or decrement if diff < 0)
* Return: 0 if OK; 1 on error
*/
l_int32
l_dnaShiftValue(L_DNA *da,
l_int32 index,
l_float64 diff)
{
PROCNAME("l_dnaShiftValue");
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (index < 0 || index >= da->n)
return ERROR_INT("index not valid", procName, 1);
da->array[index] += diff;
return 0;
}
/*!
* l_dnaGetIArray()
*
* Input: da
* Return: a copy of the bare internal array, integerized
* by rounding, or null on error
* Notes:
* (1) A copy of the array is made, because we need to
* generate an integer array from the bare double array.
* The caller is responsible for freeing the array.
* (2) The array size is determined by the number of stored numbers,
* not by the size of the allocated array in the l_dna.
* (3) This function is provided to simplify calculations
* using the bare internal array, rather than continually
* calling accessors on the l_dna. It is typically used
* on an array of size 256.
*/
l_int32 *
l_dnaGetIArray(L_DNA *da)
{
l_int32 i, n, ival;
l_int32 *array;
PROCNAME("l_dnaGetIArray");
if (!da)
return (l_int32 *)ERROR_PTR("da not defined", procName, NULL);
n = l_dnaGetCount(da);
if ((array = (l_int32 *)CALLOC(n, sizeof(l_int32))) == NULL)
return (l_int32 *)ERROR_PTR("array not made", procName, NULL);
for (i = 0; i < n; i++) {
l_dnaGetIValue(da, i, &ival);
array[i] = ival;
}
return array;
}
/*!
* l_dnaGetDArray()
*
* Input: da
* copyflag (L_NOCOPY or L_COPY)
* Return: either the bare internal array or a copy of it,
* or null on error
*
* Notes:
* (1) If copyflag == L_COPY, it makes a copy which the caller
* is responsible for freeing. Otherwise, it operates
* directly on the bare array of the l_dna.
* (2) Very important: for L_NOCOPY, any writes to the array
* will be in the l_dna. Do not write beyond the size of
* the count field, because it will not be accessable
* from the l_dna! If necessary, be sure to set the count
* field to a larger number (such as the alloc size)
* BEFORE calling this function. Creating with l_dnaMakeConstant()
* is another way to insure full initialization.
*/
l_float64 *
l_dnaGetDArray(L_DNA *da,
l_int32 copyflag)
{
l_int32 i, n;
l_float64 *array;
PROCNAME("l_dnaGetDArray");
if (!da)
return (l_float64 *)ERROR_PTR("da not defined", procName, NULL);
if (copyflag == L_NOCOPY) {
array = da->array;
} else { /* copyflag == L_COPY */
n = l_dnaGetCount(da);
if ((array = (l_float64 *)CALLOC(n, sizeof(l_float64))) == NULL)
return (l_float64 *)ERROR_PTR("array not made", procName, NULL);
for (i = 0; i < n; i++)
array[i] = da->array[i];
}
return array;
}
/*!
* l_dnaGetRefCount()
*
* Input: da
* Return: refcount, or UNDEF on error
*/
l_int32
l_dnaGetRefcount(L_DNA *da)
{
PROCNAME("l_dnaGetRefcount");
if (!da)
return ERROR_INT("da not defined", procName, UNDEF);
return da->refcount;
}
/*!
* l_dnaChangeRefCount()
*
* Input: da
* delta (change to be applied)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaChangeRefcount(L_DNA *da,
l_int32 delta)
{
PROCNAME("l_dnaChangeRefcount");
if (!da)
return ERROR_INT("da not defined", procName, 1);
da->refcount += delta;
return 0;
}
/*!
* l_dnaGetParameters()
*
* Input: da
* &startx (<optional return> startx)
* &delx (<optional return> delx)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaGetParameters(L_DNA *da,
l_float64 *pstartx,
l_float64 *pdelx)
{
PROCNAME("l_dnaGetParameters");
if (pstartx) *pstartx = 0.0;
if (pdelx) *pdelx = 1.0;
if (!pstartx && !pdelx)
return ERROR_INT("neither &startx nor &delx are defined", procName, 1);
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (pstartx) *pstartx = da->startx;
if (pdelx) *pdelx = da->delx;
return 0;
}
/*!
* l_dnaSetParameters()
*
* Input: da
* startx (x value corresponding to da[0])
* delx (difference in x values for the situation where the
* elements of da correspond to the evaulation of a
* function at equal intervals of size @delx)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaSetParameters(L_DNA *da,
l_float64 startx,
l_float64 delx)
{
PROCNAME("l_dnaSetParameters");
if (!da)
return ERROR_INT("da not defined", procName, 1);
da->startx = startx;
da->delx = delx;
return 0;
}
/*!
* l_dnaCopyParameters()
*
* Input: dad (destination DNuma)
* das (source DNuma)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaCopyParameters(L_DNA *dad,
L_DNA *das)
{
l_float64 start, binsize;
PROCNAME("l_dnaCopyParameters");
if (!das || !dad)
return ERROR_INT("das and dad not both defined", procName, 1);
l_dnaGetParameters(das, &start, &binsize);
l_dnaSetParameters(dad, start, binsize);
return 0;
}
/*----------------------------------------------------------------------*
* Serialize Dna for I/O *
*----------------------------------------------------------------------*/
/*!
* l_dnaRead()
*
* Input: filename
* Return: da, or null on error
*/
L_DNA *
l_dnaRead(const char *filename)
{
FILE *fp;
L_DNA *da;
PROCNAME("l_dnaRead");
if (!filename)
return (L_DNA *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (L_DNA *)ERROR_PTR("stream not opened", procName, NULL);
if ((da = l_dnaReadStream(fp)) == NULL) {
fclose(fp);
return (L_DNA *)ERROR_PTR("da not read", procName, NULL);
}
fclose(fp);
return da;
}
/*!
* l_dnaReadStream()
*
* Input: stream
* Return: da, or null on error
*/
L_DNA *
l_dnaReadStream(FILE *fp)
{
l_int32 i, n, index, ret, version;
l_float64 val, startx, delx;
L_DNA *da;
PROCNAME("l_dnaReadStream");
if (!fp)
return (L_DNA *)ERROR_PTR("stream not defined", procName, NULL);
ret = fscanf(fp, "\nL_Dna Version %d\n", &version);
if (ret != 1)
return (L_DNA *)ERROR_PTR("not a l_dna file", procName, NULL);
if (version != DNA_VERSION_NUMBER)
return (L_DNA *)ERROR_PTR("invalid l_dna version", procName, NULL);
if (fscanf(fp, "Number of numbers = %d\n", &n) != 1)
return (L_DNA *)ERROR_PTR("invalid number of numbers", procName, NULL);
if ((da = l_dnaCreate(n)) == NULL)
return (L_DNA *)ERROR_PTR("da not made", procName, NULL);
for (i = 0; i < n; i++) {
if (fscanf(fp, " [%d] = %lf\n", &index, &val) != 2)
return (L_DNA *)ERROR_PTR("bad input data", procName, NULL);
l_dnaAddNumber(da, val);
}
/* Optional data */
if (fscanf(fp, "startx = %lf, delx = %lf\n", &startx, &delx) == 2)
l_dnaSetParameters(da, startx, delx);
return da;
}
/*!
* l_dnaWrite()
*
* Input: filename, da
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaWrite(const char *filename,
L_DNA *da)
{
FILE *fp;
PROCNAME("l_dnaWrite");
if (!filename)
return ERROR_INT("filename not defined", procName, 1);
if (!da)
return ERROR_INT("da not defined", procName, 1);
if ((fp = fopenWriteStream(filename, "w")) == NULL)
return ERROR_INT("stream not opened", procName, 1);
if (l_dnaWriteStream(fp, da))
return ERROR_INT("da not written to stream", procName, 1);
fclose(fp);
return 0;
}
/*!
* l_dnaWriteStream()
*
* Input: stream, da
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaWriteStream(FILE *fp,
L_DNA *da)
{
l_int32 i, n;
l_float64 startx, delx;
PROCNAME("l_dnaWriteStream");
if (!fp)
return ERROR_INT("stream not defined", procName, 1);
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaGetCount(da);
fprintf(fp, "\nL_Dna Version %d\n", DNA_VERSION_NUMBER);
fprintf(fp, "Number of numbers = %d\n", n);
for (i = 0; i < n; i++)
fprintf(fp, " [%d] = %lf\n", i, da->array[i]);
fprintf(fp, "\n");
/* Optional data */
l_dnaGetParameters(da, &startx, &delx);
if (startx != 0.0 || delx != 1.0)
fprintf(fp, "startx = %lf, delx = %lf\n", startx, delx);
return 0;
}
/*--------------------------------------------------------------------------*
* Dnaa creation, destruction *
*--------------------------------------------------------------------------*/
/*!
* l_dnaaCreate()
*
* Input: size of l_dna ptr array to be alloc'd (0 for default)
* Return: daa, or null on error
*
*/
L_DNAA *
l_dnaaCreate(l_int32 n)
{
L_DNAA *daa;
PROCNAME("l_dnaaCreate");
if (n <= 0)
n = INITIAL_PTR_ARRAYSIZE;
if ((daa = (L_DNAA *)CALLOC(1, sizeof(L_DNAA))) == NULL)
return (L_DNAA *)ERROR_PTR("daa not made", procName, NULL);
if ((daa->dna = (L_DNA **)CALLOC(n, sizeof(L_DNA *))) == NULL)
return (L_DNAA *)ERROR_PTR("l_dna ptr array not made", procName, NULL);
daa->nalloc = n;
daa->n = 0;
return daa;
}
/*!
* l_dnaaDestroy()
*
* Input: &dnaa <to be nulled if it exists>
* Return: void
*/
void
l_dnaaDestroy(L_DNAA **pdaa)
{
l_int32 i;
L_DNAA *daa;
PROCNAME("l_dnaaDestroy");
if (pdaa == NULL) {
L_WARNING("ptr address is NULL!\n", procName);
return;
}
if ((daa = *pdaa) == NULL)
return;
for (i = 0; i < daa->n; i++)
l_dnaDestroy(&daa->dna[i]);
FREE(daa->dna);
FREE(daa);
*pdaa = NULL;
return;
}
/*--------------------------------------------------------------------------*
* Add Dna to Dnaa *
*--------------------------------------------------------------------------*/
/*!
* l_dnaaAddDna()
*
* Input: daa
* da (to be added)
* copyflag (L_INSERT, L_COPY, L_CLONE)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaaAddDna(L_DNAA *daa,
L_DNA *da,
l_int32 copyflag)
{
l_int32 n;
L_DNA *dac;
PROCNAME("l_dnaaAddDna");
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
if (!da)
return ERROR_INT("da not defined", procName, 1);
if (copyflag == L_INSERT) {
dac = da;
} else if (copyflag == L_COPY) {
if ((dac = l_dnaCopy(da)) == NULL)
return ERROR_INT("dac not made", procName, 1);
} else if (copyflag == L_CLONE) {
dac = l_dnaClone(da);
} else {
return ERROR_INT("invalid copyflag", procName, 1);
}
n = l_dnaaGetCount(daa);
if (n >= daa->nalloc)
l_dnaaExtendArray(daa);
daa->dna[n] = dac;
daa->n++;
return 0;
}
/*!
* l_dnaaExtendArray()
*
* Input: daa
* Return: 0 if OK, 1 on error
*/
static l_int32
l_dnaaExtendArray(L_DNAA *daa)
{
PROCNAME("l_dnaaExtendArray");
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
if ((daa->dna = (L_DNA **)reallocNew((void **)&daa->dna,
sizeof(L_DNA *) * daa->nalloc,
2 * sizeof(L_DNA *) * daa->nalloc)) == NULL)
return ERROR_INT("new ptr array not returned", procName, 1);
daa->nalloc *= 2;
return 0;
}
/*----------------------------------------------------------------------*
* DNumaa accessors *
*----------------------------------------------------------------------*/
/*!
* l_dnaaGetCount()
*
* Input: daa
* Return: count (number of l_dna), or 0 if no l_dna or on error
*/
l_int32
l_dnaaGetCount(L_DNAA *daa)
{
PROCNAME("l_dnaaGetCount");
if (!daa)
return ERROR_INT("daa not defined", procName, 0);
return daa->n;
}
/*!
* l_dnaaGetDnaCount()
*
* Input: daa
* index (of l_dna in daa)
* Return: count of numbers in the referenced l_dna, or 0 on error.
*/
l_int32
l_dnaaGetDnaCount(L_DNAA *daa,
l_int32 index)
{
PROCNAME("l_dnaaGetDnaCount");
if (!daa)
return ERROR_INT("daa not defined", procName, 0);
if (index < 0 || index >= daa->n)
return ERROR_INT("invalid index into daa", procName, 0);
return l_dnaGetCount(daa->dna[index]);
}
/*!
* l_dnaaGetNumberCount()
*
* Input: daa
* Return: count (total number of numbers in the l_dnaa),
* or 0 if no numbers or on error
*/
l_int32
l_dnaaGetNumberCount(L_DNAA *daa)
{
L_DNA *da;
l_int32 n, sum, i;
PROCNAME("l_dnaaGetNumberCount");
if (!daa)
return ERROR_INT("daa not defined", procName, 0);
n = l_dnaaGetCount(daa);
for (sum = 0, i = 0; i < n; i++) {
da = l_dnaaGetDna(daa, i, L_CLONE);
sum += l_dnaGetCount(da);
l_dnaDestroy(&da);
}
return sum;
}
/*!
* l_dnaaGetDna()
*
* Input: daa
* index (to the index-th l_dna)
* accessflag (L_COPY or L_CLONE)
* Return: l_dna, or null on error
*/
L_DNA *
l_dnaaGetDna(L_DNAA *daa,
l_int32 index,
l_int32 accessflag)
{
PROCNAME("l_dnaaGetDna");
if (!daa)
return (L_DNA *)ERROR_PTR("daa not defined", procName, NULL);
if (index < 0 || index >= daa->n)
return (L_DNA *)ERROR_PTR("index not valid", procName, NULL);
if (accessflag == L_COPY)
return l_dnaCopy(daa->dna[index]);
else if (accessflag == L_CLONE)
return l_dnaClone(daa->dna[index]);
else
return (L_DNA *)ERROR_PTR("invalid accessflag", procName, NULL);
}
/*!
* l_dnaaReplaceDna()
*
* Input: daa
* index (to the index-th l_dna)
* l_dna (insert and replace any existing one)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) Any existing l_dna is destroyed, and the input one
* is inserted in its place.
* (2) If the index is invalid, return 1 (error)
*/
l_int32
l_dnaaReplaceDna(L_DNAA *daa,
l_int32 index,
L_DNA *da)
{
l_int32 n;
PROCNAME("l_dnaaReplaceDna");
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
if (!da)
return ERROR_INT("da not defined", procName, 1);
n = l_dnaaGetCount(daa);
if (index < 0 || index >= n)
return ERROR_INT("index not valid", procName, 1);
l_dnaDestroy(&daa->dna[index]);
daa->dna[index] = da;
return 0;
}
/*!
* l_dnaaGetValue()
*
* Input: daa
* i (index of l_dna within l_dnaa)
* j (index into l_dna)
* val (<return> double value)
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaaGetValue(L_DNAA *daa,
l_int32 i,
l_int32 j,
l_float64 *pval)
{
l_int32 n;
L_DNA *da;
PROCNAME("l_dnaaGetValue");
if (!pval)
return ERROR_INT("&val not defined", procName, 1);
*pval = 0.0;
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
n = l_dnaaGetCount(daa);
if (i < 0 || i >= n)
return ERROR_INT("invalid index into daa", procName, 1);
da = daa->dna[i];
if (j < 0 || j >= da->n)
return ERROR_INT("invalid index into da", procName, 1);
*pval = da->array[j];
return 0;
}
/*!
* l_dnaaAddNumber()
*
* Input: daa
* index (of l_dna within l_dnaa)
* val (number to be added; stored as a double)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) Adds to an existing l_dna only.
*/
l_int32
l_dnaaAddNumber(L_DNAA *daa,
l_int32 index,
l_float64 val)
{
l_int32 n;
L_DNA *da;
PROCNAME("l_dnaaAddNumber");
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
n = l_dnaaGetCount(daa);
if (index < 0 || index >= n)
return ERROR_INT("invalid index in daa", procName, 1);
da = l_dnaaGetDna(daa, index, L_CLONE);
l_dnaAddNumber(da, val);
l_dnaDestroy(&da);
return 0;
}
/*----------------------------------------------------------------------*
* Serialize Dna for I/O *
*----------------------------------------------------------------------*/
/*!
* l_dnaaRead()
*
* Input: filename
* Return: daa, or null on error
*/
L_DNAA *
l_dnaaRead(const char *filename)
{
FILE *fp;
L_DNAA *daa;
PROCNAME("l_dnaaRead");
if (!filename)
return (L_DNAA *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (L_DNAA *)ERROR_PTR("stream not opened", procName, NULL);
if ((daa = l_dnaaReadStream(fp)) == NULL) {
fclose(fp);
return (L_DNAA *)ERROR_PTR("daa not read", procName, NULL);
}
fclose(fp);
return daa;
}
/*!
* l_dnaaReadStream()
*
* Input: stream
* Return: daa, or null on error
*/
L_DNAA *
l_dnaaReadStream(FILE *fp)
{
l_int32 i, n, index, ret, version;
L_DNA *da;
L_DNAA *daa;
PROCNAME("l_dnaaReadStream");
if (!fp)
return (L_DNAA *)ERROR_PTR("stream not defined", procName, NULL);
ret = fscanf(fp, "\nL_Dnaa Version %d\n", &version);
if (ret != 1)
return (L_DNAA *)ERROR_PTR("not a l_dna file", procName, NULL);
if (version != DNA_VERSION_NUMBER)
return (L_DNAA *)ERROR_PTR("invalid l_dnaa version", procName, NULL);
if (fscanf(fp, "Number of L_Dna = %d\n\n", &n) != 1)
return (L_DNAA *)ERROR_PTR("invalid number of l_dna", procName, NULL);
if ((daa = l_dnaaCreate(n)) == NULL)
return (L_DNAA *)ERROR_PTR("daa not made", procName, NULL);
for (i = 0; i < n; i++) {
if (fscanf(fp, "L_Dna[%d]:", &index) != 1)
return (L_DNAA *)ERROR_PTR("invalid l_dna header", procName, NULL);
if ((da = l_dnaReadStream(fp)) == NULL)
return (L_DNAA *)ERROR_PTR("da not made", procName, NULL);
l_dnaaAddDna(daa, da, L_INSERT);
}
return daa;
}
/*!
* l_dnaaWrite()
*
* Input: filename, daa
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaaWrite(const char *filename,
L_DNAA *daa)
{
FILE *fp;
PROCNAME("l_dnaaWrite");
if (!filename)
return ERROR_INT("filename not defined", procName, 1);
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
if ((fp = fopenWriteStream(filename, "w")) == NULL)
return ERROR_INT("stream not opened", procName, 1);
if (l_dnaaWriteStream(fp, daa))
return ERROR_INT("daa not written to stream", procName, 1);
fclose(fp);
return 0;
}
/*!
* l_dnaaWriteStream()
*
* Input: stream, daa
* Return: 0 if OK, 1 on error
*/
l_int32
l_dnaaWriteStream(FILE *fp,
L_DNAA *daa)
{
l_int32 i, n;
L_DNA *da;
PROCNAME("l_dnaaWriteStream");
if (!fp)
return ERROR_INT("stream not defined", procName, 1);
if (!daa)
return ERROR_INT("daa not defined", procName, 1);
n = l_dnaaGetCount(daa);
fprintf(fp, "\nL_Dnaa Version %d\n", DNA_VERSION_NUMBER);
fprintf(fp, "Number of L_Dna = %d\n\n", n);
for (i = 0; i < n; i++) {
if ((da = l_dnaaGetDna(daa, i, L_CLONE)) == NULL)
return ERROR_INT("da not found", procName, 1);
fprintf(fp, "L_Dna[%d]:", i);
l_dnaWriteStream(fp, da);
l_dnaDestroy(&da);
}
return 0;
}
/*----------------------------------------------------------------------*
* Other Dna functions *
*----------------------------------------------------------------------*/
/*!
* l_dnaMakeDelta()
*
* Input: das (input l_dna)
* Return: dad (of difference values val[i+1] - val[i]),
* or null on error
*/
L_DNA *
l_dnaMakeDelta(L_DNA *das)
{
l_int32 i, n, prev, cur;
L_DNA *dad;
PROCNAME("l_dnaMakeDelta");
if (!das)
return (L_DNA *)ERROR_PTR("das not defined", procName, NULL);
n = l_dnaGetCount(das);
dad = l_dnaCreate(n - 1);
prev = 0;
for (i = 1; i < n; i++) {
l_dnaGetIValue(das, i, &cur);
l_dnaAddNumber(dad, cur - prev);
prev = cur;
}
return dad;
}
/*!
* l_dnaConvertToNuma()
*
* Input: da
* Return: na, or null on error
*/
NUMA *
l_dnaConvertToNuma(L_DNA *da)
{
l_int32 i, n;
l_float64 val;
NUMA *na;
PROCNAME("l_dnaConvertToNuma");
if (!da)
return (NUMA *)ERROR_PTR("da not defined", procName, NULL);
n = l_dnaGetCount(da);
na = numaCreate(n);
for (i = 0; i < n; i++) {
l_dnaGetDValue(da, i, &val);
numaAddNumber(na, val);
}
return na;
}
/*!
* numaConvertToDna
*
* Input: na
* Return: da, or null on error
*/
L_DNA *
numaConvertToDna(NUMA *na)
{
l_int32 i, n;
l_float32 val;
L_DNA *da;
PROCNAME("numaConvertToDna");
if (!na)
return (L_DNA *)ERROR_PTR("na not defined", procName, NULL);
n = numaGetCount(na);
da = l_dnaCreate(n);
for (i = 0; i < n; i++) {
numaGetFValue(na, i, &val);
l_dnaAddNumber(da, val);
}
return da;
}
/*!
* l_dnaJoin()
*
* Input: dad (dest dma; add to this one)
* das (<optional> source dna; add from this one)
* istart (starting index in das)
* iend (ending index in das; use -1 to cat all)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) istart < 0 is taken to mean 'read from the start' (istart = 0)
* (2) iend < 0 means 'read to the end'
* (3) if das == NULL, this is a no-op
*/
l_int32
l_dnaJoin(L_DNA *dad,
L_DNA *das,
l_int32 istart,
l_int32 iend)
{
l_int32 n, i;
l_float64 val;
PROCNAME("l_dnaJoin");
if (!dad)
return ERROR_INT("dad not defined", procName, 1);
if (!das)
return 0;
if (istart < 0)
istart = 0;
n = l_dnaGetCount(das);
if (iend < 0 || iend >= n)
iend = n - 1;
if (istart > iend)
return ERROR_INT("istart > iend; nothing to add", procName, 1);
for (i = istart; i <= iend; i++) {
l_dnaGetDValue(das, i, &val);
l_dnaAddNumber(dad, val);
}
return 0;
}
|
266842.c | /*====================================================================*
*
* int copyfile (char *oldfilename, char *ofn, struct stat *logstat, flag_t flags);
*
* copy one file to another; abandon the operation on failure but
* do not remove the new file; this preserves partial data should
* the disk fill up;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "../recycle/recycle.h"
#include "../tools/types.h"
#include "../tools/error.h"
int copyfile (char const *ifn, char const *ofn, struct stat *statinfo, flag_t flags)
{
file_t ifd = -1;
file_t ofd = -1;
char buffer [BUFSIZ];
ssize_t count;
if ((ifd = open (ifn, O_RDWR)) < 0)
{
error (0, errno, "can't open %s for reading", ifn);
return (1);
}
if ((ofd = open (ofn, O_WRONLY | O_CREAT | O_TRUNC, statinfo->st_mode)) < 0)
{
error (0, errno, "can't open %s for writing", ofn);
close (ifd);
return (1);
}
if (fchmod (ofd, statinfo->st_mode))
{
error (0, errno, "can't set %s permissions", ofn);
close (ifd);
close (ofd);
return (1);
}
if (fchown (ofd, statinfo->st_uid, statinfo->st_gid))
{
error (0, errno, "can't set %s ownership", ofn);
close (ifd);
close (ofd);
return (1);
}
while ((count = read (ifd, buffer, sizeof (buffer))) > 0)
{
if (write (ofd, buffer, count) != count)
{
error (0, errno, "error writing to %s", ofn);
close (ifd);
close (ofd);
return (1);
}
}
if (count < 0)
{
error (0, errno, "error reading %s", ifn);
close (ifd);
close (ofd);
return (1);
}
if (ftruncate (ifd, 0))
{
error (0, errno, "error truncating %s", ifn);
close (ifd);
close (ofd);
return (1);
}
else
{
close (ifd);
close (ofd);
}
return (0);
}
|
588987.c |
/*============================================================================
This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3a, by John R. Hauser.
Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#include "platform.h"
#include "internals.h"
#include "softfloat.h"
float64_t f64_sub( float64_t a, float64_t b )
{
union ui64_f64 uA;
uint_fast64_t uiA;
bool signA;
union ui64_f64 uB;
uint_fast64_t uiB;
bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
float64_t (*magsFuncPtr)( uint_fast64_t, uint_fast64_t, bool );
#endif
uA.f = a;
uiA = uA.ui;
signA = signF64UI( uiA );
uB.f = b;
uiB = uB.ui;
signB = signF64UI( uiB );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
if ( signA == signB ) {
return softfloat_subMagsF64( uiA, uiB, signA );
} else {
return softfloat_addMagsF64( uiA, uiB, signA );
}
#else
magsFuncPtr =
(signA == signB) ? softfloat_subMagsF64 : softfloat_addMagsF64;
return (*magsFuncPtr)( uiA, uiB, signA );
#endif
}
|
786559.c | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Actions Semi Owl SoCs SD/MMC driver
*
* Copyright (c) 2014 Actions Semi Inc.
* Copyright (c) 2019 Manivannan Sadhasivam <[email protected]>
*
* TODO: SDIO support
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/dmaengine.h>
#include <linux/dma-direction.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/mmc/host.h>
#include <linux/mmc/slot-gpio.h>
#include <linux/module.h>
#include <linux/of_platform.h>
#include <linux/reset.h>
#include <linux/spinlock.h>
/*
* SDC registers
*/
#define OWL_REG_SD_EN 0x0000
#define OWL_REG_SD_CTL 0x0004
#define OWL_REG_SD_STATE 0x0008
#define OWL_REG_SD_CMD 0x000c
#define OWL_REG_SD_ARG 0x0010
#define OWL_REG_SD_RSPBUF0 0x0014
#define OWL_REG_SD_RSPBUF1 0x0018
#define OWL_REG_SD_RSPBUF2 0x001c
#define OWL_REG_SD_RSPBUF3 0x0020
#define OWL_REG_SD_RSPBUF4 0x0024
#define OWL_REG_SD_DAT 0x0028
#define OWL_REG_SD_BLK_SIZE 0x002c
#define OWL_REG_SD_BLK_NUM 0x0030
#define OWL_REG_SD_BUF_SIZE 0x0034
/* SD_EN Bits */
#define OWL_SD_EN_RANE BIT(31)
#define OWL_SD_EN_RAN_SEED(x) (((x) & 0x3f) << 24)
#define OWL_SD_EN_S18EN BIT(12)
#define OWL_SD_EN_RESE BIT(10)
#define OWL_SD_EN_DAT1_S BIT(9)
#define OWL_SD_EN_CLK_S BIT(8)
#define OWL_SD_ENABLE BIT(7)
#define OWL_SD_EN_BSEL BIT(6)
#define OWL_SD_EN_SDIOEN BIT(3)
#define OWL_SD_EN_DDREN BIT(2)
#define OWL_SD_EN_DATAWID(x) (((x) & 0x3) << 0)
/* SD_CTL Bits */
#define OWL_SD_CTL_TOUTEN BIT(31)
#define OWL_SD_CTL_TOUTCNT(x) (((x) & 0x7f) << 24)
#define OWL_SD_CTL_DELAY_MSK GENMASK(23, 16)
#define OWL_SD_CTL_RDELAY(x) (((x) & 0xf) << 20)
#define OWL_SD_CTL_WDELAY(x) (((x) & 0xf) << 16)
#define OWL_SD_CTL_CMDLEN BIT(13)
#define OWL_SD_CTL_SCC BIT(12)
#define OWL_SD_CTL_TCN(x) (((x) & 0xf) << 8)
#define OWL_SD_CTL_TS BIT(7)
#define OWL_SD_CTL_LBE BIT(6)
#define OWL_SD_CTL_C7EN BIT(5)
#define OWL_SD_CTL_TM(x) (((x) & 0xf) << 0)
#define OWL_SD_DELAY_LOW_CLK 0x0f
#define OWL_SD_DELAY_MID_CLK 0x0a
#define OWL_SD_DELAY_HIGH_CLK 0x09
#define OWL_SD_RDELAY_DDR50 0x0a
#define OWL_SD_WDELAY_DDR50 0x08
/* SD_STATE Bits */
#define OWL_SD_STATE_DAT1BS BIT(18)
#define OWL_SD_STATE_SDIOB_P BIT(17)
#define OWL_SD_STATE_SDIOB_EN BIT(16)
#define OWL_SD_STATE_TOUTE BIT(15)
#define OWL_SD_STATE_BAEP BIT(14)
#define OWL_SD_STATE_MEMRDY BIT(12)
#define OWL_SD_STATE_CMDS BIT(11)
#define OWL_SD_STATE_DAT1AS BIT(10)
#define OWL_SD_STATE_SDIOA_P BIT(9)
#define OWL_SD_STATE_SDIOA_EN BIT(8)
#define OWL_SD_STATE_DAT0S BIT(7)
#define OWL_SD_STATE_TEIE BIT(6)
#define OWL_SD_STATE_TEI BIT(5)
#define OWL_SD_STATE_CLNR BIT(4)
#define OWL_SD_STATE_CLC BIT(3)
#define OWL_SD_STATE_WC16ER BIT(2)
#define OWL_SD_STATE_RC16ER BIT(1)
#define OWL_SD_STATE_CRC7ER BIT(0)
#define OWL_CMD_TIMEOUT_MS 30000
struct owl_mmc_host {
struct device *dev;
struct reset_control *reset;
void __iomem *base;
struct clk *clk;
struct completion sdc_complete;
spinlock_t lock;
int irq;
u32 clock;
bool ddr_50;
enum dma_data_direction dma_dir;
struct dma_chan *dma;
struct dma_async_tx_descriptor *desc;
struct dma_slave_config dma_cfg;
struct completion dma_complete;
struct mmc_host *mmc;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
};
static void owl_mmc_update_reg(void __iomem *reg, unsigned int val, bool state)
{
unsigned int regval;
regval = readl(reg);
if (state)
regval |= val;
else
regval &= ~val;
writel(regval, reg);
}
static irqreturn_t owl_irq_handler(int irq, void *devid)
{
struct owl_mmc_host *owl_host = devid;
unsigned long flags;
u32 state;
spin_lock_irqsave(&owl_host->lock, flags);
state = readl(owl_host->base + OWL_REG_SD_STATE);
if (state & OWL_SD_STATE_TEI) {
state = readl(owl_host->base + OWL_REG_SD_STATE);
state |= OWL_SD_STATE_TEI;
writel(state, owl_host->base + OWL_REG_SD_STATE);
complete(&owl_host->sdc_complete);
}
spin_unlock_irqrestore(&owl_host->lock, flags);
return IRQ_HANDLED;
}
static void owl_mmc_finish_request(struct owl_mmc_host *owl_host)
{
struct mmc_request *mrq = owl_host->mrq;
struct mmc_data *data = mrq->data;
/* Should never be NULL */
WARN_ON(!mrq);
owl_host->mrq = NULL;
if (data)
dma_unmap_sg(owl_host->dma->device->dev, data->sg, data->sg_len,
owl_host->dma_dir);
/* Finally finish request */
mmc_request_done(owl_host->mmc, mrq);
}
static void owl_mmc_send_cmd(struct owl_mmc_host *owl_host,
struct mmc_command *cmd,
struct mmc_data *data)
{
unsigned long timeout;
u32 mode, state, resp[2];
u32 cmd_rsp_mask = 0;
init_completion(&owl_host->sdc_complete);
switch (mmc_resp_type(cmd)) {
case MMC_RSP_NONE:
mode = OWL_SD_CTL_TM(0);
break;
case MMC_RSP_R1:
if (data) {
if (data->flags & MMC_DATA_READ)
mode = OWL_SD_CTL_TM(4);
else
mode = OWL_SD_CTL_TM(5);
} else {
mode = OWL_SD_CTL_TM(1);
}
cmd_rsp_mask = OWL_SD_STATE_CLNR | OWL_SD_STATE_CRC7ER;
break;
case MMC_RSP_R1B:
mode = OWL_SD_CTL_TM(3);
cmd_rsp_mask = OWL_SD_STATE_CLNR | OWL_SD_STATE_CRC7ER;
break;
case MMC_RSP_R2:
mode = OWL_SD_CTL_TM(2);
cmd_rsp_mask = OWL_SD_STATE_CLNR | OWL_SD_STATE_CRC7ER;
break;
case MMC_RSP_R3:
mode = OWL_SD_CTL_TM(1);
cmd_rsp_mask = OWL_SD_STATE_CLNR;
break;
default:
dev_warn(owl_host->dev, "Unknown MMC command\n");
cmd->error = -EINVAL;
return;
}
/* Keep current WDELAY and RDELAY */
mode |= (readl(owl_host->base + OWL_REG_SD_CTL) & (0xff << 16));
/* Start to send corresponding command type */
writel(cmd->arg, owl_host->base + OWL_REG_SD_ARG);
writel(cmd->opcode, owl_host->base + OWL_REG_SD_CMD);
/* Set LBE to send clk at the end of last read block */
if (data) {
mode |= (OWL_SD_CTL_TS | OWL_SD_CTL_LBE | 0x64000000);
} else {
mode &= ~(OWL_SD_CTL_TOUTEN | OWL_SD_CTL_LBE);
mode |= OWL_SD_CTL_TS;
}
owl_host->cmd = cmd;
/* Start transfer */
writel(mode, owl_host->base + OWL_REG_SD_CTL);
if (data)
return;
timeout = msecs_to_jiffies(cmd->busy_timeout ? cmd->busy_timeout :
OWL_CMD_TIMEOUT_MS);
if (!wait_for_completion_timeout(&owl_host->sdc_complete, timeout)) {
dev_err(owl_host->dev, "CMD interrupt timeout\n");
cmd->error = -ETIMEDOUT;
return;
}
state = readl(owl_host->base + OWL_REG_SD_STATE);
if (mmc_resp_type(cmd) & MMC_RSP_PRESENT) {
if (cmd_rsp_mask & state) {
if (state & OWL_SD_STATE_CLNR) {
dev_err(owl_host->dev, "Error CMD_NO_RSP\n");
cmd->error = -EILSEQ;
return;
}
if (state & OWL_SD_STATE_CRC7ER) {
dev_err(owl_host->dev, "Error CMD_RSP_CRC\n");
cmd->error = -EILSEQ;
return;
}
}
if (mmc_resp_type(cmd) & MMC_RSP_136) {
cmd->resp[3] = readl(owl_host->base + OWL_REG_SD_RSPBUF0);
cmd->resp[2] = readl(owl_host->base + OWL_REG_SD_RSPBUF1);
cmd->resp[1] = readl(owl_host->base + OWL_REG_SD_RSPBUF2);
cmd->resp[0] = readl(owl_host->base + OWL_REG_SD_RSPBUF3);
} else {
resp[0] = readl(owl_host->base + OWL_REG_SD_RSPBUF0);
resp[1] = readl(owl_host->base + OWL_REG_SD_RSPBUF1);
cmd->resp[0] = resp[1] << 24 | resp[0] >> 8;
cmd->resp[1] = resp[1] >> 8;
}
}
}
static void owl_mmc_dma_complete(void *param)
{
struct owl_mmc_host *owl_host = param;
struct mmc_data *data = owl_host->data;
if (data)
complete(&owl_host->dma_complete);
}
static int owl_mmc_prepare_data(struct owl_mmc_host *owl_host,
struct mmc_data *data)
{
u32 total;
owl_mmc_update_reg(owl_host->base + OWL_REG_SD_EN, OWL_SD_EN_BSEL,
true);
writel(data->blocks, owl_host->base + OWL_REG_SD_BLK_NUM);
writel(data->blksz, owl_host->base + OWL_REG_SD_BLK_SIZE);
total = data->blksz * data->blocks;
if (total < 512)
writel(total, owl_host->base + OWL_REG_SD_BUF_SIZE);
else
writel(512, owl_host->base + OWL_REG_SD_BUF_SIZE);
if (data->flags & MMC_DATA_WRITE) {
owl_host->dma_dir = DMA_TO_DEVICE;
owl_host->dma_cfg.direction = DMA_MEM_TO_DEV;
} else {
owl_host->dma_dir = DMA_FROM_DEVICE;
owl_host->dma_cfg.direction = DMA_DEV_TO_MEM;
}
dma_map_sg(owl_host->dma->device->dev, data->sg,
data->sg_len, owl_host->dma_dir);
dmaengine_slave_config(owl_host->dma, &owl_host->dma_cfg);
owl_host->desc = dmaengine_prep_slave_sg(owl_host->dma, data->sg,
data->sg_len,
owl_host->dma_cfg.direction,
DMA_PREP_INTERRUPT |
DMA_CTRL_ACK);
if (!owl_host->desc) {
dev_err(owl_host->dev, "Can't prepare slave sg\n");
return -EBUSY;
}
owl_host->data = data;
owl_host->desc->callback = owl_mmc_dma_complete;
owl_host->desc->callback_param = (void *)owl_host;
data->error = 0;
return 0;
}
static void owl_mmc_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct owl_mmc_host *owl_host = mmc_priv(mmc);
struct mmc_data *data = mrq->data;
int ret;
owl_host->mrq = mrq;
if (mrq->data) {
ret = owl_mmc_prepare_data(owl_host, data);
if (ret < 0) {
data->error = ret;
goto err_out;
}
init_completion(&owl_host->dma_complete);
dmaengine_submit(owl_host->desc);
dma_async_issue_pending(owl_host->dma);
}
owl_mmc_send_cmd(owl_host, mrq->cmd, data);
if (data) {
if (!wait_for_completion_timeout(&owl_host->sdc_complete,
10 * HZ)) {
dev_err(owl_host->dev, "CMD interrupt timeout\n");
mrq->cmd->error = -ETIMEDOUT;
dmaengine_terminate_all(owl_host->dma);
goto err_out;
}
if (!wait_for_completion_timeout(&owl_host->dma_complete,
5 * HZ)) {
dev_err(owl_host->dev, "DMA interrupt timeout\n");
mrq->cmd->error = -ETIMEDOUT;
dmaengine_terminate_all(owl_host->dma);
goto err_out;
}
if (data->stop)
owl_mmc_send_cmd(owl_host, data->stop, NULL);
data->bytes_xfered = data->blocks * data->blksz;
}
err_out:
owl_mmc_finish_request(owl_host);
}
static int owl_mmc_set_clk_rate(struct owl_mmc_host *owl_host,
unsigned int rate)
{
unsigned long clk_rate;
int ret;
u32 reg;
reg = readl(owl_host->base + OWL_REG_SD_CTL);
reg &= ~OWL_SD_CTL_DELAY_MSK;
/* Set RDELAY and WDELAY based on the clock */
if (rate <= 1000000) {
writel(reg | OWL_SD_CTL_RDELAY(OWL_SD_DELAY_LOW_CLK) |
OWL_SD_CTL_WDELAY(OWL_SD_DELAY_LOW_CLK),
owl_host->base + OWL_REG_SD_CTL);
} else if ((rate > 1000000) && (rate <= 26000000)) {
writel(reg | OWL_SD_CTL_RDELAY(OWL_SD_DELAY_MID_CLK) |
OWL_SD_CTL_WDELAY(OWL_SD_DELAY_MID_CLK),
owl_host->base + OWL_REG_SD_CTL);
} else if ((rate > 26000000) && (rate <= 52000000) && !owl_host->ddr_50) {
writel(reg | OWL_SD_CTL_RDELAY(OWL_SD_DELAY_HIGH_CLK) |
OWL_SD_CTL_WDELAY(OWL_SD_DELAY_HIGH_CLK),
owl_host->base + OWL_REG_SD_CTL);
/* DDR50 mode has special delay chain */
} else if ((rate > 26000000) && (rate <= 52000000) && owl_host->ddr_50) {
writel(reg | OWL_SD_CTL_RDELAY(OWL_SD_RDELAY_DDR50) |
OWL_SD_CTL_WDELAY(OWL_SD_WDELAY_DDR50),
owl_host->base + OWL_REG_SD_CTL);
} else {
dev_err(owl_host->dev, "SD clock rate not supported\n");
return -EINVAL;
}
clk_rate = clk_round_rate(owl_host->clk, rate << 1);
ret = clk_set_rate(owl_host->clk, clk_rate);
return ret;
}
static void owl_mmc_set_clk(struct owl_mmc_host *owl_host, struct mmc_ios *ios)
{
if (!ios->clock)
return;
owl_host->clock = ios->clock;
owl_mmc_set_clk_rate(owl_host, ios->clock);
}
static void owl_mmc_set_bus_width(struct owl_mmc_host *owl_host,
struct mmc_ios *ios)
{
u32 reg;
reg = readl(owl_host->base + OWL_REG_SD_EN);
reg &= ~0x03;
switch (ios->bus_width) {
case MMC_BUS_WIDTH_1:
break;
case MMC_BUS_WIDTH_4:
reg |= OWL_SD_EN_DATAWID(1);
break;
case MMC_BUS_WIDTH_8:
reg |= OWL_SD_EN_DATAWID(2);
break;
}
writel(reg, owl_host->base + OWL_REG_SD_EN);
}
static void owl_mmc_ctr_reset(struct owl_mmc_host *owl_host)
{
reset_control_assert(owl_host->reset);
udelay(20);
reset_control_deassert(owl_host->reset);
}
static void owl_mmc_power_on(struct owl_mmc_host *owl_host)
{
u32 mode;
init_completion(&owl_host->sdc_complete);
/* Enable transfer end IRQ */
owl_mmc_update_reg(owl_host->base + OWL_REG_SD_STATE,
OWL_SD_STATE_TEIE, true);
/* Send init clk */
mode = (readl(owl_host->base + OWL_REG_SD_CTL) & (0xff << 16));
mode |= OWL_SD_CTL_TS | OWL_SD_CTL_TCN(5) | OWL_SD_CTL_TM(8);
writel(mode, owl_host->base + OWL_REG_SD_CTL);
if (!wait_for_completion_timeout(&owl_host->sdc_complete, HZ)) {
dev_err(owl_host->dev, "CMD interrupt timeout\n");
return;
}
}
static void owl_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct owl_mmc_host *owl_host = mmc_priv(mmc);
switch (ios->power_mode) {
case MMC_POWER_UP:
dev_dbg(owl_host->dev, "Powering card up\n");
/* Reset the SDC controller to clear all previous states */
owl_mmc_ctr_reset(owl_host);
clk_prepare_enable(owl_host->clk);
writel(OWL_SD_ENABLE | OWL_SD_EN_RESE,
owl_host->base + OWL_REG_SD_EN);
break;
case MMC_POWER_ON:
dev_dbg(owl_host->dev, "Powering card on\n");
owl_mmc_power_on(owl_host);
break;
case MMC_POWER_OFF:
dev_dbg(owl_host->dev, "Powering card off\n");
clk_disable_unprepare(owl_host->clk);
return;
default:
dev_dbg(owl_host->dev, "Ignoring unknown card power state\n");
break;
}
if (ios->clock != owl_host->clock)
owl_mmc_set_clk(owl_host, ios);
owl_mmc_set_bus_width(owl_host, ios);
/* Enable DDR mode if requested */
if (ios->timing == MMC_TIMING_UHS_DDR50) {
owl_host->ddr_50 = 1;
owl_mmc_update_reg(owl_host->base + OWL_REG_SD_EN,
OWL_SD_EN_DDREN, true);
} else {
owl_host->ddr_50 = 0;
}
}
static int owl_mmc_start_signal_voltage_switch(struct mmc_host *mmc,
struct mmc_ios *ios)
{
struct owl_mmc_host *owl_host = mmc_priv(mmc);
/* It is enough to change the pad ctrl bit for voltage switch */
switch (ios->signal_voltage) {
case MMC_SIGNAL_VOLTAGE_330:
owl_mmc_update_reg(owl_host->base + OWL_REG_SD_EN,
OWL_SD_EN_S18EN, false);
break;
case MMC_SIGNAL_VOLTAGE_180:
owl_mmc_update_reg(owl_host->base + OWL_REG_SD_EN,
OWL_SD_EN_S18EN, true);
break;
default:
return -ENOTSUPP;
}
return 0;
}
static const struct mmc_host_ops owl_mmc_ops = {
.request = owl_mmc_request,
.set_ios = owl_mmc_set_ios,
.get_ro = mmc_gpio_get_ro,
.get_cd = mmc_gpio_get_cd,
.start_signal_voltage_switch = owl_mmc_start_signal_voltage_switch,
};
static int owl_mmc_probe(struct platform_device *pdev)
{
struct owl_mmc_host *owl_host;
struct mmc_host *mmc;
struct resource *res;
int ret;
mmc = mmc_alloc_host(sizeof(struct owl_mmc_host), &pdev->dev);
if (!mmc) {
dev_err(&pdev->dev, "mmc alloc host failed\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, mmc);
owl_host = mmc_priv(mmc);
owl_host->dev = &pdev->dev;
owl_host->mmc = mmc;
spin_lock_init(&owl_host->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
owl_host->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(owl_host->base)) {
dev_err(&pdev->dev, "Failed to remap registers\n");
ret = PTR_ERR(owl_host->base);
goto err_free_host;
}
owl_host->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(owl_host->clk)) {
dev_err(&pdev->dev, "No clock defined\n");
ret = PTR_ERR(owl_host->clk);
goto err_free_host;
}
owl_host->reset = devm_reset_control_get_exclusive(&pdev->dev, NULL);
if (IS_ERR(owl_host->reset)) {
dev_err(&pdev->dev, "Could not get reset control\n");
ret = PTR_ERR(owl_host->reset);
goto err_free_host;
}
mmc->ops = &owl_mmc_ops;
mmc->max_blk_count = 512;
mmc->max_blk_size = 512;
mmc->max_segs = 256;
mmc->max_seg_size = 262144;
mmc->max_req_size = 262144;
/* 100kHz ~ 52MHz */
mmc->f_min = 100000;
mmc->f_max = 52000000;
mmc->caps |= MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED |
MMC_CAP_4_BIT_DATA;
mmc->caps2 = (MMC_CAP2_BOOTPART_NOACC | MMC_CAP2_NO_SDIO);
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34 |
MMC_VDD_165_195;
ret = mmc_of_parse(mmc);
if (ret)
goto err_free_host;
pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32);
pdev->dev.dma_mask = &pdev->dev.coherent_dma_mask;
owl_host->dma = dma_request_chan(&pdev->dev, "mmc");
if (IS_ERR(owl_host->dma)) {
dev_err(owl_host->dev, "Failed to get external DMA channel.\n");
ret = PTR_ERR(owl_host->dma);
goto err_free_host;
}
dev_info(&pdev->dev, "Using %s for DMA transfers\n",
dma_chan_name(owl_host->dma));
owl_host->dma_cfg.src_addr = res->start + OWL_REG_SD_DAT;
owl_host->dma_cfg.dst_addr = res->start + OWL_REG_SD_DAT;
owl_host->dma_cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
owl_host->dma_cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
owl_host->dma_cfg.device_fc = false;
owl_host->irq = platform_get_irq(pdev, 0);
if (owl_host->irq < 0) {
ret = -EINVAL;
goto err_free_host;
}
ret = devm_request_irq(&pdev->dev, owl_host->irq, owl_irq_handler,
0, dev_name(&pdev->dev), owl_host);
if (ret) {
dev_err(&pdev->dev, "Failed to request irq %d\n",
owl_host->irq);
goto err_free_host;
}
ret = mmc_add_host(mmc);
if (ret) {
dev_err(&pdev->dev, "Failed to add host\n");
goto err_free_host;
}
dev_dbg(&pdev->dev, "Owl MMC Controller Initialized\n");
return 0;
err_free_host:
mmc_free_host(mmc);
return ret;
}
static int owl_mmc_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
struct owl_mmc_host *owl_host = mmc_priv(mmc);
mmc_remove_host(mmc);
disable_irq(owl_host->irq);
mmc_free_host(mmc);
return 0;
}
static const struct of_device_id owl_mmc_of_match[] = {
{.compatible = "actions,owl-mmc",},
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, owl_mmc_of_match);
static struct platform_driver owl_mmc_driver = {
.driver = {
.name = "owl_mmc",
.of_match_table = owl_mmc_of_match,
},
.probe = owl_mmc_probe,
.remove = owl_mmc_remove,
};
module_platform_driver(owl_mmc_driver);
MODULE_DESCRIPTION("Actions Semi Owl SoCs SD/MMC Driver");
MODULE_AUTHOR("Actions Semi");
MODULE_AUTHOR("Manivannan Sadhasivam <[email protected]>");
MODULE_LICENSE("GPL");
|
500683.c | /*
* linux/drivers/video/68328fb.c -- Low level implementation of the
* mc68x328 LCD frame buffer device
*
* Copyright (C) 2003 Georges Menie
*
* This driver assumes an already configured controller (e.g. from config.c)
* Keep the code clean of board specific initialization.
*
* This code has not been tested with colors, colormap management functions
* are minimal (no colormap data written to the 68328 registers...)
*
* initial version of this driver:
* Copyright (C) 1998,1999 Kenneth Albanowski <[email protected]>,
* The Silver Hammer Group, Ltd.
*
* this version is based on :
*
* linux/drivers/video/vfb.c -- Virtual frame buffer device
*
* Copyright (C) 2002 James Simmons
*
* Copyright (C) 1997 Geert Uytterhoeven
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <linux/fb.h>
#include <linux/init.h>
#if defined(CONFIG_M68VZ328)
#include <asm/MC68VZ328.h>
#elif defined(CONFIG_M68EZ328)
#include <asm/MC68EZ328.h>
#elif defined(CONFIG_M68328)
#include <asm/MC68328.h>
#else
#error wrong architecture for the MC68x328 frame buffer device
#endif
#if defined(CONFIG_FB_68328_INVERT)
#define MC68X328FB_MONO_VISUAL FB_VISUAL_MONO01
#else
#define MC68X328FB_MONO_VISUAL FB_VISUAL_MONO10
#endif
static u_long videomemory;
static u_long videomemorysize;
static struct fb_info fb_info;
static u32 mc68x328fb_pseudo_palette[16];
static struct fb_var_screeninfo mc68x328fb_default __initdata = {
.red = { 0, 8, 0 },
.green = { 0, 8, 0 },
.blue = { 0, 8, 0 },
.activate = FB_ACTIVATE_TEST,
.height = -1,
.width = -1,
.pixclock = 20000,
.left_margin = 64,
.right_margin = 64,
.upper_margin = 32,
.lower_margin = 32,
.hsync_len = 64,
.vsync_len = 2,
.vmode = FB_VMODE_NONINTERLACED,
};
static struct fb_fix_screeninfo mc68x328fb_fix __initdata = {
.id = "68328fb",
.type = FB_TYPE_PACKED_PIXELS,
.xpanstep = 1,
.ypanstep = 1,
.ywrapstep = 1,
.accel = FB_ACCEL_NONE,
};
/*
* Interface used by the world
*/
int mc68x328fb_init(void);
int mc68x328fb_setup(char *);
static int mc68x328fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mc68x328fb_set_par(struct fb_info *info);
static int mc68x328fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info);
static int mc68x328fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mc68x328fb_mmap(struct fb_info *info, struct vm_area_struct *vma);
static struct fb_ops mc68x328fb_ops = {
.fb_check_var = mc68x328fb_check_var,
.fb_set_par = mc68x328fb_set_par,
.fb_setcolreg = mc68x328fb_setcolreg,
.fb_pan_display = mc68x328fb_pan_display,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_mmap = mc68x328fb_mmap,
};
/*
* Internal routines
*/
static u_long get_line_length(int xres_virtual, int bpp)
{
u_long length;
length = xres_virtual * bpp;
length = (length + 31) & ~31;
length >>= 3;
return (length);
}
/*
* Setting the video mode has been split into two parts.
* First part, xxxfb_check_var, must not write anything
* to hardware, it should only verify and adjust var.
* This means it doesn't alter par but it does use hardware
* data from it to check this var.
*/
static int mc68x328fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
u_long line_length;
/*
* FB_VMODE_CONUPDATE and FB_VMODE_SMOOTH_XPAN are equal!
* as FB_VMODE_SMOOTH_XPAN is only used internally
*/
if (var->vmode & FB_VMODE_CONUPDATE) {
var->vmode |= FB_VMODE_YWRAP;
var->xoffset = info->var.xoffset;
var->yoffset = info->var.yoffset;
}
/*
* Some very basic checks
*/
if (!var->xres)
var->xres = 1;
if (!var->yres)
var->yres = 1;
if (var->xres > var->xres_virtual)
var->xres_virtual = var->xres;
if (var->yres > var->yres_virtual)
var->yres_virtual = var->yres;
if (var->bits_per_pixel <= 1)
var->bits_per_pixel = 1;
else if (var->bits_per_pixel <= 8)
var->bits_per_pixel = 8;
else if (var->bits_per_pixel <= 16)
var->bits_per_pixel = 16;
else if (var->bits_per_pixel <= 24)
var->bits_per_pixel = 24;
else if (var->bits_per_pixel <= 32)
var->bits_per_pixel = 32;
else
return -EINVAL;
if (var->xres_virtual < var->xoffset + var->xres)
var->xres_virtual = var->xoffset + var->xres;
if (var->yres_virtual < var->yoffset + var->yres)
var->yres_virtual = var->yoffset + var->yres;
/*
* Memory limit
*/
line_length =
get_line_length(var->xres_virtual, var->bits_per_pixel);
if (line_length * var->yres_virtual > videomemorysize)
return -ENOMEM;
/*
* Now that we checked it we alter var. The reason being is that the video
* mode passed in might not work but slight changes to it might make it
* work. This way we let the user know what is acceptable.
*/
switch (var->bits_per_pixel) {
case 1:
var->red.offset = 0;
var->red.length = 1;
var->green.offset = 0;
var->green.length = 1;
var->blue.offset = 0;
var->blue.length = 1;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 8:
var->red.offset = 0;
var->red.length = 8;
var->green.offset = 0;
var->green.length = 8;
var->blue.offset = 0;
var->blue.length = 8;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 16: /* RGBA 5551 */
if (var->transp.length) {
var->red.offset = 0;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 5;
var->blue.offset = 10;
var->blue.length = 5;
var->transp.offset = 15;
var->transp.length = 1;
} else { /* RGB 565 */
var->red.offset = 0;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.offset = 11;
var->blue.length = 5;
var->transp.offset = 0;
var->transp.length = 0;
}
break;
case 24: /* RGB 888 */
var->red.offset = 0;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.offset = 16;
var->blue.length = 8;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 32: /* RGBA 8888 */
var->red.offset = 0;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.offset = 16;
var->blue.length = 8;
var->transp.offset = 24;
var->transp.length = 8;
break;
}
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.msb_right = 0;
var->transp.msb_right = 0;
return 0;
}
/* This routine actually sets the video mode. It's in here where we
* the hardware state info->par and fix which can be affected by the
* change in par. For this driver it doesn't do much.
*/
static int mc68x328fb_set_par(struct fb_info *info)
{
info->fix.line_length = get_line_length(info->var.xres_virtual,
info->var.bits_per_pixel);
return 0;
}
/*
* Set a single color register. The values supplied are already
* rounded down to the hardware's capabilities (according to the
* entries in the var structure). Return != 0 for invalid regno.
*/
static int mc68x328fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
if (regno >= 256) /* no. of hw registers */
return 1;
/*
* Program hardware... do anything you want with transp
*/
/* grayscale works only partially under directcolor */
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue =
(red * 77 + green * 151 + blue * 28) >> 8;
}
/* Directcolor:
* var->{color}.offset contains start of bitfield
* var->{color}.length contains length of bitfield
* {hardwarespecific} contains width of RAMDAC
* cmap[X] is programmed to (X << red.offset) | (X << green.offset) | (X << blue.offset)
* RAMDAC[X] is programmed to (red, green, blue)
*
* Pseudocolor:
* uses offset = 0 && length = RAMDAC register width.
* var->{color}.offset is 0
* var->{color}.length contains width of DAC
* cmap is not used
* RAMDAC[X] is programmed to (red, green, blue)
* Truecolor:
* does not use DAC. Usually 3 are present.
* var->{color}.offset contains start of bitfield
* var->{color}.length contains length of bitfield
* cmap is programmed to (red << red.offset) | (green << green.offset) |
* (blue << blue.offset) | (transp << transp.offset)
* RAMDAC does not exist
*/
#define CNVT_TOHW(val,width) ((((val)<<(width))+0x7FFF-(val))>>16)
switch (info->fix.visual) {
case FB_VISUAL_TRUECOLOR:
case FB_VISUAL_PSEUDOCOLOR:
red = CNVT_TOHW(red, info->var.red.length);
green = CNVT_TOHW(green, info->var.green.length);
blue = CNVT_TOHW(blue, info->var.blue.length);
transp = CNVT_TOHW(transp, info->var.transp.length);
break;
case FB_VISUAL_DIRECTCOLOR:
red = CNVT_TOHW(red, 8); /* expect 8 bit DAC */
green = CNVT_TOHW(green, 8);
blue = CNVT_TOHW(blue, 8);
/* hey, there is bug in transp handling... */
transp = CNVT_TOHW(transp, 8);
break;
}
#undef CNVT_TOHW
/* Truecolor has hardware independent palette */
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 v;
if (regno >= 16)
return 1;
v = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
switch (info->var.bits_per_pixel) {
case 8:
break;
case 16:
((u32 *) (info->pseudo_palette))[regno] = v;
break;
case 24:
case 32:
((u32 *) (info->pseudo_palette))[regno] = v;
break;
}
return 0;
}
return 0;
}
/*
* Pan or Wrap the Display
*
* This call looks only at xoffset, yoffset and the FB_VMODE_YWRAP flag
*/
static int mc68x328fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
if (var->vmode & FB_VMODE_YWRAP) {
if (var->yoffset < 0
|| var->yoffset >= info->var.yres_virtual
|| var->xoffset)
return -EINVAL;
} else {
if (var->xoffset + info->var.xres > info->var.xres_virtual ||
var->yoffset + info->var.yres > info->var.yres_virtual)
return -EINVAL;
}
info->var.xoffset = var->xoffset;
info->var.yoffset = var->yoffset;
if (var->vmode & FB_VMODE_YWRAP)
info->var.vmode |= FB_VMODE_YWRAP;
else
info->var.vmode &= ~FB_VMODE_YWRAP;
return 0;
}
/*
* Most drivers don't need their own mmap function
*/
static int mc68x328fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
#ifndef MMU
/* this is uClinux (no MMU) specific code */
vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
vma->vm_start = videomemory;
return 0;
#else
return -EINVAL;
#endif
}
int __init mc68x328fb_setup(char *options)
{
#if 0
char *this_opt;
#endif
if (!options || !*options)
return 1;
#if 0
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "disable", 7))
mc68x328fb_enable = 0;
}
#endif
return 1;
}
/*
* Initialisation
*/
int __init mc68x328fb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("68328fb", &option))
return -ENODEV;
mc68x328fb_setup(option);
#endif
/*
* initialize the default mode from the LCD controller registers
*/
mc68x328fb_default.xres = LXMAX;
mc68x328fb_default.yres = LYMAX+1;
mc68x328fb_default.xres_virtual = mc68x328fb_default.xres;
mc68x328fb_default.yres_virtual = mc68x328fb_default.yres;
mc68x328fb_default.bits_per_pixel = 1 + (LPICF & 0x01);
videomemory = LSSA;
videomemorysize = (mc68x328fb_default.xres_virtual+7) / 8 *
mc68x328fb_default.yres_virtual * mc68x328fb_default.bits_per_pixel;
fb_info.screen_base = (void *)videomemory;
fb_info.fbops = &mc68x328fb_ops;
fb_info.var = mc68x328fb_default;
fb_info.fix = mc68x328fb_fix;
fb_info.fix.smem_start = videomemory;
fb_info.fix.smem_len = videomemorysize;
fb_info.fix.line_length =
get_line_length(mc68x328fb_default.xres_virtual, mc68x328fb_default.bits_per_pixel);
fb_info.fix.visual = (mc68x328fb_default.bits_per_pixel) == 1 ?
MC68X328FB_MONO_VISUAL : FB_VISUAL_PSEUDOCOLOR;
if (fb_info.var.bits_per_pixel == 1) {
fb_info.var.red.length = fb_info.var.green.length = fb_info.var.blue.length = 1;
fb_info.var.red.offset = fb_info.var.green.offset = fb_info.var.blue.offset = 0;
}
fb_info.pseudo_palette = &mc68x328fb_pseudo_palette;
fb_info.flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN;
if (fb_alloc_cmap(&fb_info.cmap, 256, 0))
return -ENOMEM;
if (register_framebuffer(&fb_info) < 0) {
fb_dealloc_cmap(&fb_info.cmap);
return -EINVAL;
}
printk(KERN_INFO
"fb%d: %s frame buffer device\n", fb_info.node, fb_info.fix.id);
printk(KERN_INFO
"fb%d: %dx%dx%d at 0x%08lx\n", fb_info.node,
mc68x328fb_default.xres_virtual, mc68x328fb_default.yres_virtual,
1 << mc68x328fb_default.bits_per_pixel, videomemory);
return 0;
}
module_init(mc68x328fb_init);
#ifdef MODULE
static void __exit mc68x328fb_cleanup(void)
{
unregister_framebuffer(&fb_info);
fb_dealloc_cmap(&fb_info.cmap);
}
module_exit(mc68x328fb_cleanup);
MODULE_LICENSE("GPL");
#endif /* MODULE */
|
265699.c | #include <pebble_worker.h>
#include "Worker_Persistence.h"
static bool closedInBattle = false;
static bool workerCanLaunch = false;
bool GetClosedInBattle(void)
{
return closedInBattle;
}
void SetClosedInBattle(bool enable)
{
closedInBattle = enable;
}
bool GetWorkerCanLaunch(void)
{
return workerCanLaunch;
}
void SetWorkerCanLaunch(bool enable)
{
workerCanLaunch = enable;
}
bool LoadWorkerData(void)
{
if(!persist_exists(PERSISTED_IS_DATA_SAVED) || !persist_read_bool(PERSISTED_IS_DATA_SAVED))
return false;
if(!IsPersistedDataCurrent())
{
return false;
}
SetWorkerCanLaunch(persist_read_bool(PERSISTED_WORKER_CAN_LAUNCH));
SetClosedInBattle(persist_read_bool(PERSISTED_IN_COMBAT));
return true;
}
|
74828.c | /*
* Copyright (c) 2004-2008 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2008 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2006-2007 Los Alamos National Security, LLC.
* All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*
* In windows, many of the socket functions return an EWOULDBLOCK
* instead of \ things like EAGAIN, EINPROGRESS, etc. It has been
* verified that this will \ not conflict with other error codes that
* are returned by these functions \ under UNIX/Linux environments
*/
#include "orte_config.h"
#include "orte/constants.h"
#include "opal/types.h"
#include "opal/opal_socket_errno.h"
#include "opal/class/opal_hash_table.h"
#include "orte/util/name_fns.h"
#include "orte/mca/errmgr/errmgr.h"
#include "orte/mca/routed/routed.h"
#include "orte/runtime/orte_globals.h"
#include "orte/mca/oob/tcp/oob_tcp.h"
#include "orte/mca/oob/tcp/oob_tcp_msg.h"
static void mca_oob_tcp_msg_construct(mca_oob_tcp_msg_t*);
static void mca_oob_tcp_msg_destruct(mca_oob_tcp_msg_t*);
static void mca_oob_tcp_msg_ident(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer);
static bool mca_oob_tcp_msg_recv(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer);
static void mca_oob_tcp_msg_data(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer);
static void mca_oob_tcp_msg_ping(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer);
OBJ_CLASS_INSTANCE(
mca_oob_tcp_msg_t,
opal_list_item_t,
mca_oob_tcp_msg_construct,
mca_oob_tcp_msg_destruct);
static void mca_oob_tcp_msg_construct(mca_oob_tcp_msg_t* msg)
{
OBJ_CONSTRUCT(&msg->msg_lock, opal_mutex_t);
OBJ_CONSTRUCT(&msg->msg_condition, opal_condition_t);
}
static void mca_oob_tcp_msg_destruct(mca_oob_tcp_msg_t* msg)
{
OBJ_DESTRUCT(&msg->msg_lock);
OBJ_DESTRUCT(&msg->msg_condition);
}
/*
* Signal that a message has completed.
* @param msg (IN) Message to wait on.
* @param peer (IN) the peer of the message
* @retval ORTE_SUCCESS or error code on failure.
*/
int mca_oob_tcp_msg_complete(mca_oob_tcp_msg_t* msg, orte_process_name_t * peer)
{
OPAL_THREAD_LOCK(&msg->msg_lock);
msg->msg_complete = true;
if(NULL != msg->msg_cbfunc) {
OPAL_THREAD_UNLOCK(&msg->msg_lock);
/* post to a global list of completed messages */
if ((msg->msg_flags & ORTE_RML_FLAG_RECURSIVE_CALLBACK) == 0) {
int size;
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_lock);
opal_list_append(&mca_oob_tcp_component.tcp_msg_completed, (opal_list_item_t*)msg);
size = opal_list_get_size(&mca_oob_tcp_component.tcp_msg_completed);
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_lock);
if(size > 1) {
return ORTE_SUCCESS;
}
}
/* invoke message callback */
msg->msg_cbfunc(msg->msg_rc, peer, msg->msg_uiov, msg->msg_ucnt, msg->msg_hdr.msg_tag, msg->msg_cbdata);
/* dispatch any completed events */
if ((msg->msg_flags & ORTE_RML_FLAG_RECURSIVE_CALLBACK) == 0) {
opal_list_item_t* item;
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_lock);
opal_list_remove_item(&mca_oob_tcp_component.tcp_msg_completed, (opal_list_item_t*)msg);
MCA_OOB_TCP_MSG_RETURN(msg);
while(NULL !=
(item = opal_list_remove_first(&mca_oob_tcp_component.tcp_msg_completed))) {
msg = (mca_oob_tcp_msg_t*)item;
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_lock);
msg->msg_cbfunc(
msg->msg_rc,
&msg->msg_peer,
msg->msg_uiov,
msg->msg_ucnt,
msg->msg_hdr.msg_tag,
msg->msg_cbdata);
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_lock);
MCA_OOB_TCP_MSG_RETURN(msg);
}
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_lock);
} else {
MCA_OOB_TCP_MSG_RETURN(msg);
}
} else {
opal_condition_broadcast(&msg->msg_condition);
OPAL_THREAD_UNLOCK(&msg->msg_lock);
}
return ORTE_SUCCESS;
}
/*
* The function that actually sends the data!
* @param msg a pointer to the message to send
* @param peer the peer we are sending to
* @retval true if the entire message has been sent
* @retval false if the entire message has not been sent
*/
bool mca_oob_tcp_msg_send_handler(mca_oob_tcp_msg_t* msg, struct mca_oob_tcp_peer_t * peer)
{
int rc;
while(1) {
rc = writev(peer->peer_sd, msg->msg_rwptr, msg->msg_rwnum);
if(rc < 0) {
if(opal_socket_errno == EINTR) {
continue;
}
/* In windows, many of the socket functions return an EWOULDBLOCK instead of \
things like EAGAIN, EINPROGRESS, etc. It has been verified that this will \
not conflict with other error codes that are returned by these functions \
under UNIX/Linux environments */
else if (opal_socket_errno == EAGAIN || opal_socket_errno == EWOULDBLOCK) {
return false;
}
else {
opal_output(0, "%s->%s mca_oob_tcp_msg_send_handler: writev failed: %s (%d) [sd = %d]",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&(peer->peer_name)),
strerror(opal_socket_errno),
opal_socket_errno,
peer->peer_sd);
mca_oob_tcp_peer_close(peer);
msg->msg_rc = ORTE_ERR_CONNECTION_FAILED;
return true;
}
}
msg->msg_rc += rc;
do {/* while there is still more iovecs to write */
if(rc < (int)msg->msg_rwptr->iov_len) {
msg->msg_rwptr->iov_len -= rc;
msg->msg_rwptr->iov_base = (ompi_iov_base_ptr_t)((char *) msg->msg_rwptr->iov_base + rc);
break;
} else {
rc -= msg->msg_rwptr->iov_len;
(msg->msg_rwnum)--;
(msg->msg_rwptr)++;
if(0 == msg->msg_rwnum) {
return true;
}
}
} while(1);
}
}
/*
* Receives message data.
* @param msg the message to be received into
* @param peer the peer to receive from
* @retval true if the whole message was received
* @retval false if the whole message was not received
*/
bool mca_oob_tcp_msg_recv_handler(mca_oob_tcp_msg_t* msg, struct mca_oob_tcp_peer_t * peer)
{
/* has entire header been received */
if(msg->msg_rwptr == msg->msg_rwiov) {
if(mca_oob_tcp_msg_recv(msg, peer) == false)
return false;
/* allocate a buffer for the receive */
MCA_OOB_TCP_HDR_NTOH(&msg->msg_hdr);
if(msg->msg_hdr.msg_size > 0) {
msg->msg_rwbuf = malloc(msg->msg_hdr.msg_size);
if(NULL == msg->msg_rwbuf) {
opal_output(0, "%s-%s mca_oob_tcp_msg_recv_handler: malloc(%d) failed\n",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&(peer->peer_name)),
msg->msg_hdr.msg_size);
mca_oob_tcp_peer_close(peer);
return false;
}
msg->msg_rwiov[1].iov_base = (ompi_iov_base_ptr_t)msg->msg_rwbuf;
msg->msg_rwiov[1].iov_len = msg->msg_hdr.msg_size;
msg->msg_rwnum = 1;
} else {
msg->msg_rwiov[1].iov_base = NULL;
msg->msg_rwiov[1].iov_len = 0;
msg->msg_rwnum = 0;
}
if (mca_oob_tcp_component.tcp_debug >= OOB_TCP_DEBUG_INFO) {
opal_output(0, "%s-%s (origin: %s) mca_oob_tcp_msg_recv_handler: size %lu\n",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&(peer->peer_name)),
ORTE_NAME_PRINT(&(msg->msg_hdr.msg_origin)),
(unsigned long)(msg->msg_hdr.msg_size) );
}
}
/* do the right thing based on the message type */
switch(msg->msg_hdr.msg_type) {
case MCA_OOB_TCP_IDENT:
/* done - there is nothing else to receive */
return true;
case MCA_OOB_TCP_PING:
/* done - there is nothing else to receive */
return true;
case MCA_OOB_TCP_DATA:
/* finish receiving message */
return mca_oob_tcp_msg_recv(msg, peer);
default:
return true;
}
}
/**
* Process the current iovec
*/
static bool mca_oob_tcp_msg_recv(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer)
{
int rc;
while(msg->msg_rwnum) {
rc = readv(peer->peer_sd, msg->msg_rwptr, msg->msg_rwnum);
if(rc < 0) {
if(opal_socket_errno == EINTR) {
continue;
}
/* In windows, many of the socket functions return an EWOULDBLOCK instead of \
things like EAGAIN, EINPROGRESS, etc. It has been verified that this will \
not conflict with other error codes that are returned by these functions \
under UNIX/Linux environments */
else if (opal_socket_errno == EAGAIN || opal_socket_errno == EWOULDBLOCK) {
return false;
}
if (mca_oob_tcp_component.tcp_debug >= OOB_TCP_DEBUG_INFO) {
opal_output(0, "%s-%s mca_oob_tcp_msg_recv: readv failed: %s (%d)",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&(peer->peer_name)),
strerror(opal_socket_errno),
opal_socket_errno);
}
mca_oob_tcp_peer_close(peer);
if (NULL != mca_oob_tcp.oob_exception_callback) {
mca_oob_tcp.oob_exception_callback(&peer->peer_name, ORTE_RML_PEER_DISCONNECTED);
}
return false;
} else if (rc == 0) {
if(mca_oob_tcp_component.tcp_debug >= OOB_TCP_DEBUG_CONNECT_FAIL) {
opal_output(0, "%s-%s mca_oob_tcp_msg_recv: peer closed connection",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&(peer->peer_name)));
}
mca_oob_tcp_peer_close(peer);
if (NULL != mca_oob_tcp.oob_exception_callback) {
mca_oob_tcp.oob_exception_callback(&peer->peer_name, ORTE_RML_PEER_DISCONNECTED);
}
return false;
}
do {
if(rc < (int)msg->msg_rwptr->iov_len) {
msg->msg_rwptr->iov_len -= rc;
msg->msg_rwptr->iov_base = (ompi_iov_base_ptr_t)((char *) msg->msg_rwptr->iov_base + rc);
break;
} else {
rc -= msg->msg_rwptr->iov_len;
(msg->msg_rwnum)--;
(msg->msg_rwptr)++;
if(0 == msg->msg_rwnum) {
assert( 0 == rc );
return true;
}
}
} while(1);
}
return true;
}
/**
* Process a completed message.
*/
void mca_oob_tcp_msg_recv_complete(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer)
{
switch(msg->msg_hdr.msg_type) {
case MCA_OOB_TCP_IDENT:
mca_oob_tcp_msg_ident(msg,peer);
break;
case MCA_OOB_TCP_PING:
mca_oob_tcp_msg_ping(msg,peer);
break;
case MCA_OOB_TCP_DATA:
mca_oob_tcp_msg_data(msg,peer);
break;
default:
opal_output(0, "%s mca_oob_tcp_msg_recv_complete: invalid message type: %d from peer %s\n",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), msg->msg_hdr.msg_type,
ORTE_NAME_PRINT(&peer->peer_name));
MCA_OOB_TCP_MSG_RETURN(msg);
break;
}
}
/**
* Process an ident message. In this case, we insist that the two process names
* exactly match - hence, we use the orte_ns.compare_fields function, which
* checks each field in a literal manner (i.e., no wildcards).
*/
static void mca_oob_tcp_msg_ident(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer)
{
orte_process_name_t src = msg->msg_hdr.msg_src;
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_lock);
if (orte_util_compare_name_fields(ORTE_NS_CMP_ALL, &peer->peer_name, &src) != OPAL_EQUAL) {
opal_hash_table_remove_value_uint64(&mca_oob_tcp_component.tcp_peers,
orte_util_hash_name(&peer->peer_name));
peer->peer_name = src;
opal_hash_table_set_value_uint64(&mca_oob_tcp_component.tcp_peers,
orte_util_hash_name(&peer->peer_name), peer);
}
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_lock);
}
/**
* Process a ping message.
*/
static void mca_oob_tcp_msg_ping(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer)
{
/* for now - we dont do anything - may want to send back a response at some poing */
}
/*
* Progress a completed recv:
* (1) signal a posted recv as complete
* (2) queue an unexpected message in the recv list
*/
static void mca_oob_tcp_msg_data(mca_oob_tcp_msg_t* msg, mca_oob_tcp_peer_t* peer)
{
/* attempt to match unexpected message to a posted recv */
mca_oob_tcp_msg_t* post;
int rc;
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_match_lock);
/* if I'm not a proc, check if this message came from
* another job family - procs dont' need to do this because
* they always route through their daemons anyway
*/
if (!ORTE_PROC_IS_MPI) {
if ((ORTE_JOB_FAMILY(msg->msg_hdr.msg_origin.jobid) !=
ORTE_JOB_FAMILY(ORTE_PROC_MY_NAME->jobid)) &&
(0 != ORTE_JOB_FAMILY(msg->msg_hdr.msg_origin.jobid))) {
/* this message came from a different job family that is not
* a local slave, so we may
* not know how to route any reply back to the originator. Update
* our route so we can dynamically build the routing table
*/
if (ORTE_SUCCESS != (rc = orte_routed.update_route(&(msg->msg_hdr.msg_origin),
&(msg->msg_hdr.msg_src)))) {
/* Nothing we can do about errors here as we definitely want
* the receive to complete, but at least bark loudly
*/
ORTE_ERROR_LOG(rc);
}
}
}
/* match msg against posted receives */
post = mca_oob_tcp_msg_match_post(&msg->msg_hdr.msg_origin, msg->msg_hdr.msg_tag);
if(NULL != post) {
if(NULL == post->msg_uiov || 0 == post->msg_ucnt) {
opal_output(0, "msg_data returning bad param");
post->msg_rc = ORTE_ERR_BAD_PARAM;
} else {
/* copy msg data into posted recv */
if (post->msg_flags & ORTE_RML_ALLOC) msg->msg_flags |= ORTE_RML_ALLOC;
post->msg_rc = mca_oob_tcp_msg_copy(msg, post->msg_uiov, post->msg_ucnt);
if(post->msg_flags & ORTE_RML_TRUNC) {
int i, size = 0;
for(i=1; i<msg->msg_rwcnt+1; i++)
size += msg->msg_rwiov[i].iov_len;
post->msg_rc = size;
}
}
if(post->msg_flags & ORTE_RML_PEEK) {
/* will need message for actual receive */
opal_list_append(&mca_oob_tcp_component.tcp_msg_recv, &msg->super.super);
} else {
MCA_OOB_TCP_MSG_RETURN(msg);
}
mca_oob_tcp_component.tcp_match_count++;
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_match_lock);
if(post->msg_flags & ORTE_RML_PERSISTENT) {
post->msg_cbfunc(
post->msg_rc,
&peer->peer_name,
post->msg_uiov,
post->msg_ucnt,
post->msg_hdr.msg_tag,
post->msg_cbdata);
} else {
mca_oob_tcp_msg_complete(post, &msg->msg_hdr.msg_origin);
}
OPAL_THREAD_LOCK(&mca_oob_tcp_component.tcp_match_lock);
if(--mca_oob_tcp_component.tcp_match_count == 0)
opal_condition_signal(&mca_oob_tcp_component.tcp_match_cond);
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_match_lock);
} else {
opal_list_append(&mca_oob_tcp_component.tcp_msg_recv, (opal_list_item_t*)msg);
OPAL_THREAD_UNLOCK(&mca_oob_tcp_component.tcp_match_lock);
}
}
/*
* Called to copy the results of a message into user supplied iovec array.
* @param msg (IN) Message send that is in progress.
* @param iov (IN) Iovec array of user supplied buffers.
* @retval count Number of elements in iovec array.
*/
int mca_oob_tcp_msg_copy(mca_oob_tcp_msg_t* msg, struct iovec* iov, int count)
{
int i, ret = 0;
unsigned char* src_ptr = (unsigned char*) msg->msg_rwbuf;
size_t src_len = msg->msg_hdr.msg_size;
for (i = 0 ; i < count ; i++) {
if ((msg->msg_flags & ORTE_RML_ALLOC) && (i == count - 1)) {
if (i == 0) {
iov[i].iov_base = (IOVBASE_TYPE *) src_ptr;
iov[i].iov_len = src_len;
msg->msg_rwbuf = NULL;
} else {
iov[i].iov_base = (IOVBASE_TYPE *) malloc(src_len);
iov[i].iov_len = src_len;
memcpy(iov[i].iov_base, src_ptr, src_len);
}
} else {
if (iov[i].iov_len > src_len) {
memcpy(iov[i].iov_base, src_ptr, src_len);
iov[i].iov_len = src_len;
} else {
memcpy(iov[i].iov_base, src_ptr, iov[i].iov_len);
}
}
ret += iov[i].iov_len;
src_len -= iov[i].iov_len;
src_ptr += iov[i].iov_len;
if (0 == src_len) break;
}
return ret;
}
/*
* Match name to a message that has been received asynchronously (unexpected).
*
* @param name (IN) Name associated with peer or wildcard to match first posted recv.
* @return msg Matched message or NULL.
*
* Note - this routine requires the caller to be holding the module lock.
*/
mca_oob_tcp_msg_t* mca_oob_tcp_msg_match_recv(orte_process_name_t* name, int tag)
{
mca_oob_tcp_msg_t* msg;
for(msg = (mca_oob_tcp_msg_t*) opal_list_get_first(&mca_oob_tcp_component.tcp_msg_recv);
msg != (mca_oob_tcp_msg_t*) opal_list_get_end(&mca_oob_tcp_component.tcp_msg_recv);
msg = (mca_oob_tcp_msg_t*) opal_list_get_next(msg)) {
if(OPAL_EQUAL == opal_dss.compare(name, &msg->msg_hdr.msg_origin, ORTE_NAME)) {
if (tag == msg->msg_hdr.msg_tag) {
return msg;
}
}
}
return NULL;
}
/*
* Match name to a posted recv request.
*
* @param name (IN) Name associated with peer or wildcard to match first posted recv.
* @return msg Matched message or NULL.
*
* Note - this routine requires the caller to be holding the module lock.
*/
mca_oob_tcp_msg_t* mca_oob_tcp_msg_match_post(orte_process_name_t* name, int tag)
{
mca_oob_tcp_msg_t* msg;
for(msg = (mca_oob_tcp_msg_t*) opal_list_get_first(&mca_oob_tcp_component.tcp_msg_post);
msg != (mca_oob_tcp_msg_t*) opal_list_get_end(&mca_oob_tcp_component.tcp_msg_post);
msg = (mca_oob_tcp_msg_t*) opal_list_get_next(msg)) {
if(OPAL_EQUAL == opal_dss.compare(name, &msg->msg_peer, ORTE_NAME)) {
if (msg->msg_hdr.msg_tag == tag) {
if((msg->msg_flags & ORTE_RML_PERSISTENT) == 0) {
opal_list_remove_item(&mca_oob_tcp_component.tcp_msg_post, &msg->super.super);
}
return msg;
}
}
}
return NULL;
}
|
839462.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 (xerr && 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;
}
|
503858.c | #include <std.h>
#include "/d/dagger/phederia/phedefs.h"
inherit ROOM;
void create(){
::create();
set_property("light",2);
set_short(
"Hayfield."
);
set_long(
"Hayfield.\n"
" This hayfield is overgrown and uncared for."
" It is well past harvest time and it doesnt look like anyone has put any interest in working with the field."
" The hay might once of been a perfect field but now the stalks hang grey and lifeless."
"\n"
);
set_smell("default",
"You smell the far way smells of farm animals."
);
set_listen("default",
"The animals cower away from you as if terrified of something."
);
set_items(([
"hay":"Withered, grey and dying. It should of really been harvested a long time ago.",
"fences":"Once well done boards suppored by sturdy posts kept the animals where they should be. Now they're free to wander as the fence has fallen to disrepair.",
]));
set_exits(([
"north":ROOMS"v29.c",
"east":ROOMS"v33.c",
"west":ROOMS"v31.c",
"south":ROOMS"v35.c",
]));
}
|
284057.c |
/*******************************************************************
*
* CAUTION: This file is automatically generated by HSI.
* Version: 2021.2
* DO NOT EDIT.
*
* Copyright (C) 2010-2022 Xilinx, Inc. All Rights Reserved.
* SPDX-License-Identifier: MIT
*
* Description: Driver configuration
*
*******************************************************************/
#include "xparameters.h"
#include "xuartps.h"
/*
* The configuration table for devices
*/
XUartPs_Config XUartPs_ConfigTable[XPAR_XUARTPS_NUM_INSTANCES] =
{
{
XPAR_PS7_UART_1_DEVICE_ID,
XPAR_PS7_UART_1_BASEADDR,
XPAR_PS7_UART_1_UART_CLK_FREQ_HZ,
XPAR_PS7_UART_1_HAS_MODEM
}
};
|
930417.c | #include "API.h"
// Wrapper functions.
int init_db(int buf_num) {
return rso_init_db(buf_num);
}
int shutdown_db(void) {
return rso_shutdown_db();
}
int open_table(char* pathname) {
return rso_open_table(pathname);
}
int close_table(int table_id) {
return rso_close_table(table_id);
}
int db_insert(int table_id, int64_t key, char* value) {
return rso_insert(table_id, key, value);
}
int db_find(int table_id, int64_t key, char* ret_val) {
return rso_find(table_id, key, ret_val);
}
int db_delete(int table_id, int64_t key) {
return rso_delete(table_id, key);
}
int join_table(int table_id_1, int table_id_2, char* pathname) {
return rso_join_table(table_id_1, table_id_2, pathname);
} |
917351.c | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "Pemja.h"
#include "java_class/Constructor.h"
static jmethodID getParameterTypes = 0;
jobjectArray
JavaConstructor_getParameterTypes(JNIEnv* env, jobject this)
{
if (!getParameterTypes) {
getParameterTypes = (*env)->GetMethodID(env, JCONSTRUCTOR_TYPE, "getParameterTypes",
"()[Ljava/lang/Class;");
}
return (*env)->CallObjectMethod(env, this, getParameterTypes);
}
|
322860.c | /*******************************************************************************
* File Name: cycfg_routing.c
*
* Description:
* Establishes all necessary connections between hardware elements.
* This file was automatically generated and should not be modified.
* Device Configurator: 2.0.0.1483
* Device Support Library (../../../psoc6pdl): 1.6.0.4266
*
********************************************************************************
* Copyright 2017-2019 Cypress Semiconductor Corporation
* 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 "cycfg_routing.h"
void init_cycfg_routing(void)
{
}
|
482729.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "driver.h"
/* 10MB 镜像文件 */
#define SECTOR_SIZE 512
/*
#define DISK_SECTORS (20480*10)
#define DISK_SIZE (DISK_SECTORS * SECTOR_SIZE)
*/
// #define DEBUG_FATFS_DRIVER
FILE *drv_file;
void *drv_buf;
char disk_path[256];
char disk_name[32];
int open_ref;
int mkfs_flags;
extern int rom_disk; /* rom is always new */
/* 磁盘大小 */
int disk_size;
/* 磁盘扇区数 */
int disk_sectors;
int drv_init(char *path, int disk_sz)
{
open_ref = 0;
mkfs_flags = 0;
drv_buf = NULL;
memset(disk_path, 0, 256);
strcpy(disk_path, path);
if (rom_disk) { /* new one */
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: a rom disk.\n");
#endif
drv_file = fopen(disk_path, "wb+");
if (drv_file == NULL) {
printf("fatfs: open disk %s failed!\n", disk_path);
return -1;
}
} else { /* can open old disk */
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: a traditional disk.\n");
#endif
drv_file = fopen(disk_path, "rb+");
if (drv_file == NULL) { /* 文件存在则继续,不存在则失败 */
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: create a new disk.\n");
#endif
if (disk_sz == 0) { /* 磁盘为0表示不创建新的 */
printf("fatfs: disk %s not exist, please create the disk first!\n", path);
return -1;
}
drv_file = fopen(disk_path, "wb+");
if (drv_file == NULL) {
printf("fatfs: open disk %s failed!\n", disk_path);
return -1;
}
}
}
fseek(drv_file, 0, SEEK_END);
int filesz = ftell(drv_file);
if (filesz <= 0) { /* 创建一个新的镜像文件 */
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: build a new disk.\n");
#endif
/* 文件大小是参数中的大小 */
disk_size = disk_sz;
disk_sectors = disk_size / SECTOR_SIZE;
/* 文件存在,且指针在最前面 */
drv_buf = malloc(disk_size);
if (drv_buf == NULL) {
printf("fatfs: malloc for disk buf failed!\n");
fclose(drv_file);
return -1;
}
memset(drv_buf, 0, disk_size);
//mkfs_flags = 1; /* 一块新的磁盘,需要创建文件系统 */
if (fwrite(drv_buf, disk_size / 10, 10, drv_file) < 0) {
printf("fatfs: build a new disk failed!\n");
fclose(drv_file);
return -1;
}
fflush(drv_file);
} else { /* 已经存在的话,那么文件大小就是磁盘文件大小 */
disk_size = filesz;
disk_sectors = filesz / SECTOR_SIZE;
}
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: disk size=%d setctors=%d.\n", disk_size, disk_sectors);
#endif
if (drv_buf == NULL) {
/* 文件存在,且指针在最前面 */
drv_buf = malloc(disk_size);
if (drv_buf == NULL) {
printf("fatfs: malloc for disk buf failed!\n");
fclose(drv_file);
return -1;
}
memset(drv_buf, 0, disk_size);
}
fseek(drv_file, 0, SEEK_END);
filesz = ftell(drv_file);
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: disk size is %d, %d MB\n", filesz, filesz / (1024*1024));
#endif
rewind(drv_file);
/* 读取0扇区,检测是否需要创建文件系统 */
unsigned char bootbuf[SECTOR_SIZE] = {0};
if (fread(bootbuf, SECTOR_SIZE, 1, drv_file) < 0) {
printf("fatfs: read boot sector failed!\n");
fclose(drv_file);
free(drv_buf);
return -1;
}
/* 如果没有引导,说明需要创建文件系统 */
if (!(bootbuf[510] == 0x55 && bootbuf[511] == 0xAA)) {
mkfs_flags = 1;
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: need make fs on disk.\n");
#endif
}
rewind(drv_file);
return 0;
}
int drv_open()
{
//printf("fatfs: call open driver!\n");
if (open_ref > 0) {
open_ref++;
return 0;
}
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: do open driver.\n");
#endif
/* 加载磁盘数据到内存 */
rewind(drv_file);
if (fread(drv_buf, disk_size / 10, 10, drv_file) <= 0) {
printf("fatfs: load disk to ram failed!\n");
return -1;
}
rewind(drv_file);
open_ref++;
return 0;
}
int drv_close()
{
//printf("fatfs: call close driver!\n");
open_ref--;
if (open_ref > 0) {
return 0;
}
#ifdef DEBUG_FATFS_DRIVER
printf("fatfs: do close driver.\n");
#endif
rewind(drv_file);
fwrite(drv_buf, disk_size / 10, 10, drv_file);
free(drv_buf);
return fclose(drv_file);
}
int drv_read(unsigned int off, void *buffer, size_t count)
{
if (off + count > disk_sectors)
return -1;
unsigned char *pos;
pos = (unsigned char *) drv_buf + off * SECTOR_SIZE;
memcpy(buffer, pos, count * SECTOR_SIZE);
return count;
}
int drv_write(unsigned int off, void *buffer, size_t count)
{
if (off + count > disk_sectors)
return -1;
unsigned char *pos;
pos = (unsigned char *) drv_buf + off * SECTOR_SIZE;
memcpy(pos, buffer, count * SECTOR_SIZE);
return count;
}
int drv_ioctl(int cmd, unsigned long arg)
{
switch(cmd)
{
case DISKIO_SYNC:
rewind(drv_file);
fwrite(drv_buf, disk_size / 10, 10, drv_file);
fflush(drv_file);
rewind(drv_file);
break;
case DISKIO_GETSSIZE:
*(unsigned int *)arg = SECTOR_SIZE;
break;
case DISKIO_GETSIZE:
*(unsigned int *)arg = disk_sectors;
break;
default:
return -1;
}
return 0;
}
|
243257.c | /*-------------------------------------------------------------------------
*
* tablecmds.c
* Commands for creating and altering table structures and settings
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/commands/tablecmds.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tupconvert.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_inherits_fn.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/pg_type_fn.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/policy.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "commands/user.h"
#include "executor/executor.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/clauses.h"
#include "optimizer/planner.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
#include "utils/typcache.h"
/*
* ON COMMIT action list
*/
typedef struct OnCommitItem
{
Oid relid; /* relid of relation */
OnCommitAction oncommit; /* what to do at end of xact */
/*
* If this entry was created during the current transaction,
* creating_subid is the ID of the creating subxact; if created in a prior
* transaction, creating_subid is zero. If deleted during the current
* transaction, deleting_subid is the ID of the deleting subxact; if no
* deletion request is pending, deleting_subid is zero.
*/
SubTransactionId creating_subid;
SubTransactionId deleting_subid;
} OnCommitItem;
static List *on_commits = NIL;
/*
* State information for ALTER TABLE
*
* The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
* structs, one for each table modified by the operation (the named table
* plus any child tables that are affected). We save lists of subcommands
* to apply to this table (possibly modified by parse transformation steps);
* these lists will be executed in Phase 2. If a Phase 3 step is needed,
* necessary information is stored in the constraints and newvals lists.
*
* Phase 2 is divided into multiple passes; subcommands are executed in
* a pass determined by subcommand type.
*/
#define AT_PASS_UNSET -1 /* UNSET will cause ERROR */
#define AT_PASS_DROP 0 /* DROP (all flavors) */
#define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
#define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
#define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
#define AT_PASS_COL_ATTRS 4 /* set other column attributes */
/* We could support a RENAME COLUMN pass here, but not currently used */
#define AT_PASS_ADD_COL 5 /* ADD COLUMN */
#define AT_PASS_ADD_INDEX 6 /* ADD indexes */
#define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
#define AT_PASS_MISC 8 /* other stuff */
#define AT_NUM_PASSES 9
typedef struct AlteredTableInfo
{
/* Information saved before any work commences: */
Oid relid; /* Relation to work on */
char relkind; /* Its relkind */
TupleDesc oldDesc; /* Pre-modification tuple descriptor */
/* Information saved by Phase 1 for Phase 2: */
List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
/* Information saved by Phases 1/2 for Phase 3: */
List *constraints; /* List of NewConstraint */
List *newvals; /* List of NewColumnValue */
bool new_notnull; /* T if we added new NOT NULL constraints */
int rewrite; /* Reason for forced rewrite, if any */
Oid newTableSpace; /* new tablespace; 0 means no change */
bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
char newrelpersistence; /* if above is true */
/* Objects to rebuild after completing ALTER TYPE operations */
List *changedConstraintOids; /* OIDs of constraints to rebuild */
List *changedConstraintDefs; /* string definitions of same */
List *changedIndexOids; /* OIDs of indexes to rebuild */
List *changedIndexDefs; /* string definitions of same */
} AlteredTableInfo;
/* Struct describing one new constraint to check in Phase 3 scan */
/* Note: new NOT NULL constraints are handled elsewhere */
typedef struct NewConstraint
{
char *name; /* Constraint name, or NULL if none */
ConstrType contype; /* CHECK or FOREIGN */
Oid refrelid; /* PK rel, if FOREIGN */
Oid refindid; /* OID of PK's index, if FOREIGN */
Oid conid; /* OID of pg_constraint entry, if FOREIGN */
Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
List *qualstate; /* Execution state for CHECK */
} NewConstraint;
/*
* Struct describing one new column value that needs to be computed during
* Phase 3 copy (this could be either a new column with a non-null default, or
* a column that we're changing the type of). Columns without such an entry
* are just copied from the old table during ATRewriteTable. Note that the
* expr is an expression over *old* table values.
*/
typedef struct NewColumnValue
{
AttrNumber attnum; /* which column */
Expr *expr; /* expression to compute */
ExprState *exprstate; /* execution state */
} NewColumnValue;
/*
* Error-reporting support for RemoveRelations
*/
struct dropmsgstrings
{
char kind;
int nonexistent_code;
const char *nonexistent_msg;
const char *skipping_msg;
const char *nota_msg;
const char *drophint_msg;
};
static const struct dropmsgstrings dropmsgstringarray[] = {
{RELKIND_RELATION,
ERRCODE_UNDEFINED_TABLE,
gettext_noop("table \"%s\" does not exist"),
gettext_noop("table \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a table"),
gettext_noop("Use DROP TABLE to remove a table.")},
{RELKIND_SEQUENCE,
ERRCODE_UNDEFINED_TABLE,
gettext_noop("sequence \"%s\" does not exist"),
gettext_noop("sequence \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a sequence"),
gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
{RELKIND_VIEW,
ERRCODE_UNDEFINED_TABLE,
gettext_noop("view \"%s\" does not exist"),
gettext_noop("view \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a view"),
gettext_noop("Use DROP VIEW to remove a view.")},
{RELKIND_MATVIEW,
ERRCODE_UNDEFINED_TABLE,
gettext_noop("materialized view \"%s\" does not exist"),
gettext_noop("materialized view \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a materialized view"),
gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
{RELKIND_INDEX,
ERRCODE_UNDEFINED_OBJECT,
gettext_noop("index \"%s\" does not exist"),
gettext_noop("index \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not an index"),
gettext_noop("Use DROP INDEX to remove an index.")},
{RELKIND_COMPOSITE_TYPE,
ERRCODE_UNDEFINED_OBJECT,
gettext_noop("type \"%s\" does not exist"),
gettext_noop("type \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a type"),
gettext_noop("Use DROP TYPE to remove a type.")},
{RELKIND_FOREIGN_TABLE,
ERRCODE_UNDEFINED_OBJECT,
gettext_noop("foreign table \"%s\" does not exist"),
gettext_noop("foreign table \"%s\" does not exist, skipping"),
gettext_noop("\"%s\" is not a foreign table"),
gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
{'\0', 0, NULL, NULL, NULL, NULL}
};
struct DropRelationCallbackState
{
char relkind;
Oid heapOid;
bool concurrent;
};
/* Alter table target-type flags for ATSimplePermissions */
#define ATT_TABLE 0x0001
#define ATT_VIEW 0x0002
#define ATT_MATVIEW 0x0004
#define ATT_INDEX 0x0008
#define ATT_COMPOSITE_TYPE 0x0010
#define ATT_FOREIGN_TABLE 0x0020
static void truncate_check_rel(Relation rel);
static List *MergeAttributes(List *schema, List *supers, char relpersistence,
List **supOids, List **supconstr, int *supOidCount);
static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
static void StoreCatalogInheritance(Oid relationId, List *supers);
static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
int32 seqNumber, Relation inhRelation);
static int findAttrByName(const char *attributeName, List *schema);
static void AlterIndexNamespaces(Relation classRel, Relation rel,
Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
static void AlterSeqNamespaces(Relation classRel, Relation rel,
Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
LOCKMODE lockmode);
static ObjectAddress ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
bool recurse, bool recursing, LOCKMODE lockmode);
static ObjectAddress ATExecValidateConstraint(Relation rel, char *constrName,
bool recurse, bool recursing, LOCKMODE lockmode);
static int transformColumnNameList(Oid relId, List *colList,
int16 *attnums, Oid *atttypids);
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
List **attnamelist,
int16 *attnums, Oid *atttypids,
Oid *opclasses);
static Oid transformFkeyCheckAttrs(Relation pkrel,
int numattrs, int16 *attnums,
Oid *opclasses);
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
Oid *funcid);
static void validateCheckConstraint(Relation rel, HeapTuple constrtup);
static void validateForeignKeyConstraint(char *conname,
Relation rel, Relation pkrel,
Oid pkindOid, Oid constraintOid);
static void createForeignKeyTriggers(Relation rel, Oid refRelOid,
Constraint *fkconstraint,
Oid constraintOid, Oid indexOid);
static void ATController(AlterTableStmt *parsetree,
Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
bool recurse, bool recursing, LOCKMODE lockmode);
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
AlterTableCmd *cmd, LOCKMODE lockmode);
static void ATRewriteTables(AlterTableStmt *parsetree,
List **wqueue, LOCKMODE lockmode);
static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
static void ATSimplePermissions(Relation rel, int allowed_targets);
static void ATWrongRelkindError(Relation rel, int allowed_targets);
static void ATSimpleRecursion(List **wqueue, Relation rel,
AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
LOCKMODE lockmode);
static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
DropBehavior behavior);
static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode);
static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
Relation rel, ColumnDef *colDef, bool isOid,
bool recurse, bool recursing, LOCKMODE lockmode);
static void check_for_column_name_collision(Relation rel, const char *colname);
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
AlterTableCmd *cmd, LOCKMODE lockmode);
static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
static ObjectAddress ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
const char *colName, LOCKMODE lockmode);
static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
Node *newDefault, LOCKMODE lockmode);
static void ATPrepSetStatistics(Relation rel, const char *colName,
Node *newValue, LOCKMODE lockmode);
static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName,
Node *newValue, LOCKMODE lockmode);
static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
Node *options, bool isReset, LOCKMODE lockmode);
static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
Node *newValue, LOCKMODE lockmode);
static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
AlterTableCmd *cmd, LOCKMODE lockmode);
static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
DropBehavior behavior,
bool recurse, bool recursing,
bool missing_ok, LOCKMODE lockmode);
static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
static ObjectAddress ATExecAddConstraint(List **wqueue,
AlteredTableInfo *tab, Relation rel,
Constraint *newConstraint, bool recurse, bool is_readd,
LOCKMODE lockmode);
static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
IndexStmt *stmt, LOCKMODE lockmode);
static ObjectAddress ATAddCheckConstraint(List **wqueue,
AlteredTableInfo *tab, Relation rel,
Constraint *constr,
bool recurse, bool recursing, bool is_readd,
LOCKMODE lockmode);
static ObjectAddress ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
Constraint *fkconstraint, LOCKMODE lockmode);
static void ATExecDropConstraint(Relation rel, const char *constrName,
DropBehavior behavior,
bool recurse, bool recursing,
bool missing_ok, LOCKMODE lockmode);
static void ATPrepAlterColumnType(List **wqueue,
AlteredTableInfo *tab, Relation rel,
bool recurse, bool recursing,
AlterTableCmd *cmd, LOCKMODE lockmode);
static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
AlterTableCmd *cmd, LOCKMODE lockmode);
static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
List *options, LOCKMODE lockmode);
static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
LOCKMODE lockmode);
static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
char *cmd, List **wqueue, LOCKMODE lockmode,
bool rewrite);
static void RebuildConstraintComment(AlteredTableInfo *tab, int pass,
Oid objid, Relation rel, char *conname);
static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
static void TryReuseForeignKey(Oid oldId, Constraint *con);
static void change_owner_fix_column_acls(Oid relationOid,
Oid oldOwnerId, Oid newOwnerId);
static void change_owner_recurse_to_sequences(Oid relationOid,
Oid newOwnerId, LOCKMODE lockmode);
static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
LOCKMODE lockmode);
static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
static bool ATPrepChangePersistence(Relation rel, bool toLogged);
static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
char *tablespacename, LOCKMODE lockmode);
static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
static void ATExecSetRelOptions(Relation rel, List *defList,
AlterTableType operation,
LOCKMODE lockmode);
static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
char fires_when, bool skip_system, LOCKMODE lockmode);
static void ATExecEnableDisableRule(Relation rel, char *rulename,
char fires_when, LOCKMODE lockmode);
static void ATPrepAddInherit(Relation child_rel);
static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid);
static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
static void ATExecGenericOptions(Relation rel, List *options);
static void ATExecEnableRowSecurity(Relation rel);
static void ATExecDisableRowSecurity(Relation rel);
static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
ForkNumber forkNum, char relpersistence);
static const char *storage_name(char c);
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
Oid oldRelOid, void *arg);
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
Oid oldrelid, void *arg);
/* ----------------------------------------------------------------
* DefineRelation
* Creates a new relation.
*
* stmt carries parsetree information from an ordinary CREATE TABLE statement.
* The other arguments are used to extend the behavior for other cases:
* relkind: relkind to assign to the new relation
* ownerId: if not InvalidOid, use this as the new relation's owner.
* typaddress: if not null, it's set to the pg_type entry's address.
*
* Note that permissions checks are done against current user regardless of
* ownerId. A nonzero ownerId is used when someone is creating a relation
* "on behalf of" someone else, so we still want to see that the current user
* has permissions to do it.
*
* If successful, returns the address of the new relation.
* ----------------------------------------------------------------
*/
ObjectAddress
DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
ObjectAddress *typaddress)
{
char relname[NAMEDATALEN];
Oid namespaceId;
List *schema = stmt->tableElts;
Oid relationId;
Oid tablespaceId;
Relation rel;
TupleDesc descriptor;
List *inheritOids;
List *old_constraints;
bool localHasOids;
int parentOidCount;
List *rawDefaults;
List *cookedDefaults;
Datum reloptions;
ListCell *listptr;
AttrNumber attnum;
static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
Oid ofTypeId;
ObjectAddress address;
/*
* Truncate relname to appropriate length (probably a waste of time, as
* parser should have done this already).
*/
StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
/*
* Check consistency of arguments
*/
if (stmt->oncommit != ONCOMMIT_NOOP
&& stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("ON COMMIT can only be used on temporary tables")));
/*
* Look up the namespace in which we are supposed to create the relation,
* check we have permission to create there, lock it against concurrent
* drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
* namespace is selected.
*/
namespaceId =
RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
/*
* Security check: disallow creating temp tables from security-restricted
* code. This is needed because calling code might not expect untrusted
* tables to appear in pg_temp at the front of its search path.
*/
if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
&& InSecurityRestrictedOperation())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("cannot create temporary table within security-restricted operation")));
/*
* Select tablespace to use. If not specified, use default tablespace
* (which may in turn default to database's default).
*/
if (stmt->tablespacename)
{
tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
}
else
{
tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
/* note InvalidOid is OK in this case */
}
/* Check permissions except when using database's default */
if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
{
AclResult aclresult;
aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
get_tablespace_name(tablespaceId));
}
/* In all cases disallow placing user relations in pg_global */
if (tablespaceId == GLOBALTABLESPACE_OID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("only shared relations can be placed in pg_global tablespace")));
/* Identify user ID that will own the table */
if (!OidIsValid(ownerId))
ownerId = GetUserId();
/*
* Parse and validate reloptions, if any.
*/
reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
true, false);
if (relkind == RELKIND_VIEW)
(void) view_reloptions(reloptions, true);
else
(void) heap_reloptions(relkind, reloptions, true);
if (stmt->ofTypename)
{
AclResult aclresult;
ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
if (aclresult != ACLCHECK_OK)
aclcheck_error_type(aclresult, ofTypeId);
}
else
ofTypeId = InvalidOid;
/*
* Look up inheritance ancestors and generate relation schema, including
* inherited attributes.
*/
schema = MergeAttributes(schema, stmt->inhRelations,
stmt->relation->relpersistence,
&inheritOids, &old_constraints, &parentOidCount);
/*
* Create a tuple descriptor from the relation schema. Note that this
* deals with column names, types, and NOT NULL constraints, but not
* default values or CHECK constraints; we handle those below.
*/
descriptor = BuildDescForRelation(schema);
/*
* Notice that we allow OIDs here only for plain tables, even though some
* other relkinds can support them. This is necessary because the
* default_with_oids GUC must apply only to plain tables and not any other
* relkind; doing otherwise would break existing pg_dump files. We could
* allow explicit "WITH OIDS" while not allowing default_with_oids to
* affect other relkinds, but it would complicate interpretOidsOption().
*/
localHasOids = interpretOidsOption(stmt->options,
(relkind == RELKIND_RELATION));
descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
/*
* Find columns with default values and prepare for insertion of the
* defaults. Pre-cooked (that is, inherited) defaults go into a list of
* CookedConstraint structs that we'll pass to heap_create_with_catalog,
* while raw defaults go into a list of RawColumnDefault structs that will
* be processed by AddRelationNewConstraints. (We can't deal with raw
* expressions until we can do transformExpr.)
*
* We can set the atthasdef flags now in the tuple descriptor; this just
* saves StoreAttrDefault from having to do an immediate update of the
* pg_attribute rows.
*/
rawDefaults = NIL;
cookedDefaults = NIL;
attnum = 0;
foreach(listptr, schema)
{
ColumnDef *colDef = lfirst(listptr);
attnum++;
if (colDef->raw_default != NULL)
{
RawColumnDefault *rawEnt;
Assert(colDef->cooked_default == NULL);
rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
rawEnt->attnum = attnum;
rawEnt->raw_default = colDef->raw_default;
rawDefaults = lappend(rawDefaults, rawEnt);
descriptor->attrs[attnum - 1]->atthasdef = true;
}
else if (colDef->cooked_default != NULL)
{
CookedConstraint *cooked;
cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
cooked->contype = CONSTR_DEFAULT;
cooked->conoid = InvalidOid; /* until created */
cooked->name = NULL;
cooked->attnum = attnum;
cooked->expr = colDef->cooked_default;
cooked->skip_validation = false;
cooked->is_local = true; /* not used for defaults */
cooked->inhcount = 0; /* ditto */
cooked->is_no_inherit = false;
cookedDefaults = lappend(cookedDefaults, cooked);
descriptor->attrs[attnum - 1]->atthasdef = true;
}
}
/*
* Create the relation. Inherited defaults and constraints are passed in
* for immediate handling --- since they don't need parsing, they can be
* stored immediately.
*/
relationId = heap_create_with_catalog(relname,
namespaceId,
tablespaceId,
InvalidOid,
InvalidOid,
ofTypeId,
ownerId,
descriptor,
list_concat(cookedDefaults,
old_constraints),
relkind,
stmt->relation->relpersistence,
false,
false,
localHasOids,
parentOidCount,
stmt->oncommit,
reloptions,
true,
allowSystemTableMods,
false,
typaddress);
/* Store inheritance information for new rel. */
StoreCatalogInheritance(relationId, inheritOids);
/*
* We must bump the command counter to make the newly-created relation
* tuple visible for opening.
*/
CommandCounterIncrement();
/*
* Open the new relation and acquire exclusive lock on it. This isn't
* really necessary for locking out other backends (since they can't see
* the new rel anyway until we commit), but it keeps the lock manager from
* complaining about deadlock risks.
*/
rel = relation_open(relationId, AccessExclusiveLock);
/*
* Now add any newly specified column default values and CHECK constraints
* to the new relation. These are passed to us in the form of raw
* parsetrees; we need to transform them to executable expression trees
* before they can be added. The most convenient way to do that is to
* apply the parser's transformExpr routine, but transformExpr doesn't
* work unless we have a pre-existing relation. So, the transformation has
* to be postponed to this final step of CREATE TABLE.
*/
if (rawDefaults || stmt->constraints)
AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
true, true, false);
ObjectAddressSet(address, RelationRelationId, relationId);
/*
* Clean up. We keep lock on new relation (although it shouldn't be
* visible to anyone else anyway, until commit).
*/
relation_close(rel, NoLock);
return address;
}
/*
* Emit the right error or warning message for a "DROP" command issued on a
* non-existent relation
*/
static void
DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
{
const struct dropmsgstrings *rentry;
if (rel->schemaname != NULL &&
!OidIsValid(LookupNamespaceNoError(rel->schemaname)))
{
if (!missing_ok)
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_SCHEMA),
errmsg("schema \"%s\" does not exist", rel->schemaname)));
}
else
{
ereport(NOTICE,
(errmsg("schema \"%s\" does not exist, skipping",
rel->schemaname)));
}
return;
}
for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
{
if (rentry->kind == rightkind)
{
if (!missing_ok)
{
ereport(ERROR,
(errcode(rentry->nonexistent_code),
errmsg(rentry->nonexistent_msg, rel->relname)));
}
else
{
ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
break;
}
}
}
Assert(rentry->kind != '\0'); /* Should be impossible */
}
/*
* Emit the right error message for a "DROP" command issued on a
* relation of the wrong type
*/
static void
DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
{
const struct dropmsgstrings *rentry;
const struct dropmsgstrings *wentry;
for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
if (rentry->kind == rightkind)
break;
Assert(rentry->kind != '\0');
for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
if (wentry->kind == wrongkind)
break;
/* wrongkind could be something we don't have in our table... */
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg(rentry->nota_msg, relname),
(wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
}
/*
* RemoveRelations
* Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
* DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
*/
void
RemoveRelations(DropStmt *drop)
{
ObjectAddresses *objects;
char relkind;
ListCell *cell;
int flags = 0;
LOCKMODE lockmode = AccessExclusiveLock;
/* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
if (drop->concurrent)
{
flags |= PERFORM_DELETION_CONCURRENTLY;
lockmode = ShareUpdateExclusiveLock;
Assert(drop->removeType == OBJECT_INDEX);
if (list_length(drop->objects) != 1)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
if (drop->behavior == DROP_CASCADE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
}
/*
* First we identify all the relations, then we delete them in a single
* performMultipleDeletions() call. This is to avoid unwanted DROP
* RESTRICT errors if one of the relations depends on another.
*/
/* Determine required relkind */
switch (drop->removeType)
{
case OBJECT_TABLE:
relkind = RELKIND_RELATION;
break;
case OBJECT_INDEX:
relkind = RELKIND_INDEX;
break;
case OBJECT_SEQUENCE:
relkind = RELKIND_SEQUENCE;
break;
case OBJECT_VIEW:
relkind = RELKIND_VIEW;
break;
case OBJECT_MATVIEW:
relkind = RELKIND_MATVIEW;
break;
case OBJECT_FOREIGN_TABLE:
relkind = RELKIND_FOREIGN_TABLE;
break;
default:
elog(ERROR, "unrecognized drop object type: %d",
(int) drop->removeType);
relkind = 0; /* keep compiler quiet */
break;
}
/* Lock and validate each relation; build a list of object addresses */
objects = new_object_addresses();
foreach(cell, drop->objects)
{
RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
Oid relOid;
ObjectAddress obj;
struct DropRelationCallbackState state;
/*
* These next few steps are a great deal like relation_openrv, but we
* don't bother building a relcache entry since we don't need it.
*
* Check for shared-cache-inval messages before trying to access the
* relation. This is needed to cover the case where the name
* identifies a rel that has been dropped and recreated since the
* start of our transaction: if we don't flush the old syscache entry,
* then we'll latch onto that entry and suffer an error later.
*/
AcceptInvalidationMessages();
/* Look up the appropriate relation using namespace search. */
state.relkind = relkind;
state.heapOid = InvalidOid;
state.concurrent = drop->concurrent;
relOid = RangeVarGetRelidExtended(rel, lockmode, true,
false,
RangeVarCallbackForDropRelation,
(void *) &state);
/* Not there? */
if (!OidIsValid(relOid))
{
DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
continue;
}
/* OK, we're ready to delete this one */
obj.classId = RelationRelationId;
obj.objectId = relOid;
obj.objectSubId = 0;
add_exact_object_address(&obj, objects);
}
performMultipleDeletions(objects, drop->behavior, flags);
free_object_addresses(objects);
}
/*
* Before acquiring a table lock, check whether we have sufficient rights.
* In the case of DROP INDEX, also try to lock the table before the index.
*/
static void
RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
void *arg)
{
HeapTuple tuple;
struct DropRelationCallbackState *state;
char relkind;
Form_pg_class classform;
LOCKMODE heap_lockmode;
state = (struct DropRelationCallbackState *) arg;
relkind = state->relkind;
heap_lockmode = state->concurrent ?
ShareUpdateExclusiveLock : AccessExclusiveLock;
/*
* If we previously locked some other index's heap, and the name we're
* looking up no longer refers to that relation, release the now-useless
* lock.
*/
if (relOid != oldRelOid && OidIsValid(state->heapOid))
{
UnlockRelationOid(state->heapOid, heap_lockmode);
state->heapOid = InvalidOid;
}
/* Didn't find a relation, so no need for locking or permission checks. */
if (!OidIsValid(relOid))
return;
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
if (!HeapTupleIsValid(tuple))
return; /* concurrently dropped, so nothing to do */
classform = (Form_pg_class) GETSTRUCT(tuple);
if (classform->relkind != relkind)
DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
/* Allow DROP to either table owner or schema owner */
if (!pg_class_ownercheck(relOid, GetUserId()) &&
!pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
rel->relname);
if (!allowSystemTableMods && IsSystemClass(relOid, classform))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
rel->relname)));
ReleaseSysCache(tuple);
/*
* In DROP INDEX, attempt to acquire lock on the parent table before
* locking the index. index_drop() will need this anyway, and since
* regular queries lock tables before their indexes, we risk deadlock if
* we do it the other way around. No error if we don't find a pg_index
* entry, though --- the relation may have been dropped.
*/
if (relkind == RELKIND_INDEX && relOid != oldRelOid)
{
state->heapOid = IndexGetRelation(relOid, true);
if (OidIsValid(state->heapOid))
LockRelationOid(state->heapOid, heap_lockmode);
}
}
/*
* ExecuteTruncate
* Executes a TRUNCATE command.
*
* This is a multi-relation truncate. We first open and grab exclusive
* lock on all relations involved, checking permissions and otherwise
* verifying that the relation is OK for truncation. In CASCADE mode,
* relations having FK references to the targeted relations are automatically
* added to the group; in RESTRICT mode, we check that all FK references are
* internal to the group that's being truncated. Finally all the relations
* are truncated and reindexed.
*/
void
ExecuteTruncate(TruncateStmt *stmt)
{
List *rels = NIL;
List *relids = NIL;
List *seq_relids = NIL;
EState *estate;
ResultRelInfo *resultRelInfos;
ResultRelInfo *resultRelInfo;
SubTransactionId mySubid;
ListCell *cell;
/*
* Open, exclusive-lock, and check all the explicitly-specified relations
*/
foreach(cell, stmt->relations)
{
RangeVar *rv = lfirst(cell);
Relation rel;
bool recurse = interpretInhOption(rv->inhOpt);
Oid myrelid;
rel = heap_openrv(rv, AccessExclusiveLock);
myrelid = RelationGetRelid(rel);
/* don't throw error for "TRUNCATE foo, foo" */
if (list_member_oid(relids, myrelid))
{
heap_close(rel, AccessExclusiveLock);
continue;
}
truncate_check_rel(rel);
rels = lappend(rels, rel);
relids = lappend_oid(relids, myrelid);
if (recurse)
{
ListCell *child;
List *children;
children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
if (list_member_oid(relids, childrelid))
continue;
/* find_all_inheritors already got lock */
rel = heap_open(childrelid, NoLock);
truncate_check_rel(rel);
rels = lappend(rels, rel);
relids = lappend_oid(relids, childrelid);
}
}
}
/*
* In CASCADE mode, suck in all referencing relations as well. This
* requires multiple iterations to find indirectly-dependent relations. At
* each phase, we need to exclusive-lock new rels before looking for their
* dependencies, else we might miss something. Also, we check each rel as
* soon as we open it, to avoid a faux pas such as holding lock for a long
* time on a rel we have no permissions for.
*/
if (stmt->behavior == DROP_CASCADE)
{
for (;;)
{
List *newrelids;
newrelids = heap_truncate_find_FKs(relids);
if (newrelids == NIL)
break; /* nothing else to add */
foreach(cell, newrelids)
{
Oid relid = lfirst_oid(cell);
Relation rel;
rel = heap_open(relid, AccessExclusiveLock);
ereport(NOTICE,
(errmsg("truncate cascades to table \"%s\"",
RelationGetRelationName(rel))));
truncate_check_rel(rel);
rels = lappend(rels, rel);
relids = lappend_oid(relids, relid);
}
}
}
/*
* Check foreign key references. In CASCADE mode, this should be
* unnecessary since we just pulled in all the references; but as a
* cross-check, do it anyway if in an Assert-enabled build.
*/
#ifdef USE_ASSERT_CHECKING
heap_truncate_check_FKs(rels, false);
#else
if (stmt->behavior == DROP_RESTRICT)
heap_truncate_check_FKs(rels, false);
#endif
/*
* If we are asked to restart sequences, find all the sequences, lock them
* (we need AccessExclusiveLock for ResetSequence), and check permissions.
* We want to do this early since it's pointless to do all the truncation
* work only to fail on sequence permissions.
*/
if (stmt->restart_seqs)
{
foreach(cell, rels)
{
Relation rel = (Relation) lfirst(cell);
List *seqlist = getOwnedSequences(RelationGetRelid(rel));
ListCell *seqcell;
foreach(seqcell, seqlist)
{
Oid seq_relid = lfirst_oid(seqcell);
Relation seq_rel;
seq_rel = relation_open(seq_relid, AccessExclusiveLock);
/* This check must match AlterSequence! */
if (!pg_class_ownercheck(seq_relid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(seq_rel));
seq_relids = lappend_oid(seq_relids, seq_relid);
relation_close(seq_rel, NoLock);
}
}
}
/* Prepare to catch AFTER triggers. */
AfterTriggerBeginQuery();
/*
* To fire triggers, we'll need an EState as well as a ResultRelInfo for
* each relation. We don't need to call ExecOpenIndices, though.
*/
estate = CreateExecutorState();
resultRelInfos = (ResultRelInfo *)
palloc(list_length(rels) * sizeof(ResultRelInfo));
resultRelInfo = resultRelInfos;
foreach(cell, rels)
{
Relation rel = (Relation) lfirst(cell);
InitResultRelInfo(resultRelInfo,
rel,
0, /* dummy rangetable index */
0);
resultRelInfo++;
}
estate->es_result_relations = resultRelInfos;
estate->es_num_result_relations = list_length(rels);
/*
* Process all BEFORE STATEMENT TRUNCATE triggers before we begin
* truncating (this is because one of them might throw an error). Also, if
* we were to allow them to prevent statement execution, that would need
* to be handled here.
*/
resultRelInfo = resultRelInfos;
foreach(cell, rels)
{
estate->es_result_relation_info = resultRelInfo;
ExecBSTruncateTriggers(estate, resultRelInfo);
resultRelInfo++;
}
/*
* OK, truncate each table.
*/
mySubid = GetCurrentSubTransactionId();
foreach(cell, rels)
{
Relation rel = (Relation) lfirst(cell);
/*
* Normally, we need a transaction-safe truncation here. However, if
* the table was either created in the current (sub)transaction or has
* a new relfilenode in the current (sub)transaction, then we can just
* truncate it in-place, because a rollback would cause the whole
* table or the current physical file to be thrown away anyway.
*/
if (rel->rd_createSubid == mySubid ||
rel->rd_newRelfilenodeSubid == mySubid)
{
/* Immediate, non-rollbackable truncation is OK */
heap_truncate_one_rel(rel);
}
else
{
Oid heap_relid;
Oid toast_relid;
MultiXactId minmulti;
/*
* This effectively deletes all rows in the table, and may be done
* in a serializable transaction. In that case we must record a
* rw-conflict in to this transaction from each transaction
* holding a predicate lock on the table.
*/
CheckTableForSerializableConflictIn(rel);
minmulti = GetOldestMultiXactId();
/*
* Need the full transaction-safe pushups.
*
* Create a new empty storage file for the relation, and assign it
* as the relfilenode value. The old storage file is scheduled for
* deletion at commit.
*/
RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
RecentXmin, minmulti);
if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
heap_create_init_fork(rel);
heap_relid = RelationGetRelid(rel);
toast_relid = rel->rd_rel->reltoastrelid;
/*
* The same for the toast table, if any.
*/
if (OidIsValid(toast_relid))
{
rel = relation_open(toast_relid, AccessExclusiveLock);
RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
RecentXmin, minmulti);
if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
heap_create_init_fork(rel);
heap_close(rel, NoLock);
}
/*
* Reconstruct the indexes to match, and we're done.
*/
reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST, 0);
}
pgstat_count_truncate(rel);
}
/*
* Restart owned sequences if we were asked to.
*/
foreach(cell, seq_relids)
{
Oid seq_relid = lfirst_oid(cell);
ResetSequence(seq_relid);
}
/*
* Process all AFTER STATEMENT TRUNCATE triggers.
*/
resultRelInfo = resultRelInfos;
foreach(cell, rels)
{
estate->es_result_relation_info = resultRelInfo;
ExecASTruncateTriggers(estate, resultRelInfo);
resultRelInfo++;
}
/* Handle queued AFTER triggers */
AfterTriggerEndQuery(estate);
/* We can clean up the EState now */
FreeExecutorState(estate);
/* And close the rels (can't do this while EState still holds refs) */
foreach(cell, rels)
{
Relation rel = (Relation) lfirst(cell);
heap_close(rel, NoLock);
}
}
/*
* Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
*/
static void
truncate_check_rel(Relation rel)
{
AclResult aclresult;
/* Only allow truncate on regular tables */
if (rel->rd_rel->relkind != RELKIND_RELATION)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table",
RelationGetRelationName(rel))));
/* Permissions checks */
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
ACL_TRUNCATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_CLASS,
RelationGetRelationName(rel));
if (!allowSystemTableMods && IsSystemRelation(rel))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
RelationGetRelationName(rel))));
/*
* Don't allow truncate on temp tables of other backends ... their local
* buffer manager is not going to cope.
*/
if (RELATION_IS_OTHER_TEMP(rel))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate temporary tables of other sessions")));
/*
* Also check for active uses of the relation in the current transaction,
* including open scans and pending AFTER trigger events.
*/
CheckTableNotInUse(rel, "TRUNCATE");
}
/*
* storage_name
* returns the name corresponding to a typstorage/attstorage enum value
*/
static const char *
storage_name(char c)
{
switch (c)
{
case 'p':
return "PLAIN";
case 'm':
return "MAIN";
case 'x':
return "EXTENDED";
case 'e':
return "EXTERNAL";
default:
return "???";
}
}
/*----------
* MergeAttributes
* Returns new schema given initial schema and superclasses.
*
* Input arguments:
* 'schema' is the column/attribute definition for the table. (It's a list
* of ColumnDef's.) It is destructively changed.
* 'supers' is a list of names (as RangeVar nodes) of parent relations.
* 'relpersistence' is a persistence type of the table.
*
* Output arguments:
* 'supOids' receives a list of the OIDs of the parent relations.
* 'supconstr' receives a list of constraints belonging to the parents,
* updated as necessary to be valid for the child.
* 'supOidCount' is set to the number of parents that have OID columns.
*
* Return value:
* Completed schema list.
*
* Notes:
* The order in which the attributes are inherited is very important.
* Intuitively, the inherited attributes should come first. If a table
* inherits from multiple parents, the order of those attributes are
* according to the order of the parents specified in CREATE TABLE.
*
* Here's an example:
*
* create table person (name text, age int4, location point);
* create table emp (salary int4, manager text) inherits(person);
* create table student (gpa float8) inherits (person);
* create table stud_emp (percent int4) inherits (emp, student);
*
* The order of the attributes of stud_emp is:
*
* person {1:name, 2:age, 3:location}
* / \
* {6:gpa} student emp {4:salary, 5:manager}
* \ /
* stud_emp {7:percent}
*
* If the same attribute name appears multiple times, then it appears
* in the result table in the proper location for its first appearance.
*
* Constraints (including NOT NULL constraints) for the child table
* are the union of all relevant constraints, from both the child schema
* and parent tables.
*
* The default value for a child column is defined as:
* (1) If the child schema specifies a default, that value is used.
* (2) If neither the child nor any parent specifies a default, then
* the column will not have a default.
* (3) If conflicting defaults are inherited from different parents
* (and not overridden by the child), an error is raised.
* (4) Otherwise the inherited default is used.
* Rule (3) is new in Postgres 7.1; in earlier releases you got a
* rather arbitrary choice of which parent default to use.
*----------
*/
static List *
MergeAttributes(List *schema, List *supers, char relpersistence,
List **supOids, List **supconstr, int *supOidCount)
{
ListCell *entry;
List *inhSchema = NIL;
List *parentOids = NIL;
List *constraints = NIL;
int parentsWithOids = 0;
bool have_bogus_defaults = false;
int child_attno;
static Node bogus_marker = {0}; /* marks conflicting defaults */
/*
* Check for and reject tables with too many columns. We perform this
* check relatively early for two reasons: (a) we don't run the risk of
* overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
* okay if we're processing <= 1600 columns, but could take minutes to
* execute if the user attempts to create a table with hundreds of
* thousands of columns.
*
* Note that we also need to check that any we do not exceed this figure
* after including columns from inherited relations.
*/
if (list_length(schema) > MaxHeapAttributeNumber)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("tables can have at most %d columns",
MaxHeapAttributeNumber)));
/*
* Check for duplicate names in the explicit list of attributes.
*
* Although we might consider merging such entries in the same way that we
* handle name conflicts for inherited attributes, it seems to make more
* sense to assume such conflicts are errors.
*/
foreach(entry, schema)
{
ColumnDef *coldef = lfirst(entry);
ListCell *rest = lnext(entry);
ListCell *prev = entry;
if (coldef->typeName == NULL)
/*
* Typed table column option that does not belong to a column from
* the type. This works because the columns from the type come
* first in the list.
*/
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" does not exist",
coldef->colname)));
while (rest != NULL)
{
ColumnDef *restdef = lfirst(rest);
ListCell *next = lnext(rest); /* need to save it in case we
* delete it */
if (strcmp(coldef->colname, restdef->colname) == 0)
{
if (coldef->is_from_type)
{
/*
* merge the column options into the column from the type
*/
coldef->is_not_null = restdef->is_not_null;
coldef->raw_default = restdef->raw_default;
coldef->cooked_default = restdef->cooked_default;
coldef->constraints = restdef->constraints;
coldef->is_from_type = false;
list_delete_cell(schema, rest, prev);
}
else
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column \"%s\" specified more than once",
coldef->colname)));
}
prev = rest;
rest = next;
}
}
/*
* Scan the parents left-to-right, and merge their attributes to form a
* list of inherited attributes (inhSchema). Also check to see if we need
* to inherit an OID column.
*/
child_attno = 0;
foreach(entry, supers)
{
RangeVar *parent = (RangeVar *) lfirst(entry);
Relation relation;
TupleDesc tupleDesc;
TupleConstr *constr;
AttrNumber *newattno;
AttrNumber parent_attno;
/*
* A self-exclusive lock is needed here. If two backends attempt to
* add children to the same parent simultaneously, and that parent has
* no pre-existing children, then both will attempt to update the
* parent's relhassubclass field, leading to a "tuple concurrently
* updated" error. Also, this interlocks against a concurrent ANALYZE
* on the parent table, which might otherwise be attempting to clear
* the parent's relhassubclass field, if its previous children were
* recently dropped.
*/
relation = heap_openrv(parent, ShareUpdateExclusiveLock);
if (relation->rd_rel->relkind != RELKIND_RELATION &&
relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("inherited relation \"%s\" is not a table or foreign table",
parent->relname)));
/* Permanent rels cannot inherit from temporary ones */
if (relpersistence != RELPERSISTENCE_TEMP &&
relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot inherit from temporary relation \"%s\"",
parent->relname)));
/* If existing rel is temp, it must belong to this session */
if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
!relation->rd_islocaltemp)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot inherit from temporary relation of another session")));
/*
* We should have an UNDER permission flag for this, but for now,
* demand that creator of a child table own the parent.
*/
if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(relation));
/*
* Reject duplications in the list of parents.
*/
if (list_member_oid(parentOids, RelationGetRelid(relation)))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" would be inherited from more than once",
parent->relname)));
parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
if (relation->rd_rel->relhasoids)
parentsWithOids++;
tupleDesc = RelationGetDescr(relation);
constr = tupleDesc->constr;
/*
* newattno[] will contain the child-table attribute numbers for the
* attributes of this parent table. (They are not the same for
* parents after the first one, nor if we have dropped columns.)
*/
newattno = (AttrNumber *)
palloc0(tupleDesc->natts * sizeof(AttrNumber));
for (parent_attno = 1; parent_attno <= tupleDesc->natts;
parent_attno++)
{
Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
char *attributeName = NameStr(attribute->attname);
int exist_attno;
ColumnDef *def;
/*
* Ignore dropped columns in the parent.
*/
if (attribute->attisdropped)
continue; /* leave newattno entry as zero */
/*
* Does it conflict with some previously inherited column?
*/
exist_attno = findAttrByName(attributeName, inhSchema);
if (exist_attno > 0)
{
Oid defTypeId;
int32 deftypmod;
Oid defCollId;
/*
* Yes, try to merge the two column definitions. They must
* have the same type, typmod, and collation.
*/
ereport(NOTICE,
(errmsg("merging multiple inherited definitions of column \"%s\"",
attributeName)));
def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
if (defTypeId != attribute->atttypid ||
deftypmod != attribute->atttypmod)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("inherited column \"%s\" has a type conflict",
attributeName),
errdetail("%s versus %s",
TypeNameToString(def->typeName),
format_type_be(attribute->atttypid))));
defCollId = GetColumnDefCollation(NULL, def, defTypeId);
if (defCollId != attribute->attcollation)
ereport(ERROR,
(errcode(ERRCODE_COLLATION_MISMATCH),
errmsg("inherited column \"%s\" has a collation conflict",
attributeName),
errdetail("\"%s\" versus \"%s\"",
get_collation_name(defCollId),
get_collation_name(attribute->attcollation))));
/* Copy storage parameter */
if (def->storage == 0)
def->storage = attribute->attstorage;
else if (def->storage != attribute->attstorage)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("inherited column \"%s\" has a storage parameter conflict",
attributeName),
errdetail("%s versus %s",
storage_name(def->storage),
storage_name(attribute->attstorage))));
def->inhcount++;
/* Merge of NOT NULL constraints = OR 'em together */
def->is_not_null |= attribute->attnotnull;
/* Default and other constraints are handled below */
newattno[parent_attno - 1] = exist_attno;
}
else
{
/*
* No, create a new inherited column
*/
def = makeNode(ColumnDef);
def->colname = pstrdup(attributeName);
def->typeName = makeTypeNameFromOid(attribute->atttypid,
attribute->atttypmod);
def->inhcount = 1;
def->is_local = false;
def->is_not_null = attribute->attnotnull;
def->is_from_type = false;
def->storage = attribute->attstorage;
def->raw_default = NULL;
def->cooked_default = NULL;
def->collClause = NULL;
def->collOid = attribute->attcollation;
def->constraints = NIL;
def->location = -1;
inhSchema = lappend(inhSchema, def);
newattno[parent_attno - 1] = ++child_attno;
}
/*
* Copy default if any
*/
if (attribute->atthasdef)
{
Node *this_default = NULL;
AttrDefault *attrdef;
int i;
/* Find default in constraint structure */
Assert(constr != NULL);
attrdef = constr->defval;
for (i = 0; i < constr->num_defval; i++)
{
if (attrdef[i].adnum == parent_attno)
{
this_default = stringToNode(attrdef[i].adbin);
break;
}
}
Assert(this_default != NULL);
/*
* If default expr could contain any vars, we'd need to fix
* 'em, but it can't; so default is ready to apply to child.
*
* If we already had a default from some prior parent, check
* to see if they are the same. If so, no problem; if not,
* mark the column as having a bogus default. Below, we will
* complain if the bogus default isn't overridden by the child
* schema.
*/
Assert(def->raw_default == NULL);
if (def->cooked_default == NULL)
def->cooked_default = this_default;
else if (!equal(def->cooked_default, this_default))
{
def->cooked_default = &bogus_marker;
have_bogus_defaults = true;
}
}
}
/*
* Now copy the CHECK constraints of this parent, adjusting attnos
* using the completed newattno[] map. Identically named constraints
* are merged if possible, else we throw error.
*/
if (constr && constr->num_check > 0)
{
ConstrCheck *check = constr->check;
int i;
for (i = 0; i < constr->num_check; i++)
{
char *name = check[i].ccname;
Node *expr;
bool found_whole_row;
/* ignore if the constraint is non-inheritable */
if (check[i].ccnoinherit)
continue;
/* Adjust Vars to match new table's column numbering */
expr = map_variable_attnos(stringToNode(check[i].ccbin),
1, 0,
newattno, tupleDesc->natts,
&found_whole_row);
/*
* For the moment we have to reject whole-row variables. We
* could convert them, if we knew the new table's rowtype OID,
* but that hasn't been assigned yet.
*/
if (found_whole_row)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot convert whole-row table reference"),
errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
name,
RelationGetRelationName(relation))));
/* check for duplicate */
if (!MergeCheckConstraint(constraints, name, expr))
{
/* nope, this is a new one */
CookedConstraint *cooked;
cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
cooked->contype = CONSTR_CHECK;
cooked->conoid = InvalidOid; /* until created */
cooked->name = pstrdup(name);
cooked->attnum = 0; /* not used for constraints */
cooked->expr = expr;
cooked->skip_validation = false;
cooked->is_local = false;
cooked->inhcount = 1;
cooked->is_no_inherit = false;
constraints = lappend(constraints, cooked);
}
}
}
pfree(newattno);
/*
* Close the parent rel, but keep our ShareUpdateExclusiveLock on it
* until xact commit. That will prevent someone else from deleting or
* ALTERing the parent before the child is committed.
*/
heap_close(relation, NoLock);
}
/*
* If we had no inherited attributes, the result schema is just the
* explicitly declared columns. Otherwise, we need to merge the declared
* columns into the inherited schema list.
*/
if (inhSchema != NIL)
{
int schema_attno = 0;
foreach(entry, schema)
{
ColumnDef *newdef = lfirst(entry);
char *attributeName = newdef->colname;
int exist_attno;
schema_attno++;
/*
* Does it conflict with some previously inherited column?
*/
exist_attno = findAttrByName(attributeName, inhSchema);
if (exist_attno > 0)
{
ColumnDef *def;
Oid defTypeId,
newTypeId;
int32 deftypmod,
newtypmod;
Oid defcollid,
newcollid;
/*
* Yes, try to merge the two column definitions. They must
* have the same type, typmod, and collation.
*/
if (exist_attno == schema_attno)
ereport(NOTICE,
(errmsg("merging column \"%s\" with inherited definition",
attributeName)));
else
ereport(NOTICE,
(errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
errdetail("User-specified column moved to the position of the inherited column.")));
def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
if (defTypeId != newTypeId || deftypmod != newtypmod)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("column \"%s\" has a type conflict",
attributeName),
errdetail("%s versus %s",
TypeNameToString(def->typeName),
TypeNameToString(newdef->typeName))));
defcollid = GetColumnDefCollation(NULL, def, defTypeId);
newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
if (defcollid != newcollid)
ereport(ERROR,
(errcode(ERRCODE_COLLATION_MISMATCH),
errmsg("column \"%s\" has a collation conflict",
attributeName),
errdetail("\"%s\" versus \"%s\"",
get_collation_name(defcollid),
get_collation_name(newcollid))));
/* Copy storage parameter */
if (def->storage == 0)
def->storage = newdef->storage;
else if (newdef->storage != 0 && def->storage != newdef->storage)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("column \"%s\" has a storage parameter conflict",
attributeName),
errdetail("%s versus %s",
storage_name(def->storage),
storage_name(newdef->storage))));
/* Mark the column as locally defined */
def->is_local = true;
/* Merge of NOT NULL constraints = OR 'em together */
def->is_not_null |= newdef->is_not_null;
/* If new def has a default, override previous default */
if (newdef->raw_default != NULL)
{
def->raw_default = newdef->raw_default;
def->cooked_default = newdef->cooked_default;
}
}
else
{
/*
* No, attach new column to result schema
*/
inhSchema = lappend(inhSchema, newdef);
}
}
schema = inhSchema;
/*
* Check that we haven't exceeded the legal # of columns after merging
* in inherited columns.
*/
if (list_length(schema) > MaxHeapAttributeNumber)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("tables can have at most %d columns",
MaxHeapAttributeNumber)));
}
/*
* If we found any conflicting parent default values, check to make sure
* they were overridden by the child.
*/
if (have_bogus_defaults)
{
foreach(entry, schema)
{
ColumnDef *def = lfirst(entry);
if (def->cooked_default == &bogus_marker)
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
errmsg("column \"%s\" inherits conflicting default values",
def->colname),
errhint("To resolve the conflict, specify a default explicitly.")));
}
}
*supOids = parentOids;
*supconstr = constraints;
*supOidCount = parentsWithOids;
return schema;
}
/*
* MergeCheckConstraint
* Try to merge an inherited CHECK constraint with previous ones
*
* If we inherit identically-named constraints from multiple parents, we must
* merge them, or throw an error if they don't have identical definitions.
*
* constraints is a list of CookedConstraint structs for previous constraints.
*
* Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
* got a so-far-unique name, or throws error if conflict.
*/
static bool
MergeCheckConstraint(List *constraints, char *name, Node *expr)
{
ListCell *lc;
foreach(lc, constraints)
{
CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
Assert(ccon->contype == CONSTR_CHECK);
/* Non-matching names never conflict */
if (strcmp(ccon->name, name) != 0)
continue;
if (equal(expr, ccon->expr))
{
/* OK to merge */
ccon->inhcount++;
return true;
}
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
name)));
}
return false;
}
/*
* StoreCatalogInheritance
* Updates the system catalogs with proper inheritance information.
*
* supers is a list of the OIDs of the new relation's direct ancestors.
*/
static void
StoreCatalogInheritance(Oid relationId, List *supers)
{
Relation relation;
int32 seqNumber;
ListCell *entry;
/*
* sanity checks
*/
AssertArg(OidIsValid(relationId));
if (supers == NIL)
return;
/*
* Store INHERITS information in pg_inherits using direct ancestors only.
* Also enter dependencies on the direct ancestors, and make sure they are
* marked with relhassubclass = true.
*
* (Once upon a time, both direct and indirect ancestors were found here
* and then entered into pg_ipl. Since that catalog doesn't exist
* anymore, there's no need to look for indirect ancestors.)
*/
relation = heap_open(InheritsRelationId, RowExclusiveLock);
seqNumber = 1;
foreach(entry, supers)
{
Oid parentOid = lfirst_oid(entry);
StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
seqNumber++;
}
heap_close(relation, RowExclusiveLock);
}
/*
* Make catalog entries showing relationId as being an inheritance child
* of parentOid. inhRelation is the already-opened pg_inherits catalog.
*/
static void
StoreCatalogInheritance1(Oid relationId, Oid parentOid,
int32 seqNumber, Relation inhRelation)
{
TupleDesc desc = RelationGetDescr(inhRelation);
Datum values[Natts_pg_inherits];
bool nulls[Natts_pg_inherits];
ObjectAddress childobject,
parentobject;
HeapTuple tuple;
/*
* Make the pg_inherits entry
*/
values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
values[Anum_pg_inherits_inhseqno - 1] = Int32GetDatum(seqNumber);
memset(nulls, 0, sizeof(nulls));
tuple = heap_form_tuple(desc, values, nulls);
simple_heap_insert(inhRelation, tuple);
CatalogUpdateIndexes(inhRelation, tuple);
heap_freetuple(tuple);
/*
* Store a dependency too
*/
parentobject.classId = RelationRelationId;
parentobject.objectId = parentOid;
parentobject.objectSubId = 0;
childobject.classId = RelationRelationId;
childobject.objectId = relationId;
childobject.objectSubId = 0;
recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
/*
* Post creation hook of this inheritance. Since object_access_hook
* doesn't take multiple object identifiers, we relay oid of parent
* relation using auxiliary_id argument.
*/
InvokeObjectPostAlterHookArg(InheritsRelationId,
relationId, 0,
parentOid, false);
/*
* Mark the parent as having subclasses.
*/
SetRelationHasSubclass(parentOid, true);
}
/*
* Look for an existing schema entry with the given name.
*
* Returns the index (starting with 1) if attribute already exists in schema,
* 0 if it doesn't.
*/
static int
findAttrByName(const char *attributeName, List *schema)
{
ListCell *s;
int i = 1;
foreach(s, schema)
{
ColumnDef *def = lfirst(s);
if (strcmp(attributeName, def->colname) == 0)
return i;
i++;
}
return 0;
}
/*
* SetRelationHasSubclass
* Set the value of the relation's relhassubclass field in pg_class.
*
* NOTE: caller must be holding an appropriate lock on the relation.
* ShareUpdateExclusiveLock is sufficient.
*
* NOTE: an important side-effect of this operation is that an SI invalidation
* message is sent out to all backends --- including me --- causing plans
* referencing the relation to be rebuilt with the new list of children.
* This must happen even if we find that no change is needed in the pg_class
* row.
*/
void
SetRelationHasSubclass(Oid relationId, bool relhassubclass)
{
Relation relationRelation;
HeapTuple tuple;
Form_pg_class classtuple;
/*
* Fetch a modifiable copy of the tuple, modify it, update pg_class.
*/
relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relationId);
classtuple = (Form_pg_class) GETSTRUCT(tuple);
if (classtuple->relhassubclass != relhassubclass)
{
classtuple->relhassubclass = relhassubclass;
simple_heap_update(relationRelation, &tuple->t_self, tuple);
/* keep the catalog indexes up to date */
CatalogUpdateIndexes(relationRelation, tuple);
}
else
{
/* no need to change tuple, but force relcache rebuild anyway */
CacheInvalidateRelcacheByTuple(tuple);
}
heap_freetuple(tuple);
heap_close(relationRelation, RowExclusiveLock);
}
/*
* renameatt_check - basic sanity checks before attribute rename
*/
static void
renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
{
char relkind = classform->relkind;
if (classform->reloftype && !recursing)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot rename column of typed table")));
/*
* Renaming the columns of sequences or toast tables doesn't actually
* break anything from the system's point of view, since internal
* references are by attnum. But it doesn't seem right to allow users to
* change names that are hardcoded into the system, hence the following
* restriction.
*/
if (relkind != RELKIND_RELATION &&
relkind != RELKIND_VIEW &&
relkind != RELKIND_MATVIEW &&
relkind != RELKIND_COMPOSITE_TYPE &&
relkind != RELKIND_INDEX &&
relkind != RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
NameStr(classform->relname))));
/*
* permissions checking. only the owner of a class can change its schema.
*/
if (!pg_class_ownercheck(myrelid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
NameStr(classform->relname));
if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
NameStr(classform->relname))));
}
/*
* renameatt_internal - workhorse for renameatt
*
* Return value is the attribute number in the 'myrelid' relation.
*/
static AttrNumber
renameatt_internal(Oid myrelid,
const char *oldattname,
const char *newattname,
bool recurse,
bool recursing,
int expected_parents,
DropBehavior behavior)
{
Relation targetrelation;
Relation attrelation;
HeapTuple atttup;
Form_pg_attribute attform;
AttrNumber attnum;
/*
* Grab an exclusive lock on the target table, which we will NOT release
* until end of transaction.
*/
targetrelation = relation_open(myrelid, AccessExclusiveLock);
renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
/*
* if the 'recurse' flag is set then we are supposed to rename this
* attribute in all classes that inherit from 'relname' (as well as in
* 'relname').
*
* any permissions or problems with duplicate attributes will cause the
* whole transaction to abort, which is what we want -- all or nothing.
*/
if (recurse)
{
List *child_oids,
*child_numparents;
ListCell *lo,
*li;
/*
* we need the number of parents for each child so that the recursive
* calls to renameatt() can determine whether there are any parents
* outside the inheritance hierarchy being processed.
*/
child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
&child_numparents);
/*
* find_all_inheritors does the recursive search of the inheritance
* hierarchy, so all we have to do is process all of the relids in the
* list that it returns.
*/
forboth(lo, child_oids, li, child_numparents)
{
Oid childrelid = lfirst_oid(lo);
int numparents = lfirst_int(li);
if (childrelid == myrelid)
continue;
/* note we need not recurse again */
renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
}
}
else
{
/*
* If we are told not to recurse, there had better not be any child
* tables; else the rename would put them out of step.
*
* expected_parents will only be 0 if we are not already recursing.
*/
if (expected_parents == 0 &&
find_inheritance_children(myrelid, NoLock) != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("inherited column \"%s\" must be renamed in child tables too",
oldattname)));
}
/* rename attributes in typed tables of composite type */
if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
{
List *child_oids;
ListCell *lo;
child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
RelationGetRelationName(targetrelation),
behavior);
foreach(lo, child_oids)
renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
}
attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
if (!HeapTupleIsValid(atttup))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" does not exist",
oldattname)));
attform = (Form_pg_attribute) GETSTRUCT(atttup);
attnum = attform->attnum;
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot rename system column \"%s\"",
oldattname)));
/*
* if the attribute is inherited, forbid the renaming. if this is a
* top-level call to renameatt(), then expected_parents will be 0, so the
* effect of this code will be to prohibit the renaming if the attribute
* is inherited at all. if this is a recursive call to renameatt(),
* expected_parents will be the number of parents the current relation has
* within the inheritance hierarchy being processed, so we'll prohibit the
* renaming only if there are additional parents from elsewhere.
*/
if (attform->attinhcount > expected_parents)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot rename inherited column \"%s\"",
oldattname)));
/* new name should not already exist */
check_for_column_name_collision(targetrelation, newattname);
/* apply the update */
namestrcpy(&(attform->attname), newattname);
simple_heap_update(attrelation, &atttup->t_self, atttup);
/* keep system catalog indexes current */
CatalogUpdateIndexes(attrelation, atttup);
InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
heap_freetuple(atttup);
heap_close(attrelation, RowExclusiveLock);
relation_close(targetrelation, NoLock); /* close rel but keep lock */
return attnum;
}
/*
* Perform permissions and integrity checks before acquiring a relation lock.
*/
static void
RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
void *arg)
{
HeapTuple tuple;
Form_pg_class form;
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
return; /* concurrently dropped */
form = (Form_pg_class) GETSTRUCT(tuple);
renameatt_check(relid, form, false);
ReleaseSysCache(tuple);
}
/*
* renameatt - changes the name of an attribute in a relation
*
* The returned ObjectAddress is that of the renamed column.
*/
ObjectAddress
renameatt(RenameStmt *stmt)
{
Oid relid;
AttrNumber attnum;
ObjectAddress address;
/* lock level taken here should match renameatt_internal */
relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
stmt->missing_ok, false,
RangeVarCallbackForRenameAttribute,
NULL);
if (!OidIsValid(relid))
{
ereport(NOTICE,
(errmsg("relation \"%s\" does not exist, skipping",
stmt->relation->relname)));
return InvalidObjectAddress;
}
attnum =
renameatt_internal(relid,
stmt->subname, /* old att name */
stmt->newname, /* new att name */
interpretInhOption(stmt->relation->inhOpt), /* recursive? */
false, /* recursing? */
0, /* expected inhcount */
stmt->behavior);
ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
return address;
}
/*
* same logic as renameatt_internal
*/
static ObjectAddress
rename_constraint_internal(Oid myrelid,
Oid mytypid,
const char *oldconname,
const char *newconname,
bool recurse,
bool recursing,
int expected_parents)
{
Relation targetrelation = NULL;
Oid constraintOid;
HeapTuple tuple;
Form_pg_constraint con;
ObjectAddress address;
AssertArg(!myrelid || !mytypid);
if (mytypid)
{
constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
}
else
{
targetrelation = relation_open(myrelid, AccessExclusiveLock);
/*
* don't tell it whether we're recursing; we allow changing typed
* tables here
*/
renameatt_check(myrelid, RelationGetForm(targetrelation), false);
constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
}
tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for constraint %u",
constraintOid);
con = (Form_pg_constraint) GETSTRUCT(tuple);
if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
{
if (recurse)
{
List *child_oids,
*child_numparents;
ListCell *lo,
*li;
child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
&child_numparents);
forboth(lo, child_oids, li, child_numparents)
{
Oid childrelid = lfirst_oid(lo);
int numparents = lfirst_int(li);
if (childrelid == myrelid)
continue;
rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
}
}
else
{
if (expected_parents == 0 &&
find_inheritance_children(myrelid, NoLock) != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("inherited constraint \"%s\" must be renamed in child tables too",
oldconname)));
}
if (con->coninhcount > expected_parents)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot rename inherited constraint \"%s\"",
oldconname)));
}
if (con->conindid
&& (con->contype == CONSTRAINT_PRIMARY
|| con->contype == CONSTRAINT_UNIQUE
|| con->contype == CONSTRAINT_EXCLUSION))
/* rename the index; this renames the constraint as well */
RenameRelationInternal(con->conindid, newconname, false);
else
RenameConstraintById(constraintOid, newconname);
ObjectAddressSet(address, ConstraintRelationId, constraintOid);
ReleaseSysCache(tuple);
if (targetrelation)
relation_close(targetrelation, NoLock); /* close rel but keep lock */
return address;
}
ObjectAddress
RenameConstraint(RenameStmt *stmt)
{
Oid relid = InvalidOid;
Oid typid = InvalidOid;
if (stmt->renameType == OBJECT_DOMCONSTRAINT)
{
Relation rel;
HeapTuple tup;
typid = typenameTypeId(NULL, makeTypeNameFromNameList(stmt->object));
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typid);
checkDomainOwner(tup);
ReleaseSysCache(tup);
heap_close(rel, NoLock);
}
else
{
/* lock level taken here should match rename_constraint_internal */
relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
stmt->missing_ok, false,
RangeVarCallbackForRenameAttribute,
NULL);
if (!OidIsValid(relid))
{
ereport(NOTICE,
(errmsg("relation \"%s\" does not exist, skipping",
stmt->relation->relname)));
return InvalidObjectAddress;
}
}
return
rename_constraint_internal(relid, typid,
stmt->subname,
stmt->newname,
stmt->relation ? interpretInhOption(stmt->relation->inhOpt) : false, /* recursive? */
false, /* recursing? */
0 /* expected inhcount */ );
}
/*
* Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
* RENAME
*/
ObjectAddress
RenameRelation(RenameStmt *stmt)
{
Oid relid;
ObjectAddress address;
/*
* Grab an exclusive lock on the target table, index, sequence, view,
* materialized view, or foreign table, which we will NOT release until
* end of transaction.
*
* Lock level used here should match RenameRelationInternal, to avoid lock
* escalation.
*/
relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
stmt->missing_ok, false,
RangeVarCallbackForAlterRelation,
(void *) stmt);
if (!OidIsValid(relid))
{
ereport(NOTICE,
(errmsg("relation \"%s\" does not exist, skipping",
stmt->relation->relname)));
return InvalidObjectAddress;
}
/* Do the work */
RenameRelationInternal(relid, stmt->newname, false);
ObjectAddressSet(address, RelationRelationId, relid);
return address;
}
/*
* RenameRelationInternal - change the name of a relation
*
* XXX - When renaming sequences, we don't bother to modify the
* sequence name that is stored within the sequence itself
* (this would cause problems with MVCC). In the future,
* the sequence name should probably be removed from the
* sequence, AFAIK there's no need for it to be there.
*/
void
RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
{
Relation targetrelation;
Relation relrelation; /* for RELATION relation */
HeapTuple reltup;
Form_pg_class relform;
Oid namespaceId;
/*
* Grab an exclusive lock on the target table, index, sequence, view,
* materialized view, or foreign table, which we will NOT release until
* end of transaction.
*/
targetrelation = relation_open(myrelid, AccessExclusiveLock);
namespaceId = RelationGetNamespace(targetrelation);
/*
* Find relation's pg_class tuple, and make sure newrelname isn't in use.
*/
relrelation = heap_open(RelationRelationId, RowExclusiveLock);
reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
elog(ERROR, "cache lookup failed for relation %u", myrelid);
relform = (Form_pg_class) GETSTRUCT(reltup);
if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" already exists",
newrelname)));
/*
* Update pg_class tuple with new relname. (Scribbling on reltup is OK
* because it's a copy...)
*/
namestrcpy(&(relform->relname), newrelname);
simple_heap_update(relrelation, &reltup->t_self, reltup);
/* keep the system catalog indexes current */
CatalogUpdateIndexes(relrelation, reltup);
InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
InvalidOid, is_internal);
heap_freetuple(reltup);
heap_close(relrelation, RowExclusiveLock);
/*
* Also rename the associated type, if any.
*/
if (OidIsValid(targetrelation->rd_rel->reltype))
RenameTypeInternal(targetrelation->rd_rel->reltype,
newrelname, namespaceId);
/*
* Also rename the associated constraint, if any.
*/
if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
{
Oid constraintId = get_index_constraint(myrelid);
if (OidIsValid(constraintId))
RenameConstraintById(constraintId, newrelname);
}
/*
* Close rel, but keep exclusive lock!
*/
relation_close(targetrelation, NoLock);
}
/*
* Disallow ALTER TABLE (and similar commands) when the current backend has
* any open reference to the target table besides the one just acquired by
* the calling command; this implies there's an open cursor or active plan.
* We need this check because our lock doesn't protect us against stomping
* on our own foot, only other people's feet!
*
* For ALTER TABLE, the only case known to cause serious trouble is ALTER
* COLUMN TYPE, and some changes are obviously pretty benign, so this could
* possibly be relaxed to only error out for certain types of alterations.
* But the use-case for allowing any of these things is not obvious, so we
* won't work hard at it for now.
*
* We also reject these commands if there are any pending AFTER trigger events
* for the rel. This is certainly necessary for the rewriting variants of
* ALTER TABLE, because they don't preserve tuple TIDs and so the pending
* events would try to fetch the wrong tuples. It might be overly cautious
* in other cases, but again it seems better to err on the side of paranoia.
*
* REINDEX calls this with "rel" referencing the index to be rebuilt; here
* we are worried about active indexscans on the index. The trigger-event
* check can be skipped, since we are doing no damage to the parent table.
*
* The statement name (eg, "ALTER TABLE") is passed for use in error messages.
*/
void
CheckTableNotInUse(Relation rel, const char *stmt)
{
int expected_refcnt;
expected_refcnt = rel->rd_isnailed ? 2 : 1;
if (rel->rd_refcnt != expected_refcnt)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_IN_USE),
/* translator: first %s is a SQL command, eg ALTER TABLE */
errmsg("cannot %s \"%s\" because "
"it is being used by active queries in this session",
stmt, RelationGetRelationName(rel))));
if (rel->rd_rel->relkind != RELKIND_INDEX &&
AfterTriggerPendingOnRel(RelationGetRelid(rel)))
ereport(ERROR,
(errcode(ERRCODE_OBJECT_IN_USE),
/* translator: first %s is a SQL command, eg ALTER TABLE */
errmsg("cannot %s \"%s\" because "
"it has pending trigger events",
stmt, RelationGetRelationName(rel))));
}
/*
* AlterTableLookupRelation
* Look up, and lock, the OID for the relation named by an alter table
* statement.
*/
Oid
AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
{
return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
RangeVarCallbackForAlterRelation,
(void *) stmt);
}
/*
* AlterTable
* Execute ALTER TABLE, which can be a list of subcommands
*
* ALTER TABLE is performed in three phases:
* 1. Examine subcommands and perform pre-transformation checking.
* 2. Update system catalogs.
* 3. Scan table(s) to check new constraints, and optionally recopy
* the data into new table(s).
* Phase 3 is not performed unless one or more of the subcommands requires
* it. The intention of this design is to allow multiple independent
* updates of the table schema to be performed with only one pass over the
* data.
*
* ATPrepCmd performs phase 1. A "work queue" entry is created for
* each table to be affected (there may be multiple affected tables if the
* commands traverse a table inheritance hierarchy). Also we do preliminary
* validation of the subcommands, including parse transformation of those
* expressions that need to be evaluated with respect to the old table
* schema.
*
* ATRewriteCatalogs performs phase 2 for each affected table. (Note that
* phases 2 and 3 normally do no explicit recursion, since phase 1 already
* did it --- although some subcommands have to recurse in phase 2 instead.)
* Certain subcommands need to be performed before others to avoid
* unnecessary conflicts; for example, DROP COLUMN should come before
* ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
* lists, one for each logical "pass" of phase 2.
*
* ATRewriteTables performs phase 3 for those tables that need it.
*
* Thanks to the magic of MVCC, an error anywhere along the way rolls back
* the whole operation; we don't have to do anything special to clean up.
*
* The caller must lock the relation, with an appropriate lock level
* for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
* or higher. We pass the lock level down
* so that we can apply it recursively to inherited tables. Note that the
* lock level we want as we recurse might well be higher than required for
* that specific subcommand. So we pass down the overall lock requirement,
* rather than reassess it at lower levels.
*/
void
AlterTable(Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
{
Relation rel;
/* Caller is required to provide an adequate lock. */
rel = relation_open(relid, NoLock);
CheckTableNotInUse(rel, "ALTER TABLE");
ATController(stmt,
rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
lockmode);
}
/*
* AlterTableInternal
*
* ALTER TABLE with target specified by OID
*
* We do not reject if the relation is already open, because it's quite
* likely that one or more layers of caller have it open. That means it
* is unsafe to use this entry point for alterations that could break
* existing query plans. On the assumption it's not used for such, we
* don't have to reject pending AFTER triggers, either.
*/
void
AlterTableInternal(Oid relid, List *cmds, bool recurse)
{
Relation rel;
LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
rel = relation_open(relid, lockmode);
EventTriggerAlterTableRelid(relid);
ATController(NULL, rel, cmds, recurse, lockmode);
}
/*
* AlterTableGetLockLevel
*
* Sets the overall lock level required for the supplied list of subcommands.
* Policy for doing this set according to needs of AlterTable(), see
* comments there for overall explanation.
*
* Function is called before and after parsing, so it must give same
* answer each time it is called. Some subcommands are transformed
* into other subcommand types, so the transform must never be made to a
* lower lock level than previously assigned. All transforms are noted below.
*
* Since this is called before we lock the table we cannot use table metadata
* to influence the type of lock we acquire.
*
* There should be no lockmodes hardcoded into the subcommand functions. All
* lockmode decisions for ALTER TABLE are made here only. The one exception is
* ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
* and does not travel through this section of code and cannot be combined with
* any of the subcommands given here.
*
* Note that Hot Standby only knows about AccessExclusiveLocks on the master
* so any changes that might affect SELECTs running on standbys need to use
* AccessExclusiveLocks even if you think a lesser lock would do, unless you
* have a solution for that also.
*
* Also note that pg_dump uses only an AccessShareLock, meaning that anything
* that takes a lock less than AccessExclusiveLock can change object definitions
* while pg_dump is running. Be careful to check that the appropriate data is
* derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
* otherwise we might end up with an inconsistent dump that can't restore.
*/
LOCKMODE
AlterTableGetLockLevel(List *cmds)
{
/*
* This only works if we read catalog tables using MVCC snapshots.
*/
ListCell *lcmd;
LOCKMODE lockmode = ShareUpdateExclusiveLock;
foreach(lcmd, cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
switch (cmd->subtype)
{
/*
* These subcommands rewrite the heap, so require full locks.
*/
case AT_AddColumn: /* may rewrite heap, in some cases and visible
* to SELECT */
case AT_SetTableSpace: /* must rewrite heap */
case AT_AlterColumnType: /* must rewrite heap */
case AT_AddOids: /* must rewrite heap */
cmd_lockmode = AccessExclusiveLock;
break;
/*
* These subcommands may require addition of toast tables. If
* we add a toast table to a table currently being scanned, we
* might miss data added to the new toast table by concurrent
* insert transactions.
*/
case AT_SetStorage:/* may add toast tables, see
* ATRewriteCatalogs() */
cmd_lockmode = AccessExclusiveLock;
break;
/*
* Removing constraints can affect SELECTs that have been
* optimised assuming the constraint holds true.
*/
case AT_DropConstraint: /* as DROP INDEX */
case AT_DropNotNull: /* may change some SQL plans */
cmd_lockmode = AccessExclusiveLock;
break;
/*
* Subcommands that may be visible to concurrent SELECTs
*/
case AT_DropColumn: /* change visible to SELECT */
case AT_AddColumnToView: /* CREATE VIEW */
case AT_DropOids: /* calls AT_DropColumn */
case AT_EnableAlwaysRule: /* may change SELECT rules */
case AT_EnableReplicaRule: /* may change SELECT rules */
case AT_EnableRule: /* may change SELECT rules */
case AT_DisableRule: /* may change SELECT rules */
cmd_lockmode = AccessExclusiveLock;
break;
/*
* Changing owner may remove implicit SELECT privileges
*/
case AT_ChangeOwner: /* change visible to SELECT */
cmd_lockmode = AccessExclusiveLock;
break;
/*
* Changing foreign table options may affect optimisation.
*/
case AT_GenericOptions:
case AT_AlterColumnGenericOptions:
cmd_lockmode = AccessExclusiveLock;
break;
/*
* These subcommands affect write operations only.
*/
case AT_EnableTrig:
case AT_EnableAlwaysTrig:
case AT_EnableReplicaTrig:
case AT_EnableTrigAll:
case AT_EnableTrigUser:
case AT_DisableTrig:
case AT_DisableTrigAll:
case AT_DisableTrigUser:
cmd_lockmode = ShareRowExclusiveLock;
break;
/*
* These subcommands affect write operations only. XXX
* Theoretically, these could be ShareRowExclusiveLock.
*/
case AT_ColumnDefault:
case AT_AlterConstraint:
case AT_AddIndex: /* from ADD CONSTRAINT */
case AT_AddIndexConstraint:
case AT_ReplicaIdentity:
case AT_SetNotNull:
case AT_EnableRowSecurity:
case AT_DisableRowSecurity:
case AT_ForceRowSecurity:
case AT_NoForceRowSecurity:
cmd_lockmode = AccessExclusiveLock;
break;
case AT_AddConstraint:
case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
case AT_ReAddConstraint: /* becomes AT_AddConstraint */
if (IsA(cmd->def, Constraint))
{
Constraint *con = (Constraint *) cmd->def;
switch (con->contype)
{
case CONSTR_EXCLUSION:
case CONSTR_PRIMARY:
case CONSTR_UNIQUE:
/*
* Cases essentially the same as CREATE INDEX. We
* could reduce the lock strength to ShareLock if
* we can work out how to allow concurrent catalog
* updates. XXX Might be set down to
* ShareRowExclusiveLock but requires further
* analysis.
*/
cmd_lockmode = AccessExclusiveLock;
break;
case CONSTR_FOREIGN:
/*
* We add triggers to both tables when we add a
* Foreign Key, so the lock level must be at least
* as strong as CREATE TRIGGER.
*/
cmd_lockmode = ShareRowExclusiveLock;
break;
default:
cmd_lockmode = AccessExclusiveLock;
}
}
break;
/*
* These subcommands affect inheritance behaviour. Queries
* started before us will continue to see the old inheritance
* behaviour, while queries started after we commit will see
* new behaviour. No need to prevent reads or writes to the
* subtable while we hook it up though. Changing the TupDesc
* may be a problem, so keep highest lock.
*/
case AT_AddInherit:
case AT_DropInherit:
cmd_lockmode = AccessExclusiveLock;
break;
/*
* These subcommands affect implicit row type conversion. They
* have affects similar to CREATE/DROP CAST on queries. don't
* provide for invalidating parse trees as a result of such
* changes, so we keep these at AccessExclusiveLock.
*/
case AT_AddOf:
case AT_DropOf:
cmd_lockmode = AccessExclusiveLock;
break;
/*
* Only used by CREATE OR REPLACE VIEW which must conflict
* with an SELECTs currently using the view.
*/
case AT_ReplaceRelOptions:
cmd_lockmode = AccessExclusiveLock;
break;
/*
* These subcommands affect general strategies for performance
* and maintenance, though don't change the semantic results
* from normal data reads and writes. Delaying an ALTER TABLE
* behind currently active writes only delays the point where
* the new strategy begins to take effect, so there is no
* benefit in waiting. In this case the minimum restriction
* applies: we don't currently allow concurrent catalog
* updates.
*/
case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
case AT_ClusterOn: /* Uses MVCC in getIndexes() */
case AT_DropCluster: /* Uses MVCC in getIndexes() */
case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
cmd_lockmode = ShareUpdateExclusiveLock;
break;
case AT_SetLogged:
case AT_SetUnLogged:
cmd_lockmode = AccessExclusiveLock;
break;
case AT_ValidateConstraint: /* Uses MVCC in
* getConstraints() */
cmd_lockmode = ShareUpdateExclusiveLock;
break;
/*
* Rel options are more complex than first appears. Options
* are set here for tables, views and indexes; for historical
* reasons these can all be used with ALTER TABLE, so we can't
* decide between them using the basic grammar.
*
* XXX Look in detail at each option to determine lock level,
* e.g. cmd_lockmode = GetRelOptionsLockLevel((List *)
* cmd->def);
*/
case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
* getTables() */
case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
* getTables() */
cmd_lockmode = AccessExclusiveLock;
break;
default: /* oops */
elog(ERROR, "unrecognized alter table type: %d",
(int) cmd->subtype);
break;
}
/*
* Take the greatest lockmode from any subcommand
*/
if (cmd_lockmode > lockmode)
lockmode = cmd_lockmode;
}
return lockmode;
}
/*
* ATController provides top level control over the phases.
*
* parsetree is passed in to allow it to be passed to event triggers
* when requested.
*/
static void
ATController(AlterTableStmt *parsetree,
Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
{
List *wqueue = NIL;
ListCell *lcmd;
/* Phase 1: preliminary examination of commands, create work queue */
foreach(lcmd, cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
}
/* Close the relation, but keep lock until commit */
relation_close(rel, NoLock);
/* Phase 2: update system catalogs */
ATRewriteCatalogs(&wqueue, lockmode);
/* Phase 3: scan/rewrite tables as needed */
ATRewriteTables(parsetree, &wqueue, lockmode);
}
/*
* ATPrepCmd
*
* Traffic cop for ALTER TABLE Phase 1 operations, including simple
* recursion and permission checks.
*
* Caller must have acquired appropriate lock type on relation already.
* This lock should be held until commit.
*/
static void
ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
bool recurse, bool recursing, LOCKMODE lockmode)
{
AlteredTableInfo *tab;
int pass = AT_PASS_UNSET;
/* Find or create work queue entry for this table */
tab = ATGetQueueEntry(wqueue, rel);
/*
* Copy the original subcommand for each table. This avoids conflicts
* when different child tables need to make different parse
* transformations (for example, the same column may have different column
* numbers in different children).
*/
cmd = copyObject(cmd);
/*
* Do permissions checking, recursion to child tables if needed, and any
* additional phase-1 processing needed.
*/
switch (cmd->subtype)
{
case AT_AddColumn: /* ADD COLUMN */
ATSimplePermissions(rel,
ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
lockmode);
/* Recursion occurs during execution phase */
pass = AT_PASS_ADD_COL;
break;
case AT_AddColumnToView: /* add column via CREATE OR REPLACE
* VIEW */
ATSimplePermissions(rel, ATT_VIEW);
ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
lockmode);
/* Recursion occurs during execution phase */
pass = AT_PASS_ADD_COL;
break;
case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
/*
* We allow defaults on views so that INSERT into a view can have
* default-ish behavior. This works because the rewriter
* substitutes default values into INSERTs before it expands
* rules.
*/
ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE);
ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
/* No command-specific prep needed */
pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
break;
case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
/* No command-specific prep needed */
pass = AT_PASS_DROP;
break;
case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
/* No command-specific prep needed */
pass = AT_PASS_ADD_CONSTR;
break;
case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
/* Performs own permission checks */
ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
pass = AT_PASS_MISC;
break;
case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE);
/* This command never recurses */
pass = AT_PASS_MISC;
break;
case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_FOREIGN_TABLE);
ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_DropColumn: /* DROP COLUMN */
ATSimplePermissions(rel,
ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
/* Recursion occurs during execution phase */
pass = AT_PASS_DROP;
break;
case AT_AddIndex: /* ADD INDEX */
ATSimplePermissions(rel, ATT_TABLE);
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_ADD_INDEX;
break;
case AT_AddConstraint: /* ADD CONSTRAINT */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* Recursion occurs during execution phase */
/* No command-specific prep needed except saving recurse flag */
if (recurse)
cmd->subtype = AT_AddConstraintRecurse;
pass = AT_PASS_ADD_CONSTR;
break;
case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
ATSimplePermissions(rel, ATT_TABLE);
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_ADD_CONSTR;
break;
case AT_DropConstraint: /* DROP CONSTRAINT */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* Recursion occurs during execution phase */
/* No command-specific prep needed except saving recurse flag */
if (recurse)
cmd->subtype = AT_DropConstraintRecurse;
pass = AT_PASS_DROP;
break;
case AT_AlterColumnType: /* ALTER COLUMN TYPE */
ATSimplePermissions(rel,
ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
/* Performs own recursion */
ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
pass = AT_PASS_ALTER_TYPE;
break;
case AT_AlterColumnGenericOptions:
ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_ChangeOwner: /* ALTER OWNER */
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_ClusterOn: /* CLUSTER ON */
case AT_DropCluster: /* SET WITHOUT CLUSTER */
ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
/* These commands never recurse */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_SetLogged: /* SET LOGGED */
ATSimplePermissions(rel, ATT_TABLE);
tab->chgPersistence = ATPrepChangePersistence(rel, true);
/* force rewrite if necessary; see comment in ATRewriteTables */
if (tab->chgPersistence)
{
tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
}
pass = AT_PASS_MISC;
break;
case AT_SetUnLogged: /* SET UNLOGGED */
ATSimplePermissions(rel, ATT_TABLE);
tab->chgPersistence = ATPrepChangePersistence(rel, false);
/* force rewrite if necessary; see comment in ATRewriteTables */
if (tab->chgPersistence)
{
tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
}
pass = AT_PASS_MISC;
break;
case AT_AddOids: /* SET WITH OIDS */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
if (!rel->rd_rel->relhasoids || recursing)
ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
/* Recursion occurs during execution phase */
pass = AT_PASS_ADD_COL;
break;
case AT_DropOids: /* SET WITHOUT OIDS */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* Performs own recursion */
if (rel->rd_rel->relhasoids)
{
AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
dropCmd->subtype = AT_DropColumn;
dropCmd->name = pstrdup("oid");
dropCmd->behavior = cmd->behavior;
ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
}
pass = AT_PASS_DROP;
break;
case AT_SetTableSpace: /* SET TABLESPACE */
ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX);
/* This command never recurses */
ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
pass = AT_PASS_MISC; /* doesn't actually matter */
break;
case AT_SetRelOptions: /* SET (...) */
case AT_ResetRelOptions: /* RESET (...) */
case AT_ReplaceRelOptions: /* reset them all, then set just these */
ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX);
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_AddInherit: /* INHERIT */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* This command never recurses */
ATPrepAddInherit(rel);
pass = AT_PASS_MISC;
break;
case AT_DropInherit: /* NO INHERIT */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* This command never recurses */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_AlterConstraint: /* ALTER CONSTRAINT */
ATSimplePermissions(rel, ATT_TABLE);
pass = AT_PASS_MISC;
break;
case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* Recursion occurs during execution phase */
/* No command-specific prep needed except saving recurse flag */
if (recurse)
cmd->subtype = AT_ValidateConstraintRecurse;
pass = AT_PASS_MISC;
break;
case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
pass = AT_PASS_MISC;
/* This command never recurses */
/* No command-specific prep needed */
break;
case AT_EnableTrig: /* ENABLE TRIGGER variants */
case AT_EnableAlwaysTrig:
case AT_EnableReplicaTrig:
case AT_EnableTrigAll:
case AT_EnableTrigUser:
case AT_DisableTrig: /* DISABLE TRIGGER variants */
case AT_DisableTrigAll:
case AT_DisableTrigUser:
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
pass = AT_PASS_MISC;
break;
case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
case AT_EnableAlwaysRule:
case AT_EnableReplicaRule:
case AT_DisableRule:
case AT_AddOf: /* OF */
case AT_DropOf: /* NOT OF */
case AT_EnableRowSecurity:
case AT_DisableRowSecurity:
case AT_ForceRowSecurity:
case AT_NoForceRowSecurity:
ATSimplePermissions(rel, ATT_TABLE);
/* These commands never recurse */
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
case AT_GenericOptions:
ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
/* No command-specific prep needed */
pass = AT_PASS_MISC;
break;
default: /* oops */
elog(ERROR, "unrecognized alter table type: %d",
(int) cmd->subtype);
pass = AT_PASS_UNSET; /* keep compiler quiet */
break;
}
Assert(pass > AT_PASS_UNSET);
/* Add the subcommand to the appropriate list for phase 2 */
tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
}
/*
* ATRewriteCatalogs
*
* Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
* dispatched in a "safe" execution order (designed to avoid unnecessary
* conflicts).
*/
static void
ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
{
int pass;
ListCell *ltab;
/*
* We process all the tables "in parallel", one pass at a time. This is
* needed because we may have to propagate work from one table to another
* (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
* re-adding of the foreign key constraint to the other table). Work can
* only be propagated into later passes, however.
*/
for (pass = 0; pass < AT_NUM_PASSES; pass++)
{
/* Go through each table that needs to be processed */
foreach(ltab, *wqueue)
{
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
List *subcmds = tab->subcmds[pass];
Relation rel;
ListCell *lcmd;
if (subcmds == NIL)
continue;
/*
* Appropriate lock was obtained by phase 1, needn't get it again
*/
rel = relation_open(tab->relid, NoLock);
foreach(lcmd, subcmds)
ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
/*
* After the ALTER TYPE pass, do cleanup work (this is not done in
* ATExecAlterColumnType since it should be done only once if
* multiple columns of a table are altered).
*/
if (pass == AT_PASS_ALTER_TYPE)
ATPostAlterTypeCleanup(wqueue, tab, lockmode);
relation_close(rel, NoLock);
}
}
/* Check to see if a toast table must be added. */
foreach(ltab, *wqueue)
{
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
if (tab->relkind == RELKIND_RELATION ||
tab->relkind == RELKIND_MATVIEW)
AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
}
}
/*
* ATExecCmd: dispatch a subcommand to appropriate execution routine
*/
static void
ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
AlterTableCmd *cmd, LOCKMODE lockmode)
{
ObjectAddress address = InvalidObjectAddress;
switch (cmd->subtype)
{
case AT_AddColumn: /* ADD COLUMN */
case AT_AddColumnToView: /* add column via CREATE OR REPLACE
* VIEW */
address = ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
false, false, false, lockmode);
break;
case AT_AddColumnRecurse:
address = ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
false, true, false, lockmode);
break;
case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
break;
case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
address = ATExecDropNotNull(rel, cmd->name, lockmode);
break;
case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
address = ATExecSetNotNull(tab, rel, cmd->name, lockmode);
break;
case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
address = ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
break;
case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
break;
case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
break;
case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
break;
case AT_DropColumn: /* DROP COLUMN */
address = ATExecDropColumn(wqueue, rel, cmd->name,
cmd->behavior, false, false,
cmd->missing_ok, lockmode);
break;
case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
address = ATExecDropColumn(wqueue, rel, cmd->name,
cmd->behavior, true, false,
cmd->missing_ok, lockmode);
break;
case AT_AddIndex: /* ADD INDEX */
address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
lockmode);
break;
case AT_ReAddIndex: /* ADD INDEX */
address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
lockmode);
break;
case AT_AddConstraint: /* ADD CONSTRAINT */
address =
ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
false, false, lockmode);
break;
case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
address =
ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
true, false, lockmode);
break;
case AT_ReAddConstraint: /* Re-add pre-existing check
* constraint */
address =
ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
true, true, lockmode);
break;
case AT_ReAddComment: /* Re-add existing comment */
address = CommentObject((CommentStmt *) cmd->def);
break;
case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
lockmode);
break;
case AT_AlterConstraint: /* ALTER CONSTRAINT */
address = ATExecAlterConstraint(rel, cmd, false, false, lockmode);
break;
case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
address = ATExecValidateConstraint(rel, cmd->name, false, false,
lockmode);
break;
case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
* recursion */
address = ATExecValidateConstraint(rel, cmd->name, true, false,
lockmode);
break;
case AT_DropConstraint: /* DROP CONSTRAINT */
ATExecDropConstraint(rel, cmd->name, cmd->behavior,
false, false,
cmd->missing_ok, lockmode);
break;
case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
ATExecDropConstraint(rel, cmd->name, cmd->behavior,
true, false,
cmd->missing_ok, lockmode);
break;
case AT_AlterColumnType: /* ALTER COLUMN TYPE */
address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
break;
case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
address =
ATExecAlterColumnGenericOptions(rel, cmd->name,
(List *) cmd->def, lockmode);
break;
case AT_ChangeOwner: /* ALTER OWNER */
ATExecChangeOwner(RelationGetRelid(rel),
get_rolespec_oid(cmd->newowner, false),
false, lockmode);
break;
case AT_ClusterOn: /* CLUSTER ON */
address = ATExecClusterOn(rel, cmd->name, lockmode);
break;
case AT_DropCluster: /* SET WITHOUT CLUSTER */
ATExecDropCluster(rel, lockmode);
break;
case AT_SetLogged: /* SET LOGGED */
case AT_SetUnLogged: /* SET UNLOGGED */
break;
case AT_AddOids: /* SET WITH OIDS */
/* Use the ADD COLUMN code, unless prep decided to do nothing */
if (cmd->def != NULL)
address =
ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
true, false, false, lockmode);
break;
case AT_AddOidsRecurse: /* SET WITH OIDS */
/* Use the ADD COLUMN code, unless prep decided to do nothing */
if (cmd->def != NULL)
address =
ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
true, true, false, lockmode);
break;
case AT_DropOids: /* SET WITHOUT OIDS */
/*
* Nothing to do here; we'll have generated a DropColumn
* subcommand to do the real work
*/
break;
case AT_SetTableSpace: /* SET TABLESPACE */
/*
* Nothing to do here; Phase 3 does the work
*/
break;
case AT_SetRelOptions: /* SET (...) */
case AT_ResetRelOptions: /* RESET (...) */
case AT_ReplaceRelOptions: /* replace entire option list */
ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
break;
case AT_EnableTrig: /* ENABLE TRIGGER name */
ATExecEnableDisableTrigger(rel, cmd->name,
TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
break;
case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
ATExecEnableDisableTrigger(rel, cmd->name,
TRIGGER_FIRES_ALWAYS, false, lockmode);
break;
case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
ATExecEnableDisableTrigger(rel, cmd->name,
TRIGGER_FIRES_ON_REPLICA, false, lockmode);
break;
case AT_DisableTrig: /* DISABLE TRIGGER name */
ATExecEnableDisableTrigger(rel, cmd->name,
TRIGGER_DISABLED, false, lockmode);
break;
case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
ATExecEnableDisableTrigger(rel, NULL,
TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
break;
case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
ATExecEnableDisableTrigger(rel, NULL,
TRIGGER_DISABLED, false, lockmode);
break;
case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
ATExecEnableDisableTrigger(rel, NULL,
TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
break;
case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
ATExecEnableDisableTrigger(rel, NULL,
TRIGGER_DISABLED, true, lockmode);
break;
case AT_EnableRule: /* ENABLE RULE name */
ATExecEnableDisableRule(rel, cmd->name,
RULE_FIRES_ON_ORIGIN, lockmode);
break;
case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
ATExecEnableDisableRule(rel, cmd->name,
RULE_FIRES_ALWAYS, lockmode);
break;
case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
ATExecEnableDisableRule(rel, cmd->name,
RULE_FIRES_ON_REPLICA, lockmode);
break;
case AT_DisableRule: /* DISABLE RULE name */
ATExecEnableDisableRule(rel, cmd->name,
RULE_DISABLED, lockmode);
break;
case AT_AddInherit:
address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
break;
case AT_DropInherit:
address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
break;
case AT_AddOf:
address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
break;
case AT_DropOf:
ATExecDropOf(rel, lockmode);
break;
case AT_ReplicaIdentity:
ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
break;
case AT_EnableRowSecurity:
ATExecEnableRowSecurity(rel);
break;
case AT_DisableRowSecurity:
ATExecDisableRowSecurity(rel);
break;
case AT_ForceRowSecurity:
ATExecForceNoForceRowSecurity(rel, true);
break;
case AT_NoForceRowSecurity:
ATExecForceNoForceRowSecurity(rel, false);
break;
case AT_GenericOptions:
ATExecGenericOptions(rel, (List *) cmd->def);
break;
default: /* oops */
elog(ERROR, "unrecognized alter table type: %d",
(int) cmd->subtype);
break;
}
/*
* Report the subcommand to interested event triggers.
*/
EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
/*
* Bump the command counter to ensure the next subcommand in the sequence
* can see the changes so far
*/
CommandCounterIncrement();
}
/*
* ATRewriteTables: ALTER TABLE phase 3
*/
static void
ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
{
ListCell *ltab;
/* Go through each table that needs to be checked or rewritten */
foreach(ltab, *wqueue)
{
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
/* Foreign tables have no storage. */
if (tab->relkind == RELKIND_FOREIGN_TABLE)
continue;
/*
* If we change column data types or add/remove OIDs, the operation
* has to be propagated to tables that use this table's rowtype as a
* column type. tab->newvals will also be non-NULL in the case where
* we're adding a column with a default. We choose to forbid that
* case as well, since composite types might eventually support
* defaults.
*
* (Eventually we'll probably need to check for composite type
* dependencies even when we're just scanning the table without a
* rewrite, but at the moment a composite type does not enforce any
* constraints, so it's not necessary/appropriate to enforce them just
* during ALTER.)
*/
if (tab->newvals != NIL || tab->rewrite > 0)
{
Relation rel;
rel = heap_open(tab->relid, NoLock);
find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
heap_close(rel, NoLock);
}
/*
* We only need to rewrite the table if at least one column needs to
* be recomputed, we are adding/removing the OID column, or we are
* changing its persistence.
*
* There are two reasons for requiring a rewrite when changing
* persistence: on one hand, we need to ensure that the buffers
* belonging to each of the two relations are marked with or without
* BM_PERMANENT properly. On the other hand, since rewriting creates
* and assigns a new relfilenode, we automatically create or drop an
* init fork for the relation as appropriate.
*/
if (tab->rewrite > 0)
{
/* Build a temporary relation and copy data */
Relation OldHeap;
Oid OIDNewHeap;
Oid NewTableSpace;
char persistence;
OldHeap = heap_open(tab->relid, NoLock);
/*
* We don't support rewriting of system catalogs; there are too
* many corner cases and too little benefit. In particular this
* is certainly not going to work for mapped catalogs.
*/
if (IsSystemRelation(OldHeap))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot rewrite system relation \"%s\"",
RelationGetRelationName(OldHeap))));
if (RelationIsUsedAsCatalogTable(OldHeap))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot rewrite table \"%s\" used as a catalog table",
RelationGetRelationName(OldHeap))));
/*
* Don't allow rewrite on temp tables of other backends ... their
* local buffer manager is not going to cope.
*/
if (RELATION_IS_OTHER_TEMP(OldHeap))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot rewrite temporary tables of other sessions")));
/*
* Select destination tablespace (same as original unless user
* requested a change)
*/
if (tab->newTableSpace)
NewTableSpace = tab->newTableSpace;
else
NewTableSpace = OldHeap->rd_rel->reltablespace;
/*
* Select persistence of transient table (same as original unless
* user requested a change)
*/
persistence = tab->chgPersistence ?
tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
heap_close(OldHeap, NoLock);
/*
* Fire off an Event Trigger now, before actually rewriting the
* table.
*
* We don't support Event Trigger for nested commands anywhere,
* here included, and parsetree is given NULL when coming from
* AlterTableInternal.
*
* And fire it only once.
*/
if (parsetree)
EventTriggerTableRewrite((Node *) parsetree,
tab->relid,
tab->rewrite);
/*
* Create transient table that will receive the modified data.
*
* Ensure it is marked correctly as logged or unlogged. We have
* to do this here so that buffers for the new relfilenode will
* have the right persistence set, and at the same time ensure
* that the original filenode's buffers will get read in with the
* correct setting (i.e. the original one). Otherwise a rollback
* after the rewrite would possibly result with buffers for the
* original filenode having the wrong persistence setting.
*
* NB: This relies on swap_relation_files() also swapping the
* persistence. That wouldn't work for pg_class, but that can't be
* unlogged anyway.
*/
OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, persistence,
lockmode);
/*
* Copy the heap data into the new table with the desired
* modifications, and test the current data within the table
* against new constraints generated by ALTER TABLE commands.
*/
ATRewriteTable(tab, OIDNewHeap, lockmode);
/*
* Swap the physical files of the old and new heaps, then rebuild
* indexes and discard the old heap. We can use RecentXmin for
* the table's new relfrozenxid because we rewrote all the tuples
* in ATRewriteTable, so no older Xid remains in the table. Also,
* we never try to swap toast tables by content, since we have no
* interest in letting this code work on system catalogs.
*/
finish_heap_swap(tab->relid, OIDNewHeap,
false, false, true,
!OidIsValid(tab->newTableSpace),
RecentXmin,
ReadNextMultiXactId(),
persistence);
}
else
{
/*
* Test the current data within the table against new constraints
* generated by ALTER TABLE commands, but don't rebuild data.
*/
if (tab->constraints != NIL || tab->new_notnull)
ATRewriteTable(tab, InvalidOid, lockmode);
/*
* If we had SET TABLESPACE but no reason to reconstruct tuples,
* just do a block-by-block copy.
*/
if (tab->newTableSpace)
ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
}
}
/*
* Foreign key constraints are checked in a final pass, since (a) it's
* generally best to examine each one separately, and (b) it's at least
* theoretically possible that we have changed both relations of the
* foreign key, and we'd better have finished both rewrites before we try
* to read the tables.
*/
foreach(ltab, *wqueue)
{
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
Relation rel = NULL;
ListCell *lcon;
foreach(lcon, tab->constraints)
{
NewConstraint *con = lfirst(lcon);
if (con->contype == CONSTR_FOREIGN)
{
Constraint *fkconstraint = (Constraint *) con->qual;
Relation refrel;
if (rel == NULL)
{
/* Long since locked, no need for another */
rel = heap_open(tab->relid, NoLock);
}
refrel = heap_open(con->refrelid, RowShareLock);
validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
con->refindid,
con->conid);
/*
* No need to mark the constraint row as validated, we did
* that when we inserted the row earlier.
*/
heap_close(refrel, NoLock);
}
}
if (rel)
heap_close(rel, NoLock);
}
}
/*
* ATRewriteTable: scan or rewrite one table
*
* OIDNewHeap is InvalidOid if we don't need to rewrite
*/
static void
ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
{
Relation oldrel;
Relation newrel;
TupleDesc oldTupDesc;
TupleDesc newTupDesc;
bool needscan = false;
List *notnull_attrs;
int i;
ListCell *l;
EState *estate;
CommandId mycid;
BulkInsertState bistate;
int hi_options;
/*
* Open the relation(s). We have surely already locked the existing
* table.
*/
oldrel = heap_open(tab->relid, NoLock);
oldTupDesc = tab->oldDesc;
newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
if (OidIsValid(OIDNewHeap))
newrel = heap_open(OIDNewHeap, lockmode);
else
newrel = NULL;
/*
* Prepare a BulkInsertState and options for heap_insert. Because we're
* building a new heap, we can skip WAL-logging and fsync it to disk at
* the end instead (unless WAL-logging is required for archiving or
* streaming replication). The FSM is empty too, so don't bother using it.
*/
if (newrel)
{
mycid = GetCurrentCommandId(true);
bistate = GetBulkInsertState();
hi_options = HEAP_INSERT_SKIP_FSM;
if (!XLogIsNeeded())
hi_options |= HEAP_INSERT_SKIP_WAL;
}
else
{
/* keep compiler quiet about using these uninitialized */
mycid = 0;
bistate = NULL;
hi_options = 0;
}
/*
* Generate the constraint and default execution states
*/
estate = CreateExecutorState();
/* Build the needed expression execution states */
foreach(l, tab->constraints)
{
NewConstraint *con = lfirst(l);
switch (con->contype)
{
case CONSTR_CHECK:
needscan = true;
con->qualstate = (List *)
ExecPrepareExpr((Expr *) con->qual, estate);
break;
case CONSTR_FOREIGN:
/* Nothing to do here */
break;
default:
elog(ERROR, "unrecognized constraint type: %d",
(int) con->contype);
}
}
foreach(l, tab->newvals)
{
NewColumnValue *ex = lfirst(l);
/* expr already planned */
ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
}
notnull_attrs = NIL;
if (newrel || tab->new_notnull)
{
/*
* If we are rebuilding the tuples OR if we added any new NOT NULL
* constraints, check all not-null constraints. This is a bit of
* overkill but it minimizes risk of bugs, and heap_attisnull is a
* pretty cheap test anyway.
*/
for (i = 0; i < newTupDesc->natts; i++)
{
if (newTupDesc->attrs[i]->attnotnull &&
!newTupDesc->attrs[i]->attisdropped)
notnull_attrs = lappend_int(notnull_attrs, i);
}
if (notnull_attrs)
needscan = true;
}
if (newrel || needscan)
{
ExprContext *econtext;
Datum *values;
bool *isnull;
TupleTableSlot *oldslot;
TupleTableSlot *newslot;
HeapScanDesc scan;
HeapTuple tuple;
MemoryContext oldCxt;
List *dropped_attrs = NIL;
ListCell *lc;
Snapshot snapshot;
if (newrel)
ereport(DEBUG1,
(errmsg("rewriting table \"%s\"",
RelationGetRelationName(oldrel))));
else
ereport(DEBUG1,
(errmsg("verifying table \"%s\"",
RelationGetRelationName(oldrel))));
if (newrel)
{
/*
* All predicate locks on the tuples or pages are about to be made
* invalid, because we move tuples around. Promote them to
* relation locks.
*/
TransferPredicateLocksToHeapRelation(oldrel);
}
econtext = GetPerTupleExprContext(estate);
/*
* Make tuple slots for old and new tuples. Note that even when the
* tuples are the same, the tupDescs might not be (consider ADD COLUMN
* without a default).
*/
oldslot = MakeSingleTupleTableSlot(oldTupDesc);
newslot = MakeSingleTupleTableSlot(newTupDesc);
/* Preallocate values/isnull arrays */
i = Max(newTupDesc->natts, oldTupDesc->natts);
values = (Datum *) palloc(i * sizeof(Datum));
isnull = (bool *) palloc(i * sizeof(bool));
memset(values, 0, i * sizeof(Datum));
memset(isnull, true, i * sizeof(bool));
/*
* Any attributes that are dropped according to the new tuple
* descriptor can be set to NULL. We precompute the list of dropped
* attributes to avoid needing to do so in the per-tuple loop.
*/
for (i = 0; i < newTupDesc->natts; i++)
{
if (newTupDesc->attrs[i]->attisdropped)
dropped_attrs = lappend_int(dropped_attrs, i);
}
/*
* Scan through the rows, generating a new row if needed and then
* checking all the constraints.
*/
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(oldrel, snapshot, 0, NULL);
/*
* Switch to per-tuple memory context and reset it for each tuple
* produced, so we don't leak memory.
*/
oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
if (tab->rewrite > 0)
{
Oid tupOid = InvalidOid;
/* Extract data from old tuple */
heap_deform_tuple(tuple, oldTupDesc, values, isnull);
if (oldTupDesc->tdhasoid)
tupOid = HeapTupleGetOid(tuple);
/* Set dropped attributes to null in new tuple */
foreach(lc, dropped_attrs)
isnull[lfirst_int(lc)] = true;
/*
* Process supplied expressions to replace selected columns.
* Expression inputs come from the old tuple.
*/
ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
econtext->ecxt_scantuple = oldslot;
foreach(l, tab->newvals)
{
NewColumnValue *ex = lfirst(l);
values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
econtext,
&isnull[ex->attnum - 1],
NULL);
}
/*
* Form the new tuple. Note that we don't explicitly pfree it,
* since the per-tuple memory context will be reset shortly.
*/
tuple = heap_form_tuple(newTupDesc, values, isnull);
/* Preserve OID, if any */
if (newTupDesc->tdhasoid)
HeapTupleSetOid(tuple, tupOid);
/*
* Constraints might reference the tableoid column, so
* initialize t_tableOid before evaluating them.
*/
tuple->t_tableOid = RelationGetRelid(oldrel);
}
/* Now check any constraints on the possibly-changed tuple */
ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
econtext->ecxt_scantuple = newslot;
foreach(l, notnull_attrs)
{
int attn = lfirst_int(l);
if (heap_attisnull(tuple, attn + 1))
ereport(ERROR,
(errcode(ERRCODE_NOT_NULL_VIOLATION),
errmsg("column \"%s\" contains null values",
NameStr(newTupDesc->attrs[attn]->attname)),
errtablecol(oldrel, attn + 1)));
}
foreach(l, tab->constraints)
{
NewConstraint *con = lfirst(l);
switch (con->contype)
{
case CONSTR_CHECK:
if (!ExecQual(con->qualstate, econtext, true))
ereport(ERROR,
(errcode(ERRCODE_CHECK_VIOLATION),
errmsg("check constraint \"%s\" is violated by some row",
con->name),
errtableconstraint(oldrel, con->name)));
break;
case CONSTR_FOREIGN:
/* Nothing to do here */
break;
default:
elog(ERROR, "unrecognized constraint type: %d",
(int) con->contype);
}
}
/* Write the tuple out to the new relation */
if (newrel)
heap_insert(newrel, tuple, mycid, hi_options, bistate);
ResetExprContext(econtext);
CHECK_FOR_INTERRUPTS();
}
MemoryContextSwitchTo(oldCxt);
heap_endscan(scan);
UnregisterSnapshot(snapshot);
ExecDropSingleTupleTableSlot(oldslot);
ExecDropSingleTupleTableSlot(newslot);
}
FreeExecutorState(estate);
heap_close(oldrel, NoLock);
if (newrel)
{
FreeBulkInsertState(bistate);
/* If we skipped writing WAL, then we need to sync the heap. */
if (hi_options & HEAP_INSERT_SKIP_WAL)
heap_sync(newrel);
heap_close(newrel, NoLock);
}
}
/*
* ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
*/
static AlteredTableInfo *
ATGetQueueEntry(List **wqueue, Relation rel)
{
Oid relid = RelationGetRelid(rel);
AlteredTableInfo *tab;
ListCell *ltab;
foreach(ltab, *wqueue)
{
tab = (AlteredTableInfo *) lfirst(ltab);
if (tab->relid == relid)
return tab;
}
/*
* Not there, so add it. Note that we make a copy of the relation's
* existing descriptor before anything interesting can happen to it.
*/
tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
tab->relid = relid;
tab->relkind = rel->rd_rel->relkind;
tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
tab->chgPersistence = false;
*wqueue = lappend(*wqueue, tab);
return tab;
}
/*
* ATSimplePermissions
*
* - Ensure that it is a relation (or possibly a view)
* - Ensure this user is the owner
* - Ensure that it is not a system table
*/
static void
ATSimplePermissions(Relation rel, int allowed_targets)
{
int actual_target;
switch (rel->rd_rel->relkind)
{
case RELKIND_RELATION:
actual_target = ATT_TABLE;
break;
case RELKIND_VIEW:
actual_target = ATT_VIEW;
break;
case RELKIND_MATVIEW:
actual_target = ATT_MATVIEW;
break;
case RELKIND_INDEX:
actual_target = ATT_INDEX;
break;
case RELKIND_COMPOSITE_TYPE:
actual_target = ATT_COMPOSITE_TYPE;
break;
case RELKIND_FOREIGN_TABLE:
actual_target = ATT_FOREIGN_TABLE;
break;
default:
actual_target = 0;
break;
}
/* Wrong target type? */
if ((actual_target & allowed_targets) == 0)
ATWrongRelkindError(rel, allowed_targets);
/* Permissions checks */
if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(rel));
if (!allowSystemTableMods && IsSystemRelation(rel))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
RelationGetRelationName(rel))));
}
/*
* ATWrongRelkindError
*
* Throw an error when a relation has been determined to be of the wrong
* type.
*/
static void
ATWrongRelkindError(Relation rel, int allowed_targets)
{
char *msg;
switch (allowed_targets)
{
case ATT_TABLE:
msg = _("\"%s\" is not a table");
break;
case ATT_TABLE | ATT_VIEW:
msg = _("\"%s\" is not a table or view");
break;
case ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a table, view, or foreign table");
break;
case ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX:
msg = _("\"%s\" is not a table, view, materialized view, or index");
break;
case ATT_TABLE | ATT_MATVIEW:
msg = _("\"%s\" is not a table or materialized view");
break;
case ATT_TABLE | ATT_MATVIEW | ATT_INDEX:
msg = _("\"%s\" is not a table, materialized view, or index");
break;
case ATT_TABLE | ATT_MATVIEW | ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a table, materialized view, or foreign table");
break;
case ATT_TABLE | ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a table or foreign table");
break;
case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a table, composite type, or foreign table");
break;
case ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a table, materialized view, index, or foreign table");
break;
case ATT_VIEW:
msg = _("\"%s\" is not a view");
break;
case ATT_FOREIGN_TABLE:
msg = _("\"%s\" is not a foreign table");
break;
default:
/* shouldn't get here, add all necessary cases above */
msg = _("\"%s\" is of the wrong type");
break;
}
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg(msg, RelationGetRelationName(rel))));
}
/*
* ATSimpleRecursion
*
* Simple table recursion sufficient for most ALTER TABLE operations.
* All direct and indirect children are processed in an unspecified order.
* Note that if a child inherits from the original table via multiple
* inheritance paths, it will be visited just once.
*/
static void
ATSimpleRecursion(List **wqueue, Relation rel,
AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
{
/*
* Propagate to children if desired. Only plain tables and foreign tables
* have children, so no need to search for other relkinds.
*/
if (recurse &&
(rel->rd_rel->relkind == RELKIND_RELATION ||
rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE))
{
Oid relid = RelationGetRelid(rel);
ListCell *child;
List *children;
children = find_all_inheritors(relid, lockmode, NULL);
/*
* find_all_inheritors does the recursive search of the inheritance
* hierarchy, so all we have to do is process all of the relids in the
* list that it returns.
*/
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
if (childrelid == relid)
continue;
/* find_all_inheritors already got lock */
childrel = relation_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
relation_close(childrel, NoLock);
}
}
}
/*
* ATTypedTableRecursion
*
* Propagate ALTER TYPE operations to the typed tables of that type.
* Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
* recursion to inheritance children of the typed tables.
*/
static void
ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
LOCKMODE lockmode)
{
ListCell *child;
List *children;
Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
children = find_typed_table_dependencies(rel->rd_rel->reltype,
RelationGetRelationName(rel),
cmd->behavior);
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
childrel = relation_open(childrelid, lockmode);
CheckTableNotInUse(childrel, "ALTER TABLE");
ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
relation_close(childrel, NoLock);
}
}
/*
* find_composite_type_dependencies
*
* Check to see if the type "typeOid" is being used as a column in some table
* (possibly nested several levels deep in composite types, arrays, etc!).
* Eventually, we'd like to propagate the check or rewrite operation
* into such tables, but for now, just error out if we find any.
*
* Caller should provide either the associated relation of a rowtype,
* or a type name (not both) for use in the error message, if any.
*
* Note that "typeOid" is not necessarily a composite type; it could also be
* another container type such as an array or range, or a domain over one of
* these things. The name of this function is therefore somewhat historical,
* but it's not worth changing.
*
* We assume that functions and views depending on the type are not reasons
* to reject the ALTER. (How safe is this really?)
*/
void
find_composite_type_dependencies(Oid typeOid, Relation origRelation,
const char *origTypeName)
{
Relation depRel;
ScanKeyData key[2];
SysScanDesc depScan;
HeapTuple depTup;
/* since this function recurses, it could be driven to stack overflow */
check_stack_depth();
/*
* We scan pg_depend to find those things that depend on the given type.
* (We assume we can ignore refobjsubid for a type.)
*/
depRel = heap_open(DependRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(TypeRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(typeOid));
depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
NULL, 2, key);
while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
{
Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
Relation rel;
Form_pg_attribute att;
/* Check for directly dependent types */
if (pg_depend->classid == TypeRelationId)
{
/*
* This must be an array, domain, or range containing the given
* type, so recursively check for uses of this type. Note that
* any error message will mention the original type not the
* container; this is intentional.
*/
find_composite_type_dependencies(pg_depend->objid,
origRelation, origTypeName);
continue;
}
/* Else, ignore dependees that aren't user columns of relations */
/* (we assume system columns are never of interesting types) */
if (pg_depend->classid != RelationRelationId ||
pg_depend->objsubid <= 0)
continue;
rel = relation_open(pg_depend->objid, AccessShareLock);
att = rel->rd_att->attrs[pg_depend->objsubid - 1];
if (rel->rd_rel->relkind == RELKIND_RELATION ||
rel->rd_rel->relkind == RELKIND_MATVIEW)
{
if (origTypeName)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
origTypeName,
RelationGetRelationName(rel),
NameStr(att->attname))));
else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
RelationGetRelationName(origRelation),
RelationGetRelationName(rel),
NameStr(att->attname))));
else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
RelationGetRelationName(origRelation),
RelationGetRelationName(rel),
NameStr(att->attname))));
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
RelationGetRelationName(origRelation),
RelationGetRelationName(rel),
NameStr(att->attname))));
}
else if (OidIsValid(rel->rd_rel->reltype))
{
/*
* A view or composite type itself isn't a problem, but we must
* recursively check for indirect dependencies via its rowtype.
*/
find_composite_type_dependencies(rel->rd_rel->reltype,
origRelation, origTypeName);
}
relation_close(rel, AccessShareLock);
}
systable_endscan(depScan);
relation_close(depRel, AccessShareLock);
}
/*
* find_typed_table_dependencies
*
* Check to see if a composite type is being used as the type of a
* typed table. Abort if any are found and behavior is RESTRICT.
* Else return the list of tables.
*/
static List *
find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
{
Relation classRel;
ScanKeyData key[1];
HeapScanDesc scan;
HeapTuple tuple;
List *result = NIL;
classRel = heap_open(RelationRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_class_reloftype,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(typeOid));
scan = heap_beginscan_catalog(classRel, 1, key);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
if (behavior == DROP_RESTRICT)
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("cannot alter type \"%s\" because it is the type of a typed table",
typeName),
errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
else
result = lappend_oid(result, HeapTupleGetOid(tuple));
}
heap_endscan(scan);
heap_close(classRel, AccessShareLock);
return result;
}
/*
* check_of_type
*
* Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
* isn't suitable, throw an error. Currently, we require that the type
* originated with CREATE TYPE AS. We could support any row type, but doing so
* would require handling a number of extra corner cases in the DDL commands.
*/
void
check_of_type(HeapTuple typetuple)
{
Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
bool typeOk = false;
if (typ->typtype == TYPTYPE_COMPOSITE)
{
Relation typeRelation;
Assert(OidIsValid(typ->typrelid));
typeRelation = relation_open(typ->typrelid, AccessShareLock);
typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
/*
* Close the parent rel, but keep our AccessShareLock on it until xact
* commit. That will prevent someone else from deleting or ALTERing
* the type before the typed table creation/conversion commits.
*/
relation_close(typeRelation, NoLock);
}
if (!typeOk)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("type %s is not a composite type",
format_type_be(HeapTupleGetOid(typetuple)))));
}
/*
* ALTER TABLE ADD COLUMN
*
* Adds an additional attribute to a relation making the assumption that
* CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
* AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
* AlterTableCmd's.
*
* ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
* have to decide at runtime whether to recurse or not depending on whether we
* actually add a column or merely merge with an existing column. (We can't
* check this in a static pre-pass because it won't handle multiple inheritance
* situations correctly.)
*/
static void
ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
{
if (rel->rd_rel->reloftype && !recursing)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot add column to typed table")));
if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
if (recurse && !is_view)
cmd->subtype = AT_AddColumnRecurse;
}
/*
* Add a column to a table; this handles the AT_AddOids cases as well. The
* return value is the address of the new column in the parent relation.
*/
static ObjectAddress
ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
ColumnDef *colDef, bool isOid,
bool recurse, bool recursing, LOCKMODE lockmode)
{
Oid myrelid = RelationGetRelid(rel);
Relation pgclass,
attrdesc;
HeapTuple reltup;
FormData_pg_attribute attribute;
int newattnum;
char relkind;
HeapTuple typeTuple;
Oid typeOid;
int32 typmod;
Oid collOid;
Form_pg_type tform;
Expr *defval;
List *children;
ListCell *child;
AclResult aclresult;
ObjectAddress address;
/* At top level, permission check was done in ATPrepCmd, else do it */
if (recursing)
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
/*
* Are we adding the column to a recursion child? If so, check whether to
* merge with an existing definition for the column. If we do merge, we
* must not recurse. Children will already have the column, and recursing
* into them would mess up attinhcount.
*/
if (colDef->inhcount > 0)
{
HeapTuple tuple;
/* Does child already have a column by this name? */
tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
if (HeapTupleIsValid(tuple))
{
Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
Oid ctypeId;
int32 ctypmod;
Oid ccollid;
/* Child column must match on type, typmod, and collation */
typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
if (ctypeId != childatt->atttypid ||
ctypmod != childatt->atttypmod)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table \"%s\" has different type for column \"%s\"",
RelationGetRelationName(rel), colDef->colname)));
ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
if (ccollid != childatt->attcollation)
ereport(ERROR,
(errcode(ERRCODE_COLLATION_MISMATCH),
errmsg("child table \"%s\" has different collation for column \"%s\"",
RelationGetRelationName(rel), colDef->colname),
errdetail("\"%s\" versus \"%s\"",
get_collation_name(ccollid),
get_collation_name(childatt->attcollation))));
/* If it's OID, child column must actually be OID */
if (isOid && childatt->attnum != ObjectIdAttributeNumber)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table \"%s\" has a conflicting \"%s\" column",
RelationGetRelationName(rel), colDef->colname)));
/* Bump the existing child att's inhcount */
childatt->attinhcount++;
simple_heap_update(attrdesc, &tuple->t_self, tuple);
CatalogUpdateIndexes(attrdesc, tuple);
heap_freetuple(tuple);
/* Inform the user about the merge */
ereport(NOTICE,
(errmsg("merging definition of column \"%s\" for child \"%s\"",
colDef->colname, RelationGetRelationName(rel))));
heap_close(attrdesc, RowExclusiveLock);
return InvalidObjectAddress;
}
}
pgclass = heap_open(RelationRelationId, RowExclusiveLock);
reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
if (!HeapTupleIsValid(reltup))
elog(ERROR, "cache lookup failed for relation %u", myrelid);
relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
/* new name should not already exist */
check_for_column_name_collision(rel, colDef->colname);
/* Determine the new attribute's number */
if (isOid)
newattnum = ObjectIdAttributeNumber;
else
{
newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
if (newattnum > MaxHeapAttributeNumber)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("tables can have at most %d columns",
MaxHeapAttributeNumber)));
}
typeTuple = typenameType(NULL, colDef->typeName, &typmod);
tform = (Form_pg_type) GETSTRUCT(typeTuple);
typeOid = HeapTupleGetOid(typeTuple);
aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
if (aclresult != ACLCHECK_OK)
aclcheck_error_type(aclresult, typeOid);
collOid = GetColumnDefCollation(NULL, colDef, typeOid);
/* make sure datatype is legal for a column */
CheckAttributeType(colDef->colname, typeOid, collOid,
list_make1_oid(rel->rd_rel->reltype),
false);
/* construct new attribute's pg_attribute entry */
attribute.attrelid = myrelid;
namestrcpy(&(attribute.attname), colDef->colname);
attribute.atttypid = typeOid;
attribute.attstattarget = (newattnum > 0) ? -1 : 0;
attribute.attlen = tform->typlen;
attribute.attcacheoff = -1;
attribute.atttypmod = typmod;
attribute.attnum = newattnum;
attribute.attbyval = tform->typbyval;
attribute.attndims = list_length(colDef->typeName->arrayBounds);
attribute.attstorage = tform->typstorage;
attribute.attalign = tform->typalign;
attribute.attnotnull = colDef->is_not_null;
attribute.atthasdef = false;
attribute.attisdropped = false;
attribute.attislocal = colDef->is_local;
attribute.attinhcount = colDef->inhcount;
attribute.attcollation = collOid;
/* attribute.attacl is handled by InsertPgAttributeTuple */
ReleaseSysCache(typeTuple);
InsertPgAttributeTuple(attrdesc, &attribute, NULL);
heap_close(attrdesc, RowExclusiveLock);
/*
* Update pg_class tuple as appropriate
*/
if (isOid)
((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
else
((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
simple_heap_update(pgclass, &reltup->t_self, reltup);
/* keep catalog indexes current */
CatalogUpdateIndexes(pgclass, reltup);
heap_freetuple(reltup);
/* Post creation hook for new attribute */
InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
heap_close(pgclass, RowExclusiveLock);
/* Make the attribute's catalog entry visible */
CommandCounterIncrement();
/*
* Store the DEFAULT, if any, in the catalogs
*/
if (colDef->raw_default)
{
RawColumnDefault *rawEnt;
rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
rawEnt->attnum = attribute.attnum;
rawEnt->raw_default = copyObject(colDef->raw_default);
/*
* This function is intended for CREATE TABLE, so it processes a
* _list_ of defaults, but we just do one.
*/
AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
false, true, false);
/* Make the additional catalog changes visible */
CommandCounterIncrement();
}
/*
* Tell Phase 3 to fill in the default expression, if there is one.
*
* If there is no default, Phase 3 doesn't have to do anything, because
* that effectively means that the default is NULL. The heap tuple access
* routines always check for attnum > # of attributes in tuple, and return
* NULL if so, so without any modification of the tuple data we will get
* the effect of NULL values in the new column.
*
* An exception occurs when the new column is of a domain type: the domain
* might have a NOT NULL constraint, or a check constraint that indirectly
* rejects nulls. If there are any domain constraints then we construct
* an explicit NULL default value that will be passed through
* CoerceToDomain processing. (This is a tad inefficient, since it causes
* rewriting the table which we really don't have to do, but the present
* design of domain processing doesn't offer any simple way of checking
* the constraints more directly.)
*
* Note: we use build_column_default, and not just the cooked default
* returned by AddRelationNewConstraints, so that the right thing happens
* when a datatype's default applies.
*
* We skip this step completely for views and foreign tables. For a view,
* we can only get here from CREATE OR REPLACE VIEW, which historically
* doesn't set up defaults, not even for domain-typed columns. And in any
* case we mustn't invoke Phase 3 on a view or foreign table, since they
* have no storage.
*/
if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
&& relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
{
defval = (Expr *) build_column_default(rel, attribute.attnum);
if (!defval && DomainHasConstraints(typeOid))
{
Oid baseTypeId;
int32 baseTypeMod;
Oid baseTypeColl;
baseTypeMod = typmod;
baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
baseTypeColl = get_typcollation(baseTypeId);
defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
defval = (Expr *) coerce_to_target_type(NULL,
(Node *) defval,
baseTypeId,
typeOid,
typmod,
COERCION_ASSIGNMENT,
COERCE_IMPLICIT_CAST,
-1);
if (defval == NULL) /* should not happen */
elog(ERROR, "failed to coerce base type to domain");
}
if (defval)
{
NewColumnValue *newval;
newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
newval->attnum = attribute.attnum;
newval->expr = expression_planner(defval);
tab->newvals = lappend(tab->newvals, newval);
tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
}
/*
* If the new column is NOT NULL, tell Phase 3 it needs to test that.
* (Note we don't do this for an OID column. OID will be marked not
* null, but since it's filled specially, there's no need to test
* anything.)
*/
tab->new_notnull |= colDef->is_not_null;
}
/*
* If we are adding an OID column, we have to tell Phase 3 to rewrite the
* table to fix that.
*/
if (isOid)
tab->rewrite |= AT_REWRITE_ALTER_OID;
/*
* Add needed dependency entries for the new column.
*/
add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
/*
* Propagate to children as appropriate. Unlike most other ALTER
* routines, we have to do this one level of recursion at a time; we can't
* use find_all_inheritors to do it in one pass.
*/
children = find_inheritance_children(RelationGetRelid(rel), lockmode);
/*
* If we are told not to recurse, there had better not be any child
* tables; else the addition would put them out of step.
*/
if (children && !recurse)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("column must be added to child tables too")));
/* Children should see column as singly inherited */
if (!recursing)
{
colDef = copyObject(colDef);
colDef->inhcount = 1;
colDef->is_local = false;
}
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
AlteredTableInfo *childtab;
/* find_inheritance_children already got lock */
childrel = heap_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
/* Find or create work queue entry for this table */
childtab = ATGetQueueEntry(wqueue, childrel);
/* Recurse to child; return value is ignored */
ATExecAddColumn(wqueue, childtab, childrel,
colDef, isOid, recurse, true, lockmode);
heap_close(childrel, NoLock);
}
ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
return address;
}
/*
* If a new or renamed column will collide with the name of an existing
* column, error out.
*/
static void
check_for_column_name_collision(Relation rel, const char *colname)
{
HeapTuple attTuple;
int attnum;
/*
* this test is deliberately not attisdropped-aware, since if one tries to
* add a column matching a dropped column name, it's gonna fail anyway.
*/
attTuple = SearchSysCache2(ATTNAME,
ObjectIdGetDatum(RelationGetRelid(rel)),
PointerGetDatum(colname));
if (!HeapTupleIsValid(attTuple))
return;
attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
ReleaseSysCache(attTuple);
/*
* We throw a different error message for conflicts with system column
* names, since they are normally not shown and the user might otherwise
* be confused about the reason for the conflict.
*/
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column name \"%s\" conflicts with a system column name",
colname)));
else
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column \"%s\" of relation \"%s\" already exists",
colname, RelationGetRelationName(rel))));
}
/*
* Install a column's dependency on its datatype.
*/
static void
add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
{
ObjectAddress myself,
referenced;
myself.classId = RelationRelationId;
myself.objectId = relid;
myself.objectSubId = attnum;
referenced.classId = TypeRelationId;
referenced.objectId = typid;
referenced.objectSubId = 0;
recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
}
/*
* Install a column's dependency on its collation.
*/
static void
add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
{
ObjectAddress myself,
referenced;
/* We know the default collation is pinned, so don't bother recording it */
if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
{
myself.classId = RelationRelationId;
myself.objectId = relid;
myself.objectSubId = attnum;
referenced.classId = CollationRelationId;
referenced.objectId = collid;
referenced.objectSubId = 0;
recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
}
}
/*
* ALTER TABLE SET WITH OIDS
*
* Basically this is an ADD COLUMN for the special OID column. We have
* to cons up a ColumnDef node because the ADD COLUMN code needs one.
*/
static void
ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
{
/* If we're recursing to a child table, the ColumnDef is already set up */
if (cmd->def == NULL)
{
ColumnDef *cdef = makeNode(ColumnDef);
cdef->colname = pstrdup("oid");
cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
cdef->inhcount = 0;
cdef->is_local = true;
cdef->is_not_null = true;
cdef->storage = 0;
cdef->location = -1;
cmd->def = (Node *) cdef;
}
ATPrepAddColumn(wqueue, rel, recurse, false, false, cmd, lockmode);
if (recurse)
cmd->subtype = AT_AddOidsRecurse;
}
/*
* ALTER TABLE ALTER COLUMN DROP NOT NULL
*
* Return the address of the modified column. If the column was already
* nullable, InvalidObjectAddress is returned.
*/
static ObjectAddress
ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
{
HeapTuple tuple;
AttrNumber attnum;
Relation attr_rel;
List *indexoidlist;
ListCell *indexoidscan;
ObjectAddress address;
/*
* lookup the attribute
*/
attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
/* Prevent them from altering a system attribute */
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/*
* Check that the attribute is not in a primary key
*
* Note: we'll throw error even if the pkey index is not valid.
*/
/* Loop over all indexes on the relation */
indexoidlist = RelationGetIndexList(rel);
foreach(indexoidscan, indexoidlist)
{
Oid indexoid = lfirst_oid(indexoidscan);
HeapTuple indexTuple;
Form_pg_index indexStruct;
int i;
indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "cache lookup failed for index %u", indexoid);
indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
/* If the index is not a primary key, skip the check */
if (indexStruct->indisprimary)
{
/*
* Loop over each attribute in the primary key and see if it
* matches the to-be-altered attribute
*/
for (i = 0; i < indexStruct->indnatts; i++)
{
if (indexStruct->indkey.values[i] == attnum)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("column \"%s\" is in a primary key",
colName)));
}
}
ReleaseSysCache(indexTuple);
}
list_free(indexoidlist);
/*
* Okay, actually perform the catalog change ... if needed
*/
if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
{
((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
simple_heap_update(attr_rel, &tuple->t_self, tuple);
/* keep the system catalog indexes current */
CatalogUpdateIndexes(attr_rel, tuple);
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
}
else
address = InvalidObjectAddress;
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel), attnum);
heap_close(attr_rel, RowExclusiveLock);
return address;
}
/*
* ALTER TABLE ALTER COLUMN SET NOT NULL
*
* Return the address of the modified column. If the column was already NOT
* NULL, InvalidObjectAddress is returned.
*/
static ObjectAddress
ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
const char *colName, LOCKMODE lockmode)
{
HeapTuple tuple;
AttrNumber attnum;
Relation attr_rel;
ObjectAddress address;
/*
* lookup the attribute
*/
attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
/* Prevent them from altering a system attribute */
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/*
* Okay, actually perform the catalog change ... if needed
*/
if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
{
((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
simple_heap_update(attr_rel, &tuple->t_self, tuple);
/* keep the system catalog indexes current */
CatalogUpdateIndexes(attr_rel, tuple);
/* Tell Phase 3 it needs to test the constraint */
tab->new_notnull = true;
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
}
else
address = InvalidObjectAddress;
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel), attnum);
heap_close(attr_rel, RowExclusiveLock);
return address;
}
/*
* ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
*
* Return the address of the affected column.
*/
static ObjectAddress
ATExecColumnDefault(Relation rel, const char *colName,
Node *newDefault, LOCKMODE lockmode)
{
AttrNumber attnum;
ObjectAddress address;
/*
* get the number of the attribute
*/
attnum = get_attnum(RelationGetRelid(rel), colName);
if (attnum == InvalidAttrNumber)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
/* Prevent them from altering a system attribute */
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/*
* Remove any old default for the column. We use RESTRICT here for
* safety, but at present we do not expect anything to depend on the
* default.
*
* We treat removing the existing default as an internal operation when it
* is preparatory to adding a new default, but as a user-initiated
* operation when the user asked for a drop.
*/
RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
newDefault == NULL ? false : true);
if (newDefault)
{
/* SET DEFAULT */
RawColumnDefault *rawEnt;
rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
rawEnt->attnum = attnum;
rawEnt->raw_default = newDefault;
/*
* This function is intended for CREATE TABLE, so it processes a
* _list_ of defaults, but we just do one.
*/
AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
false, true, false);
}
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
return address;
}
/*
* ALTER TABLE ALTER COLUMN SET STATISTICS
*/
static void
ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
{
/*
* We do our own permission checking because (a) we want to allow SET
* STATISTICS on indexes (for expressional index columns), and (b) we want
* to allow SET STATISTICS on system catalogs without requiring
* allowSystemTableMods to be turned on.
*/
if (rel->rd_rel->relkind != RELKIND_RELATION &&
rel->rd_rel->relkind != RELKIND_MATVIEW &&
rel->rd_rel->relkind != RELKIND_INDEX &&
rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, materialized view, index, or foreign table",
RelationGetRelationName(rel))));
/* Permissions checks */
if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(rel));
}
/*
* Return value is the address of the modified column
*/
static ObjectAddress
ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
{
int newtarget;
Relation attrelation;
HeapTuple tuple;
Form_pg_attribute attrtuple;
AttrNumber attnum;
ObjectAddress address;
Assert(IsA(newValue, Integer));
newtarget = intVal(newValue);
/*
* Limit target to a sane range
*/
if (newtarget < -1)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("statistics target %d is too low",
newtarget)));
}
else if (newtarget > 10000)
{
newtarget = 10000;
ereport(WARNING,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("lowering statistics target to %d",
newtarget)));
}
attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = attrtuple->attnum;
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
attrtuple->attstattarget = newtarget;
simple_heap_update(attrelation, &tuple->t_self, tuple);
/* keep system catalog indexes current */
CatalogUpdateIndexes(attrelation, tuple);
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel),
attrtuple->attnum);
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
heap_freetuple(tuple);
heap_close(attrelation, RowExclusiveLock);
return address;
}
/*
* Return value is the address of the modified column
*/
static ObjectAddress
ATExecSetOptions(Relation rel, const char *colName, Node *options,
bool isReset, LOCKMODE lockmode)
{
Relation attrelation;
HeapTuple tuple,
newtuple;
Form_pg_attribute attrtuple;
AttrNumber attnum;
Datum datum,
newOptions;
bool isnull;
ObjectAddress address;
Datum repl_val[Natts_pg_attribute];
bool repl_null[Natts_pg_attribute];
bool repl_repl[Natts_pg_attribute];
attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = attrtuple->attnum;
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/* Generate new proposed attoptions (text array) */
Assert(IsA(options, List));
datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
&isnull);
newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
(List *) options, NULL, NULL, false,
isReset);
/* Validate new options */
(void) attribute_reloptions(newOptions, true);
/* Build new tuple. */
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
if (newOptions != (Datum) 0)
repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
else
repl_null[Anum_pg_attribute_attoptions - 1] = true;
repl_repl[Anum_pg_attribute_attoptions - 1] = true;
newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
repl_val, repl_null, repl_repl);
/* Update system catalog. */
simple_heap_update(attrelation, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(attrelation, newtuple);
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel),
attrtuple->attnum);
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
heap_freetuple(newtuple);
ReleaseSysCache(tuple);
heap_close(attrelation, RowExclusiveLock);
return address;
}
/*
* ALTER TABLE ALTER COLUMN SET STORAGE
*
* Return value is the address of the modified column
*/
static ObjectAddress
ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
{
char *storagemode;
char newstorage;
Relation attrelation;
HeapTuple tuple;
Form_pg_attribute attrtuple;
AttrNumber attnum;
ObjectAddress address;
Assert(IsA(newValue, String));
storagemode = strVal(newValue);
if (pg_strcasecmp(storagemode, "plain") == 0)
newstorage = 'p';
else if (pg_strcasecmp(storagemode, "external") == 0)
newstorage = 'e';
else if (pg_strcasecmp(storagemode, "extended") == 0)
newstorage = 'x';
else if (pg_strcasecmp(storagemode, "main") == 0)
newstorage = 'm';
else
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid storage type \"%s\"",
storagemode)));
newstorage = 0; /* keep compiler quiet */
}
attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = attrtuple->attnum;
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/*
* safety check: do not allow toasted storage modes unless column datatype
* is TOAST-aware.
*/
if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
attrtuple->attstorage = newstorage;
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("column data type %s can only have storage PLAIN",
format_type_be(attrtuple->atttypid))));
simple_heap_update(attrelation, &tuple->t_self, tuple);
/* keep system catalog indexes current */
CatalogUpdateIndexes(attrelation, tuple);
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel),
attrtuple->attnum);
heap_freetuple(tuple);
heap_close(attrelation, RowExclusiveLock);
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
return address;
}
/*
* ALTER TABLE DROP COLUMN
*
* DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
* because we have to decide at runtime whether to recurse or not depending
* on whether attinhcount goes to zero or not. (We can't check this in a
* static pre-pass because it won't handle multiple inheritance situations
* correctly.)
*/
static void
ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
AlterTableCmd *cmd, LOCKMODE lockmode)
{
if (rel->rd_rel->reloftype && !recursing)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot drop column from typed table")));
if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
if (recurse)
cmd->subtype = AT_DropColumnRecurse;
}
/*
* Return value is the address of the dropped column.
*/
static ObjectAddress
ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
DropBehavior behavior,
bool recurse, bool recursing,
bool missing_ok, LOCKMODE lockmode)
{
HeapTuple tuple;
Form_pg_attribute targetatt;
AttrNumber attnum;
List *children;
ObjectAddress object;
/* At top level, permission check was done in ATPrepCmd, else do it */
if (recursing)
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/*
* get the number of the attribute
*/
tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
{
if (!missing_ok)
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
}
else
{
ereport(NOTICE,
(errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
colName, RelationGetRelationName(rel))));
return InvalidObjectAddress;
}
}
targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = targetatt->attnum;
/* Can't drop a system attribute, except OID */
if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot drop system column \"%s\"",
colName)));
/* Don't drop inherited columns */
if (targetatt->attinhcount > 0 && !recursing)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot drop inherited column \"%s\"",
colName)));
ReleaseSysCache(tuple);
/*
* Propagate to children as appropriate. Unlike most other ALTER
* routines, we have to do this one level of recursion at a time; we can't
* use find_all_inheritors to do it in one pass.
*/
children = find_inheritance_children(RelationGetRelid(rel), lockmode);
if (children)
{
Relation attr_rel;
ListCell *child;
attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
Form_pg_attribute childatt;
/* find_inheritance_children already got lock */
childrel = heap_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
tuple = SearchSysCacheCopyAttName(childrelid, colName);
if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
colName, childrelid);
childatt = (Form_pg_attribute) GETSTRUCT(tuple);
if (childatt->attinhcount <= 0) /* shouldn't happen */
elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
childrelid, colName);
if (recurse)
{
/*
* If the child column has other definition sources, just
* decrement its inheritance count; if not, recurse to delete
* it.
*/
if (childatt->attinhcount == 1 && !childatt->attislocal)
{
/* Time to delete this child column, too */
ATExecDropColumn(wqueue, childrel, colName,
behavior, true, true,
false, lockmode);
}
else
{
/* Child column must survive my deletion */
childatt->attinhcount--;
simple_heap_update(attr_rel, &tuple->t_self, tuple);
/* keep the system catalog indexes current */
CatalogUpdateIndexes(attr_rel, tuple);
/* Make update visible */
CommandCounterIncrement();
}
}
else
{
/*
* If we were told to drop ONLY in this table (no recursion),
* we need to mark the inheritors' attributes as locally
* defined rather than inherited.
*/
childatt->attinhcount--;
childatt->attislocal = true;
simple_heap_update(attr_rel, &tuple->t_self, tuple);
/* keep the system catalog indexes current */
CatalogUpdateIndexes(attr_rel, tuple);
/* Make update visible */
CommandCounterIncrement();
}
heap_freetuple(tuple);
heap_close(childrel, NoLock);
}
heap_close(attr_rel, RowExclusiveLock);
}
/*
* Perform the actual column deletion
*/
object.classId = RelationRelationId;
object.objectId = RelationGetRelid(rel);
object.objectSubId = attnum;
performDeletion(&object, behavior, 0);
/*
* If we dropped the OID column, must adjust pg_class.relhasoids and tell
* Phase 3 to physically get rid of the column. We formerly left the
* column in place physically, but this caused subtle problems. See
* http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
*/
if (attnum == ObjectIdAttributeNumber)
{
Relation class_rel;
Form_pg_class tuple_class;
AlteredTableInfo *tab;
class_rel = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID,
ObjectIdGetDatum(RelationGetRelid(rel)));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u",
RelationGetRelid(rel));
tuple_class = (Form_pg_class) GETSTRUCT(tuple);
tuple_class->relhasoids = false;
simple_heap_update(class_rel, &tuple->t_self, tuple);
/* Keep the catalog indexes up to date */
CatalogUpdateIndexes(class_rel, tuple);
heap_close(class_rel, RowExclusiveLock);
/* Find or create work queue entry for this table */
tab = ATGetQueueEntry(wqueue, rel);
/* Tell Phase 3 to physically remove the OID column */
tab->rewrite |= AT_REWRITE_ALTER_OID;
}
return object;
}
/*
* ALTER TABLE ADD INDEX
*
* There is no such command in the grammar, but parse_utilcmd.c converts
* UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
* us schedule creation of the index at the appropriate time during ALTER.
*
* Return value is the address of the new index.
*/
static ObjectAddress
ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
{
bool check_rights;
bool skip_build;
bool quiet;
ObjectAddress address;
Assert(IsA(stmt, IndexStmt));
Assert(!stmt->concurrent);
/* The IndexStmt has already been through transformIndexStmt */
Assert(stmt->transformed);
/* suppress schema rights check when rebuilding existing index */
check_rights = !is_rebuild;
/* skip index build if phase 3 will do it or we're reusing an old one */
skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
/* suppress notices when rebuilding existing index */
quiet = is_rebuild;
address = DefineIndex(RelationGetRelid(rel),
stmt,
InvalidOid, /* no predefined OID */
true, /* is_alter_table */
check_rights,
skip_build,
quiet);
/*
* If TryReuseIndex() stashed a relfilenode for us, we used it for the new
* index instead of building from scratch. The DROP of the old edition of
* this index will have scheduled the storage for deletion at commit, so
* cancel that pending deletion.
*/
if (OidIsValid(stmt->oldNode))
{
Relation irel = index_open(address.objectId, NoLock);
RelationPreserveStorage(irel->rd_node, true);
index_close(irel, NoLock);
}
return address;
}
/*
* ALTER TABLE ADD CONSTRAINT USING INDEX
*
* Returns the address of the new constraint.
*/
static ObjectAddress
ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
IndexStmt *stmt, LOCKMODE lockmode)
{
Oid index_oid = stmt->indexOid;
Relation indexRel;
char *indexName;
IndexInfo *indexInfo;
char *constraintName;
char constraintType;
ObjectAddress address;
Assert(IsA(stmt, IndexStmt));
Assert(OidIsValid(index_oid));
Assert(stmt->isconstraint);
indexRel = index_open(index_oid, AccessShareLock);
indexName = pstrdup(RelationGetRelationName(indexRel));
indexInfo = BuildIndexInfo(indexRel);
/* this should have been checked at parse time */
if (!indexInfo->ii_Unique)
elog(ERROR, "index \"%s\" is not unique", indexName);
/*
* Determine name to assign to constraint. We require a constraint to
* have the same name as the underlying index; therefore, use the index's
* existing name as the default constraint name, and if the user
* explicitly gives some other name for the constraint, rename the index
* to match.
*/
constraintName = stmt->idxname;
if (constraintName == NULL)
constraintName = indexName;
else if (strcmp(constraintName, indexName) != 0)
{
ereport(NOTICE,
(errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
indexName, constraintName)));
RenameRelationInternal(index_oid, constraintName, false);
}
/* Extra checks needed if making primary key */
if (stmt->primary)
index_check_primary_key(rel, indexInfo, true);
/* Note we currently don't support EXCLUSION constraints here */
if (stmt->primary)
constraintType = CONSTRAINT_PRIMARY;
else
constraintType = CONSTRAINT_UNIQUE;
/* Create the catalog entries for the constraint */
address = index_constraint_create(rel,
index_oid,
indexInfo,
constraintName,
constraintType,
stmt->deferrable,
stmt->initdeferred,
stmt->primary,
true, /* update pg_index */
true, /* remove old dependencies */
allowSystemTableMods,
false); /* is_internal */
index_close(indexRel, NoLock);
return address;
}
/*
* ALTER TABLE ADD CONSTRAINT
*
* Return value is the address of the new constraint; if no constraint was
* added, InvalidObjectAddress is returned.
*/
static ObjectAddress
ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
Constraint *newConstraint, bool recurse, bool is_readd,
LOCKMODE lockmode)
{
ObjectAddress address = InvalidObjectAddress;
Assert(IsA(newConstraint, Constraint));
/*
* Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
* arriving here (see the preprocessing done in parse_utilcmd.c). Use a
* switch anyway to make it easier to add more code later.
*/
switch (newConstraint->contype)
{
case CONSTR_CHECK:
address =
ATAddCheckConstraint(wqueue, tab, rel,
newConstraint, recurse, false, is_readd,
lockmode);
break;
case CONSTR_FOREIGN:
/*
* Note that we currently never recurse for FK constraints, so the
* "recurse" flag is silently ignored.
*
* Assign or validate constraint name
*/
if (newConstraint->conname)
{
if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
RelationGetRelid(rel),
RelationGetNamespace(rel),
newConstraint->conname))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("constraint \"%s\" for relation \"%s\" already exists",
newConstraint->conname,
RelationGetRelationName(rel))));
}
else
newConstraint->conname =
ChooseConstraintName(RelationGetRelationName(rel),
strVal(linitial(newConstraint->fk_attrs)),
"fkey",
RelationGetNamespace(rel),
NIL);
address = ATAddForeignKeyConstraint(tab, rel, newConstraint,
lockmode);
break;
default:
elog(ERROR, "unrecognized constraint type: %d",
(int) newConstraint->contype);
}
return address;
}
/*
* Add a check constraint to a single table and its children. Returns the
* address of the constraint added to the parent relation, if one gets added,
* or InvalidObjectAddress otherwise.
*
* Subroutine for ATExecAddConstraint.
*
* We must recurse to child tables during execution, rather than using
* ALTER TABLE's normal prep-time recursion. The reason is that all the
* constraints *must* be given the same name, else they won't be seen as
* related later. If the user didn't explicitly specify a name, then
* AddRelationNewConstraints would normally assign different names to the
* child constraints. To fix that, we must capture the name assigned at
* the parent table and pass that down.
*/
static ObjectAddress
ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
Constraint *constr, bool recurse, bool recursing,
bool is_readd, LOCKMODE lockmode)
{
List *newcons;
ListCell *lcon;
List *children;
ListCell *child;
ObjectAddress address = InvalidObjectAddress;
/* At top level, permission check was done in ATPrepCmd, else do it */
if (recursing)
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/*
* Call AddRelationNewConstraints to do the work, making sure it works on
* a copy of the Constraint so transformExpr can't modify the original. It
* returns a list of cooked constraints.
*
* If the constraint ends up getting merged with a pre-existing one, it's
* omitted from the returned list, which is what we want: we do not need
* to do any validation work. That can only happen at child tables,
* though, since we disallow merging at the top level.
*/
newcons = AddRelationNewConstraints(rel, NIL,
list_make1(copyObject(constr)),
recursing | is_readd, /* allow_merge */
!recursing, /* is_local */
is_readd); /* is_internal */
/* we don't expect more than one constraint here */
Assert(list_length(newcons) <= 1);
/* Add each to-be-validated constraint to Phase 3's queue */
foreach(lcon, newcons)
{
CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
if (!ccon->skip_validation)
{
NewConstraint *newcon;
newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
newcon->name = ccon->name;
newcon->contype = ccon->contype;
/* ExecQual wants implicit-AND format */
newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
tab->constraints = lappend(tab->constraints, newcon);
}
/* Save the actually assigned name if it was defaulted */
if (constr->conname == NULL)
constr->conname = ccon->name;
ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
}
/* At this point we must have a locked-down name to use */
Assert(constr->conname != NULL);
/* Advance command counter in case same table is visited multiple times */
CommandCounterIncrement();
/*
* If the constraint got merged with an existing constraint, we're done.
* We mustn't recurse to child tables in this case, because they've
* already got the constraint, and visiting them again would lead to an
* incorrect value for coninhcount.
*/
if (newcons == NIL)
return address;
/*
* If adding a NO INHERIT constraint, no need to find our children.
*/
if (constr->is_no_inherit)
return address;
/*
* Propagate to children as appropriate. Unlike most other ALTER
* routines, we have to do this one level of recursion at a time; we can't
* use find_all_inheritors to do it in one pass.
*/
children = find_inheritance_children(RelationGetRelid(rel), lockmode);
/*
* Check if ONLY was specified with ALTER TABLE. If so, allow the
* constraint creation only if there are no children currently. Error out
* otherwise.
*/
if (!recurse && children != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraint must be added to child tables too")));
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
AlteredTableInfo *childtab;
/* find_inheritance_children already got lock */
childrel = heap_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
/* Find or create work queue entry for this table */
childtab = ATGetQueueEntry(wqueue, childrel);
/* Recurse to child */
ATAddCheckConstraint(wqueue, childtab, childrel,
constr, recurse, true, is_readd, lockmode);
heap_close(childrel, NoLock);
}
return address;
}
/*
* Add a foreign-key constraint to a single table; return the new constraint's
* address.
*
* Subroutine for ATExecAddConstraint. Must already hold exclusive
* lock on the rel, and have done appropriate validity checks for it.
* We do permissions checks here, however.
*/
static ObjectAddress
ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
Constraint *fkconstraint, LOCKMODE lockmode)
{
Relation pkrel;
int16 pkattnum[INDEX_MAX_KEYS];
int16 fkattnum[INDEX_MAX_KEYS];
Oid pktypoid[INDEX_MAX_KEYS];
Oid fktypoid[INDEX_MAX_KEYS];
Oid opclasses[INDEX_MAX_KEYS];
Oid pfeqoperators[INDEX_MAX_KEYS];
Oid ppeqoperators[INDEX_MAX_KEYS];
Oid ffeqoperators[INDEX_MAX_KEYS];
int i;
int numfks,
numpks;
Oid indexOid;
Oid constrOid;
bool old_check_ok;
ObjectAddress address;
ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
/*
* Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
* delete rows out from under us.
*/
if (OidIsValid(fkconstraint->old_pktable_oid))
pkrel = heap_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
else
pkrel = heap_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
/*
* Validity checks (permission checks wait till we have the column
* numbers)
*/
if (pkrel->rd_rel->relkind != RELKIND_RELATION)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("referenced relation \"%s\" is not a table",
RelationGetRelationName(pkrel))));
if (!allowSystemTableMods && IsSystemRelation(pkrel))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
RelationGetRelationName(pkrel))));
/*
* References from permanent or unlogged tables to temp tables, and from
* permanent tables to unlogged tables, are disallowed because the
* referenced data can vanish out from under us. References from temp
* tables to any other table type are also disallowed, because other
* backends might need to run the RI triggers on the perm table, but they
* can't reliably see tuples in the local buffers of other backends.
*/
switch (rel->rd_rel->relpersistence)
{
case RELPERSISTENCE_PERMANENT:
if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraints on permanent tables may reference only permanent tables")));
break;
case RELPERSISTENCE_UNLOGGED:
if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
&& pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
break;
case RELPERSISTENCE_TEMP:
if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraints on temporary tables may reference only temporary tables")));
if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraints on temporary tables must involve temporary tables of this session")));
break;
}
/*
* Look up the referencing attributes to make sure they exist, and record
* their attnums and type OIDs.
*/
MemSet(pkattnum, 0, sizeof(pkattnum));
MemSet(fkattnum, 0, sizeof(fkattnum));
MemSet(pktypoid, 0, sizeof(pktypoid));
MemSet(fktypoid, 0, sizeof(fktypoid));
MemSet(opclasses, 0, sizeof(opclasses));
MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
numfks = transformColumnNameList(RelationGetRelid(rel),
fkconstraint->fk_attrs,
fkattnum, fktypoid);
/*
* If the attribute list for the referenced table was omitted, lookup the
* definition of the primary key and use it. Otherwise, validate the
* supplied attribute list. In either case, discover the index OID and
* index opclasses, and the attnums and type OIDs of the attributes.
*/
if (fkconstraint->pk_attrs == NIL)
{
numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
&fkconstraint->pk_attrs,
pkattnum, pktypoid,
opclasses);
}
else
{
numpks = transformColumnNameList(RelationGetRelid(pkrel),
fkconstraint->pk_attrs,
pkattnum, pktypoid);
/* Look for an index matching the column list */
indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
opclasses);
}
/*
* Now we can check permissions.
*/
checkFkeyPermissions(pkrel, pkattnum, numpks);
checkFkeyPermissions(rel, fkattnum, numfks);
/*
* Look up the equality operators to use in the constraint.
*
* Note that we have to be careful about the difference between the actual
* PK column type and the opclass' declared input type, which might be
* only binary-compatible with it. The declared opcintype is the right
* thing to probe pg_amop with.
*/
if (numfks != numpks)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FOREIGN_KEY),
errmsg("number of referencing and referenced columns for foreign key disagree")));
/*
* On the strength of a previous constraint, we might avoid scanning
* tables to validate this one. See below.
*/
old_check_ok = (fkconstraint->old_conpfeqop != NIL);
Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
for (i = 0; i < numpks; i++)
{
Oid pktype = pktypoid[i];
Oid fktype = fktypoid[i];
Oid fktyped;
HeapTuple cla_ht;
Form_pg_opclass cla_tup;
Oid amid;
Oid opfamily;
Oid opcintype;
Oid pfeqop;
Oid ppeqop;
Oid ffeqop;
int16 eqstrategy;
Oid pfeqop_right;
/* We need several fields out of the pg_opclass entry */
cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
if (!HeapTupleIsValid(cla_ht))
elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
amid = cla_tup->opcmethod;
opfamily = cla_tup->opcfamily;
opcintype = cla_tup->opcintype;
ReleaseSysCache(cla_ht);
/*
* Check it's a btree; currently this can never fail since no other
* index AMs support unique indexes. If we ever did have other types
* of unique indexes, we'd need a way to determine which operator
* strategy number is equality. (Is it reasonable to insist that
* every such index AM use btree's number for equality?)
*/
if (amid != BTREE_AM_OID)
elog(ERROR, "only b-tree indexes are supported for foreign keys");
eqstrategy = BTEqualStrategyNumber;
/*
* There had better be a primary equality operator for the index.
* We'll use it for PK = PK comparisons.
*/
ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
eqstrategy);
if (!OidIsValid(ppeqop))
elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
eqstrategy, opcintype, opcintype, opfamily);
/*
* Are there equality operators that take exactly the FK type? Assume
* we should look through any domain here.
*/
fktyped = getBaseType(fktype);
pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
eqstrategy);
if (OidIsValid(pfeqop))
{
pfeqop_right = fktyped;
ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
eqstrategy);
}
else
{
/* keep compiler quiet */
pfeqop_right = InvalidOid;
ffeqop = InvalidOid;
}
if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
{
/*
* Otherwise, look for an implicit cast from the FK type to the
* opcintype, and if found, use the primary equality operator.
* This is a bit tricky because opcintype might be a polymorphic
* type such as ANYARRAY or ANYENUM; so what we have to test is
* whether the two actual column types can be concurrently cast to
* that type. (Otherwise, we'd fail to reject combinations such
* as int[] and point[].)
*/
Oid input_typeids[2];
Oid target_typeids[2];
input_typeids[0] = pktype;
input_typeids[1] = fktype;
target_typeids[0] = opcintype;
target_typeids[1] = opcintype;
if (can_coerce_type(2, input_typeids, target_typeids,
COERCION_IMPLICIT))
{
pfeqop = ffeqop = ppeqop;
pfeqop_right = opcintype;
}
}
if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("foreign key constraint \"%s\" "
"cannot be implemented",
fkconstraint->conname),
errdetail("Key columns \"%s\" and \"%s\" "
"are of incompatible types: %s and %s.",
strVal(list_nth(fkconstraint->fk_attrs, i)),
strVal(list_nth(fkconstraint->pk_attrs, i)),
format_type_be(fktype),
format_type_be(pktype))));
if (old_check_ok)
{
/*
* When a pfeqop changes, revalidate the constraint. We could
* permit intra-opfamily changes, but that adds subtle complexity
* without any concrete benefit for core types. We need not
* assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
*/
old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
old_pfeqop_item = lnext(old_pfeqop_item);
}
if (old_check_ok)
{
Oid old_fktype;
Oid new_fktype;
CoercionPathType old_pathtype;
CoercionPathType new_pathtype;
Oid old_castfunc;
Oid new_castfunc;
/*
* Identify coercion pathways from each of the old and new FK-side
* column types to the right (foreign) operand type of the pfeqop.
* We may assume that pg_constraint.conkey is not changing.
*/
old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
new_fktype = fktype;
old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
&old_castfunc);
new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
&new_castfunc);
/*
* Upon a change to the cast from the FK column to its pfeqop
* operand, revalidate the constraint. For this evaluation, a
* binary coercion cast is equivalent to no cast at all. While
* type implementors should design implicit casts with an eye
* toward consistency of operations like equality, we cannot
* assume here that they have done so.
*
* A function with a polymorphic argument could change behavior
* arbitrarily in response to get_fn_expr_argtype(). Therefore,
* when the cast destination is polymorphic, we only avoid
* revalidation if the input type has not changed at all. Given
* just the core data types and operator classes, this requirement
* prevents no would-be optimizations.
*
* If the cast converts from a base type to a domain thereon, then
* that domain type must be the opcintype of the unique index.
* Necessarily, the primary key column must then be of the domain
* type. Since the constraint was previously valid, all values on
* the foreign side necessarily exist on the primary side and in
* turn conform to the domain. Consequently, we need not treat
* domains specially here.
*
* Since we require that all collations share the same notion of
* equality (which they do, because texteq reduces to bitwise
* equality), we don't compare collation here.
*
* We need not directly consider the PK type. It's necessarily
* binary coercible to the opcintype of the unique index column,
* and ri_triggers.c will only deal with PK datums in terms of
* that opcintype. Changing the opcintype also changes pfeqop.
*/
old_check_ok = (new_pathtype == old_pathtype &&
new_castfunc == old_castfunc &&
(!IsPolymorphicType(pfeqop_right) ||
new_fktype == old_fktype));
}
pfeqoperators[i] = pfeqop;
ppeqoperators[i] = ppeqop;
ffeqoperators[i] = ffeqop;
}
/*
* Record the FK constraint in pg_constraint.
*/
constrOid = CreateConstraintEntry(fkconstraint->conname,
RelationGetNamespace(rel),
CONSTRAINT_FOREIGN,
fkconstraint->deferrable,
fkconstraint->initdeferred,
fkconstraint->initially_valid,
RelationGetRelid(rel),
fkattnum,
numfks,
InvalidOid, /* not a domain
* constraint */
indexOid,
RelationGetRelid(pkrel),
pkattnum,
pfeqoperators,
ppeqoperators,
ffeqoperators,
numpks,
fkconstraint->fk_upd_action,
fkconstraint->fk_del_action,
fkconstraint->fk_matchtype,
NULL, /* no exclusion constraint */
NULL, /* no check constraint */
NULL,
NULL,
true, /* islocal */
0, /* inhcount */
true, /* isnoinherit */
false); /* is_internal */
ObjectAddressSet(address, ConstraintRelationId, constrOid);
/*
* Create the triggers that will enforce the constraint.
*/
createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
constrOid, indexOid);
/*
* Tell Phase 3 to check that the constraint is satisfied by existing
* rows. We can skip this during table creation, when requested explicitly
* by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
* recreating a constraint following a SET DATA TYPE operation that did
* not impugn its validity.
*/
if (!old_check_ok && !fkconstraint->skip_validation)
{
NewConstraint *newcon;
newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
newcon->name = fkconstraint->conname;
newcon->contype = CONSTR_FOREIGN;
newcon->refrelid = RelationGetRelid(pkrel);
newcon->refindid = indexOid;
newcon->conid = constrOid;
newcon->qual = (Node *) fkconstraint;
tab->constraints = lappend(tab->constraints, newcon);
}
/*
* Close pk table, but keep lock until we've committed.
*/
heap_close(pkrel, NoLock);
return address;
}
/*
* ALTER TABLE ALTER CONSTRAINT
*
* Update the attributes of a constraint.
*
* Currently only works for Foreign Key constraints.
* Foreign keys do not inherit, so we purposely ignore the
* recursion bit here, but we keep the API the same for when
* other constraint types are supported.
*
* If the constraint is modified, returns its address; otherwise, return
* InvalidObjectAddress.
*/
static ObjectAddress
ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
bool recurse, bool recursing, LOCKMODE lockmode)
{
Constraint *cmdcon;
Relation conrel;
SysScanDesc scan;
ScanKeyData key;
HeapTuple contuple;
Form_pg_constraint currcon = NULL;
bool found = false;
ObjectAddress address;
Assert(IsA(cmd->def, Constraint));
cmdcon = (Constraint *) cmd->def;
conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
/*
* Find and check the target constraint
*/
ScanKeyInit(&key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(conrel, ConstraintRelidIndexId,
true, NULL, 1, &key);
while (HeapTupleIsValid(contuple = systable_getnext(scan)))
{
currcon = (Form_pg_constraint) GETSTRUCT(contuple);
if (strcmp(NameStr(currcon->conname), cmdcon->conname) == 0)
{
found = true;
break;
}
}
if (!found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of relation \"%s\" does not exist",
cmdcon->conname, RelationGetRelationName(rel))));
if (currcon->contype != CONSTRAINT_FOREIGN)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
cmdcon->conname, RelationGetRelationName(rel))));
if (currcon->condeferrable != cmdcon->deferrable ||
currcon->condeferred != cmdcon->initdeferred)
{
HeapTuple copyTuple;
HeapTuple tgtuple;
Form_pg_constraint copy_con;
List *otherrelids = NIL;
ScanKeyData tgkey;
SysScanDesc tgscan;
Relation tgrel;
ListCell *lc;
/*
* Now update the catalog, while we have the door open.
*/
copyTuple = heap_copytuple(contuple);
copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
copy_con->condeferrable = cmdcon->deferrable;
copy_con->condeferred = cmdcon->initdeferred;
simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
CatalogUpdateIndexes(conrel, copyTuple);
InvokeObjectPostAlterHook(ConstraintRelationId,
HeapTupleGetOid(contuple), 0);
heap_freetuple(copyTuple);
/*
* Now we need to update the multiple entries in pg_trigger that
* implement the constraint.
*/
tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
ScanKeyInit(&tgkey,
Anum_pg_trigger_tgconstraint,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(HeapTupleGetOid(contuple)));
tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
NULL, 1, &tgkey);
while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
{
Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
Form_pg_trigger copy_tg;
/*
* Remember OIDs of other relation(s) involved in FK constraint.
* (Note: it's likely that we could skip forcing a relcache inval
* for other rels that don't have a trigger whose properties
* change, but let's be conservative.)
*/
if (tgform->tgrelid != RelationGetRelid(rel))
otherrelids = list_append_unique_oid(otherrelids,
tgform->tgrelid);
/*
* Update deferrability of RI_FKey_noaction_del,
* RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
* triggers, but not others; see createForeignKeyTriggers and
* CreateFKCheckTrigger.
*/
if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
continue;
copyTuple = heap_copytuple(tgtuple);
copy_tg = (Form_pg_trigger) GETSTRUCT(copyTuple);
copy_tg->tgdeferrable = cmdcon->deferrable;
copy_tg->tginitdeferred = cmdcon->initdeferred;
simple_heap_update(tgrel, ©Tuple->t_self, copyTuple);
CatalogUpdateIndexes(tgrel, copyTuple);
InvokeObjectPostAlterHook(TriggerRelationId,
HeapTupleGetOid(tgtuple), 0);
heap_freetuple(copyTuple);
}
systable_endscan(tgscan);
heap_close(tgrel, RowExclusiveLock);
/*
* Invalidate relcache so that others see the new attributes. We must
* inval both the named rel and any others having relevant triggers.
* (At present there should always be exactly one other rel, but
* there's no need to hard-wire such an assumption here.)
*/
CacheInvalidateRelcache(rel);
foreach(lc, otherrelids)
{
CacheInvalidateRelcacheByRelid(lfirst_oid(lc));
}
ObjectAddressSet(address, ConstraintRelationId,
HeapTupleGetOid(contuple));
}
else
address = InvalidObjectAddress;
systable_endscan(scan);
heap_close(conrel, RowExclusiveLock);
return address;
}
/*
* ALTER TABLE VALIDATE CONSTRAINT
*
* XXX The reason we handle recursion here rather than at Phase 1 is because
* there's no good way to skip recursing when handling foreign keys: there is
* no need to lock children in that case, yet we wouldn't be able to avoid
* doing so at that level.
*
* Return value is the address of the validated constraint. If the constraint
* was already validated, InvalidObjectAddress is returned.
*/
static ObjectAddress
ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
bool recursing, LOCKMODE lockmode)
{
Relation conrel;
SysScanDesc scan;
ScanKeyData key;
HeapTuple tuple;
Form_pg_constraint con = NULL;
bool found = false;
ObjectAddress address;
conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
/*
* Find and check the target constraint
*/
ScanKeyInit(&key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(conrel, ConstraintRelidIndexId,
true, NULL, 1, &key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
con = (Form_pg_constraint) GETSTRUCT(tuple);
if (strcmp(NameStr(con->conname), constrName) == 0)
{
found = true;
break;
}
}
if (!found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of relation \"%s\" does not exist",
constrName, RelationGetRelationName(rel))));
if (con->contype != CONSTRAINT_FOREIGN &&
con->contype != CONSTRAINT_CHECK)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
constrName, RelationGetRelationName(rel))));
if (!con->convalidated)
{
HeapTuple copyTuple;
Form_pg_constraint copy_con;
if (con->contype == CONSTRAINT_FOREIGN)
{
Relation refrel;
/*
* Triggers are already in place on both tables, so a concurrent
* write that alters the result here is not possible. Normally we
* can run a query here to do the validation, which would only
* require AccessShareLock. In some cases, it is possible that we
* might need to fire triggers to perform the check, so we take a
* lock at RowShareLock level just in case.
*/
refrel = heap_open(con->confrelid, RowShareLock);
validateForeignKeyConstraint(constrName, rel, refrel,
con->conindid,
HeapTupleGetOid(tuple));
heap_close(refrel, NoLock);
/*
* Foreign keys do not inherit, so we purposely ignore the
* recursion bit here
*/
}
else if (con->contype == CONSTRAINT_CHECK)
{
List *children = NIL;
ListCell *child;
/*
* If we're recursing, the parent has already done this, so skip
* it. Also, if the constraint is a NO INHERIT constraint, we
* shouldn't try to look for it in the children.
*/
if (!recursing && !con->connoinherit)
children = find_all_inheritors(RelationGetRelid(rel),
lockmode, NULL);
/*
* For CHECK constraints, we must ensure that we only mark the
* constraint as validated on the parent if it's already validated
* on the children.
*
* We recurse before validating on the parent, to reduce risk of
* deadlocks.
*/
foreach(child, children)
{
Oid childoid = lfirst_oid(child);
Relation childrel;
if (childoid == RelationGetRelid(rel))
continue;
/*
* If we are told not to recurse, there had better not be any
* child tables; else the addition would put them out of step.
*/
if (!recurse)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("constraint must be validated on child tables too")));
/* find_all_inheritors already got lock */
childrel = heap_open(childoid, NoLock);
ATExecValidateConstraint(childrel, constrName, false,
true, lockmode);
heap_close(childrel, NoLock);
}
validateCheckConstraint(rel, tuple);
/*
* Invalidate relcache so that others see the new validated
* constraint.
*/
CacheInvalidateRelcache(rel);
}
/*
* Now update the catalog, while we have the door open.
*/
copyTuple = heap_copytuple(tuple);
copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
copy_con->convalidated = true;
simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
CatalogUpdateIndexes(conrel, copyTuple);
InvokeObjectPostAlterHook(ConstraintRelationId,
HeapTupleGetOid(tuple), 0);
heap_freetuple(copyTuple);
ObjectAddressSet(address, ConstraintRelationId,
HeapTupleGetOid(tuple));
}
else
address = InvalidObjectAddress; /* already validated */
systable_endscan(scan);
heap_close(conrel, RowExclusiveLock);
return address;
}
/*
* transformColumnNameList - transform list of column names
*
* Lookup each name and return its attnum and type OID
*/
static int
transformColumnNameList(Oid relId, List *colList,
int16 *attnums, Oid *atttypids)
{
ListCell *l;
int attnum;
attnum = 0;
foreach(l, colList)
{
char *attname = strVal(lfirst(l));
HeapTuple atttuple;
atttuple = SearchSysCacheAttName(relId, attname);
if (!HeapTupleIsValid(atttuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" referenced in foreign key constraint does not exist",
attname)));
if (attnum >= INDEX_MAX_KEYS)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("cannot have more than %d keys in a foreign key",
INDEX_MAX_KEYS)));
attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
ReleaseSysCache(atttuple);
attnum++;
}
return attnum;
}
/*
* transformFkeyGetPrimaryKey -
*
* Look up the names, attnums, and types of the primary key attributes
* for the pkrel. Also return the index OID and index opclasses of the
* index supporting the primary key.
*
* All parameters except pkrel are output parameters. Also, the function
* return value is the number of attributes in the primary key.
*
* Used when the column list in the REFERENCES specification is omitted.
*/
static int
transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
List **attnamelist,
int16 *attnums, Oid *atttypids,
Oid *opclasses)
{
List *indexoidlist;
ListCell *indexoidscan;
HeapTuple indexTuple = NULL;
Form_pg_index indexStruct = NULL;
Datum indclassDatum;
bool isnull;
oidvector *indclass;
int i;
/*
* Get the list of index OIDs for the table from the relcache, and look up
* each one in the pg_index syscache until we find one marked primary key
* (hopefully there isn't more than one such). Insist it's valid, too.
*/
*indexOid = InvalidOid;
indexoidlist = RelationGetIndexList(pkrel);
foreach(indexoidscan, indexoidlist)
{
Oid indexoid = lfirst_oid(indexoidscan);
indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "cache lookup failed for index %u", indexoid);
indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
if (indexStruct->indisprimary && IndexIsValid(indexStruct))
{
/*
* Refuse to use a deferrable primary key. This is per SQL spec,
* and there would be a lot of interesting semantic problems if we
* tried to allow it.
*/
if (!indexStruct->indimmediate)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
RelationGetRelationName(pkrel))));
*indexOid = indexoid;
break;
}
ReleaseSysCache(indexTuple);
}
list_free(indexoidlist);
/*
* Check that we found it
*/
if (!OidIsValid(*indexOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("there is no primary key for referenced table \"%s\"",
RelationGetRelationName(pkrel))));
/* Must get indclass the hard way */
indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
Anum_pg_index_indclass, &isnull);
Assert(!isnull);
indclass = (oidvector *) DatumGetPointer(indclassDatum);
/*
* Now build the list of PK attributes from the indkey definition (we
* assume a primary key cannot have expressional elements)
*/
*attnamelist = NIL;
for (i = 0; i < indexStruct->indnatts; i++)
{
int pkattno = indexStruct->indkey.values[i];
attnums[i] = pkattno;
atttypids[i] = attnumTypeId(pkrel, pkattno);
opclasses[i] = indclass->values[i];
*attnamelist = lappend(*attnamelist,
makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
}
ReleaseSysCache(indexTuple);
return i;
}
/*
* transformFkeyCheckAttrs -
*
* Make sure that the attributes of a referenced table belong to a unique
* (or primary key) constraint. Return the OID of the index supporting
* the constraint, as well as the opclasses associated with the index
* columns.
*/
static Oid
transformFkeyCheckAttrs(Relation pkrel,
int numattrs, int16 *attnums,
Oid *opclasses) /* output parameter */
{
Oid indexoid = InvalidOid;
bool found = false;
bool found_deferrable = false;
List *indexoidlist;
ListCell *indexoidscan;
int i,
j;
/*
* Reject duplicate appearances of columns in the referenced-columns list.
* Such a case is forbidden by the SQL standard, and even if we thought it
* useful to allow it, there would be ambiguity about how to match the
* list to unique indexes (in particular, it'd be unclear which index
* opclass goes with which FK column).
*/
for (i = 0; i < numattrs; i++)
{
for (j = i + 1; j < numattrs; j++)
{
if (attnums[i] == attnums[j])
ereport(ERROR,
(errcode(ERRCODE_INVALID_FOREIGN_KEY),
errmsg("foreign key referenced-columns list must not contain duplicates")));
}
}
/*
* Get the list of index OIDs for the table from the relcache, and look up
* each one in the pg_index syscache, and match unique indexes to the list
* of attnums we are given.
*/
indexoidlist = RelationGetIndexList(pkrel);
foreach(indexoidscan, indexoidlist)
{
HeapTuple indexTuple;
Form_pg_index indexStruct;
indexoid = lfirst_oid(indexoidscan);
indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "cache lookup failed for index %u", indexoid);
indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
/*
* Must have the right number of columns; must be unique and not a
* partial index; forget it if there are any expressions, too. Invalid
* indexes are out as well.
*/
if (indexStruct->indnatts == numattrs &&
indexStruct->indisunique &&
IndexIsValid(indexStruct) &&
heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
heap_attisnull(indexTuple, Anum_pg_index_indexprs))
{
Datum indclassDatum;
bool isnull;
oidvector *indclass;
/* Must get indclass the hard way */
indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
Anum_pg_index_indclass, &isnull);
Assert(!isnull);
indclass = (oidvector *) DatumGetPointer(indclassDatum);
/*
* The given attnum list may match the index columns in any order.
* Check for a match, and extract the appropriate opclasses while
* we're at it.
*
* We know that attnums[] is duplicate-free per the test at the
* start of this function, and we checked above that the number of
* index columns agrees, so if we find a match for each attnums[]
* entry then we must have a one-to-one match in some order.
*/
for (i = 0; i < numattrs; i++)
{
found = false;
for (j = 0; j < numattrs; j++)
{
if (attnums[i] == indexStruct->indkey.values[j])
{
opclasses[i] = indclass->values[j];
found = true;
break;
}
}
if (!found)
break;
}
/*
* Refuse to use a deferrable unique/primary key. This is per SQL
* spec, and there would be a lot of interesting semantic problems
* if we tried to allow it.
*/
if (found && !indexStruct->indimmediate)
{
/*
* Remember that we found an otherwise matching index, so that
* we can generate a more appropriate error message.
*/
found_deferrable = true;
found = false;
}
}
ReleaseSysCache(indexTuple);
if (found)
break;
}
if (!found)
{
if (found_deferrable)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
RelationGetRelationName(pkrel))));
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_FOREIGN_KEY),
errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
RelationGetRelationName(pkrel))));
}
list_free(indexoidlist);
return indexoid;
}
/*
* findFkeyCast -
*
* Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
* Caller has equal regard for binary coercibility and for an exact match.
*/
static CoercionPathType
findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
{
CoercionPathType ret;
if (targetTypeId == sourceTypeId)
{
ret = COERCION_PATH_RELABELTYPE;
*funcid = InvalidOid;
}
else
{
ret = find_coercion_pathway(targetTypeId, sourceTypeId,
COERCION_IMPLICIT, funcid);
if (ret == COERCION_PATH_NONE)
/* A previously-relied-upon cast is now gone. */
elog(ERROR, "could not find cast from %u to %u",
sourceTypeId, targetTypeId);
}
return ret;
}
/* Permissions checks for ADD FOREIGN KEY */
static void
checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
{
Oid roleid = GetUserId();
AclResult aclresult;
int i;
/* Okay if we have relation-level REFERENCES permission */
aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
ACL_REFERENCES);
if (aclresult == ACLCHECK_OK)
return;
/* Else we must have REFERENCES on each column */
for (i = 0; i < natts; i++)
{
aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
roleid, ACL_REFERENCES);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_CLASS,
RelationGetRelationName(rel));
}
}
/*
* Scan the existing rows in a table to verify they meet a proposed
* CHECK constraint.
*
* The caller must have opened and locked the relation appropriately.
*/
static void
validateCheckConstraint(Relation rel, HeapTuple constrtup)
{
EState *estate;
Datum val;
char *conbin;
Expr *origexpr;
List *exprstate;
TupleDesc tupdesc;
HeapScanDesc scan;
HeapTuple tuple;
ExprContext *econtext;
MemoryContext oldcxt;
TupleTableSlot *slot;
Form_pg_constraint constrForm;
bool isnull;
Snapshot snapshot;
/* VALIDATE CONSTRAINT is a no-op for foreign tables */
if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
return;
constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
estate = CreateExecutorState();
/*
* XXX this tuple doesn't really come from a syscache, but this doesn't
* matter to SysCacheGetAttr, because it only wants to be able to fetch
* the tupdesc
*/
val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
&isnull);
if (isnull)
elog(ERROR, "null conbin for constraint %u",
HeapTupleGetOid(constrtup));
conbin = TextDatumGetCString(val);
origexpr = (Expr *) stringToNode(conbin);
exprstate = (List *)
ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
econtext = GetPerTupleExprContext(estate);
tupdesc = RelationGetDescr(rel);
slot = MakeSingleTupleTableSlot(tupdesc);
econtext->ecxt_scantuple = slot;
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(rel, snapshot, 0, NULL);
/*
* Switch to per-tuple memory context and reset it for each tuple
* produced, so we don't leak memory.
*/
oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
ExecStoreTuple(tuple, slot, InvalidBuffer, false);
if (!ExecQual(exprstate, econtext, true))
ereport(ERROR,
(errcode(ERRCODE_CHECK_VIOLATION),
errmsg("check constraint \"%s\" is violated by some row",
NameStr(constrForm->conname)),
errtableconstraint(rel, NameStr(constrForm->conname))));
ResetExprContext(econtext);
}
MemoryContextSwitchTo(oldcxt);
heap_endscan(scan);
UnregisterSnapshot(snapshot);
ExecDropSingleTupleTableSlot(slot);
FreeExecutorState(estate);
}
/*
* Scan the existing rows in a table to verify they meet a proposed FK
* constraint.
*
* Caller must have opened and locked both relations appropriately.
*/
static void
validateForeignKeyConstraint(char *conname,
Relation rel,
Relation pkrel,
Oid pkindOid,
Oid constraintOid)
{
HeapScanDesc scan;
HeapTuple tuple;
Trigger trig;
Snapshot snapshot;
ereport(DEBUG1,
(errmsg("validating foreign key constraint \"%s\"", conname)));
/*
* Build a trigger call structure; we'll need it either way.
*/
MemSet(&trig, 0, sizeof(trig));
trig.tgoid = InvalidOid;
trig.tgname = conname;
trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
trig.tgisinternal = TRUE;
trig.tgconstrrelid = RelationGetRelid(pkrel);
trig.tgconstrindid = pkindOid;
trig.tgconstraint = constraintOid;
trig.tgdeferrable = FALSE;
trig.tginitdeferred = FALSE;
/* we needn't fill in tgargs or tgqual */
/*
* See if we can do it with a single LEFT JOIN query. A FALSE result
* indicates we must proceed with the fire-the-trigger method.
*/
if (RI_Initial_Check(&trig, rel, pkrel))
return;
/*
* Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
* if that tuple had just been inserted. If any of those fail, it should
* ereport(ERROR) and that's that.
*/
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(rel, snapshot, 0, NULL);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
FunctionCallInfoData fcinfo;
TriggerData trigdata;
/*
* Make a call to the trigger function
*
* No parameters are passed, but we do set a context
*/
MemSet(&fcinfo, 0, sizeof(fcinfo));
/*
* We assume RI_FKey_check_ins won't look at flinfo...
*/
trigdata.type = T_TriggerData;
trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
trigdata.tg_relation = rel;
trigdata.tg_trigtuple = tuple;
trigdata.tg_newtuple = NULL;
trigdata.tg_trigger = &trig;
trigdata.tg_trigtuplebuf = scan->rs_cbuf;
trigdata.tg_newtuplebuf = InvalidBuffer;
fcinfo.context = (Node *) &trigdata;
RI_FKey_check_ins(&fcinfo);
}
heap_endscan(scan);
UnregisterSnapshot(snapshot);
}
static void
CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
Oid constraintOid, Oid indexOid, bool on_insert)
{
CreateTrigStmt *fk_trigger;
/*
* Note: for a self-referential FK (referencing and referenced tables are
* the same), it is important that the ON UPDATE action fires before the
* CHECK action, since both triggers will fire on the same row during an
* UPDATE event; otherwise the CHECK trigger will be checking a non-final
* state of the row. Triggers fire in name order, so we ensure this by
* using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
* and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
*/
fk_trigger = makeNode(CreateTrigStmt);
fk_trigger->trigname = "RI_ConstraintTrigger_c";
fk_trigger->relation = NULL;
fk_trigger->row = true;
fk_trigger->timing = TRIGGER_TYPE_AFTER;
/* Either ON INSERT or ON UPDATE */
if (on_insert)
{
fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
fk_trigger->events = TRIGGER_TYPE_INSERT;
}
else
{
fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
fk_trigger->events = TRIGGER_TYPE_UPDATE;
}
fk_trigger->columns = NIL;
fk_trigger->whenClause = NULL;
fk_trigger->isconstraint = true;
fk_trigger->deferrable = fkconstraint->deferrable;
fk_trigger->initdeferred = fkconstraint->initdeferred;
fk_trigger->constrrel = NULL;
fk_trigger->args = NIL;
(void) CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid, constraintOid,
indexOid, true);
/* Make changes-so-far visible */
CommandCounterIncrement();
}
/*
* Create the triggers that implement an FK constraint.
*
* NB: if you change any trigger properties here, see also
* ATExecAlterConstraint.
*/
static void
createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint,
Oid constraintOid, Oid indexOid)
{
Oid myRelOid;
CreateTrigStmt *fk_trigger;
myRelOid = RelationGetRelid(rel);
/* Make changes-so-far visible */
CommandCounterIncrement();
/*
* Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
* DELETE action on the referenced table.
*/
fk_trigger = makeNode(CreateTrigStmt);
fk_trigger->trigname = "RI_ConstraintTrigger_a";
fk_trigger->relation = NULL;
fk_trigger->row = true;
fk_trigger->timing = TRIGGER_TYPE_AFTER;
fk_trigger->events = TRIGGER_TYPE_DELETE;
fk_trigger->columns = NIL;
fk_trigger->whenClause = NULL;
fk_trigger->isconstraint = true;
fk_trigger->constrrel = NULL;
switch (fkconstraint->fk_del_action)
{
case FKCONSTR_ACTION_NOACTION:
fk_trigger->deferrable = fkconstraint->deferrable;
fk_trigger->initdeferred = fkconstraint->initdeferred;
fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
break;
case FKCONSTR_ACTION_RESTRICT:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
break;
case FKCONSTR_ACTION_CASCADE:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
break;
case FKCONSTR_ACTION_SETNULL:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
break;
case FKCONSTR_ACTION_SETDEFAULT:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
break;
default:
elog(ERROR, "unrecognized FK action type: %d",
(int) fkconstraint->fk_del_action);
break;
}
fk_trigger->args = NIL;
(void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
indexOid, true);
/* Make changes-so-far visible */
CommandCounterIncrement();
/*
* Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
* UPDATE action on the referenced table.
*/
fk_trigger = makeNode(CreateTrigStmt);
fk_trigger->trigname = "RI_ConstraintTrigger_a";
fk_trigger->relation = NULL;
fk_trigger->row = true;
fk_trigger->timing = TRIGGER_TYPE_AFTER;
fk_trigger->events = TRIGGER_TYPE_UPDATE;
fk_trigger->columns = NIL;
fk_trigger->whenClause = NULL;
fk_trigger->isconstraint = true;
fk_trigger->constrrel = NULL;
switch (fkconstraint->fk_upd_action)
{
case FKCONSTR_ACTION_NOACTION:
fk_trigger->deferrable = fkconstraint->deferrable;
fk_trigger->initdeferred = fkconstraint->initdeferred;
fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
break;
case FKCONSTR_ACTION_RESTRICT:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
break;
case FKCONSTR_ACTION_CASCADE:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
break;
case FKCONSTR_ACTION_SETNULL:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
break;
case FKCONSTR_ACTION_SETDEFAULT:
fk_trigger->deferrable = false;
fk_trigger->initdeferred = false;
fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
break;
default:
elog(ERROR, "unrecognized FK action type: %d",
(int) fkconstraint->fk_upd_action);
break;
}
fk_trigger->args = NIL;
(void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
indexOid, true);
/* Make changes-so-far visible */
CommandCounterIncrement();
/*
* Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK
* action for both INSERTs and UPDATEs on the referencing table.
*/
CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
indexOid, true);
CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
indexOid, false);
}
/*
* ALTER TABLE DROP CONSTRAINT
*
* Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
*/
static void
ATExecDropConstraint(Relation rel, const char *constrName,
DropBehavior behavior,
bool recurse, bool recursing,
bool missing_ok, LOCKMODE lockmode)
{
List *children;
ListCell *child;
Relation conrel;
Form_pg_constraint con;
SysScanDesc scan;
ScanKeyData key;
HeapTuple tuple;
bool found = false;
bool is_no_inherit_constraint = false;
/* At top level, permission check was done in ATPrepCmd, else do it */
if (recursing)
ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
/*
* Find and drop the target constraint
*/
ScanKeyInit(&key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(conrel, ConstraintRelidIndexId,
true, NULL, 1, &key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
ObjectAddress conobj;
con = (Form_pg_constraint) GETSTRUCT(tuple);
if (strcmp(NameStr(con->conname), constrName) != 0)
continue;
/* Don't drop inherited constraints */
if (con->coninhcount > 0 && !recursing)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
constrName, RelationGetRelationName(rel))));
is_no_inherit_constraint = con->connoinherit;
/*
* If it's a foreign-key constraint, we'd better lock the referenced
* table and check that that's not in use, just as we've already done
* for the constrained table (else we might, eg, be dropping a trigger
* that has unfired events). But we can/must skip that in the
* self-referential case.
*/
if (con->contype == CONSTRAINT_FOREIGN &&
con->confrelid != RelationGetRelid(rel))
{
Relation frel;
/* Must match lock taken by RemoveTriggerById: */
frel = heap_open(con->confrelid, AccessExclusiveLock);
CheckTableNotInUse(frel, "ALTER TABLE");
heap_close(frel, NoLock);
}
/*
* Perform the actual constraint deletion
*/
conobj.classId = ConstraintRelationId;
conobj.objectId = HeapTupleGetOid(tuple);
conobj.objectSubId = 0;
performDeletion(&conobj, behavior, 0);
found = true;
/* constraint found and dropped -- no need to keep looping */
break;
}
systable_endscan(scan);
if (!found)
{
if (!missing_ok)
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of relation \"%s\" does not exist",
constrName, RelationGetRelationName(rel))));
}
else
{
ereport(NOTICE,
(errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
constrName, RelationGetRelationName(rel))));
heap_close(conrel, RowExclusiveLock);
return;
}
}
/*
* Propagate to children as appropriate. Unlike most other ALTER
* routines, we have to do this one level of recursion at a time; we can't
* use find_all_inheritors to do it in one pass.
*/
if (!is_no_inherit_constraint)
children = find_inheritance_children(RelationGetRelid(rel), lockmode);
else
children = NIL;
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
HeapTuple copy_tuple;
/* find_inheritance_children already got lock */
childrel = heap_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
ScanKeyInit(&key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(childrelid));
scan = systable_beginscan(conrel, ConstraintRelidIndexId,
true, NULL, 1, &key);
/* scan for matching tuple - there should only be one */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
con = (Form_pg_constraint) GETSTRUCT(tuple);
/* Right now only CHECK constraints can be inherited */
if (con->contype != CONSTRAINT_CHECK)
continue;
if (strcmp(NameStr(con->conname), constrName) == 0)
break;
}
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of relation \"%s\" does not exist",
constrName,
RelationGetRelationName(childrel))));
copy_tuple = heap_copytuple(tuple);
systable_endscan(scan);
con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
if (con->coninhcount <= 0) /* shouldn't happen */
elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
childrelid, constrName);
if (recurse)
{
/*
* If the child constraint has other definition sources, just
* decrement its inheritance count; if not, recurse to delete it.
*/
if (con->coninhcount == 1 && !con->conislocal)
{
/* Time to delete this child constraint, too */
ATExecDropConstraint(childrel, constrName, behavior,
true, true,
false, lockmode);
}
else
{
/* Child constraint must survive my deletion */
con->coninhcount--;
simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
CatalogUpdateIndexes(conrel, copy_tuple);
/* Make update visible */
CommandCounterIncrement();
}
}
else
{
/*
* If we were told to drop ONLY in this table (no recursion), we
* need to mark the inheritors' constraints as locally defined
* rather than inherited.
*/
con->coninhcount--;
con->conislocal = true;
simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
CatalogUpdateIndexes(conrel, copy_tuple);
/* Make update visible */
CommandCounterIncrement();
}
heap_freetuple(copy_tuple);
heap_close(childrel, NoLock);
}
heap_close(conrel, RowExclusiveLock);
}
/*
* ALTER COLUMN TYPE
*/
static void
ATPrepAlterColumnType(List **wqueue,
AlteredTableInfo *tab, Relation rel,
bool recurse, bool recursing,
AlterTableCmd *cmd, LOCKMODE lockmode)
{
char *colName = cmd->name;
ColumnDef *def = (ColumnDef *) cmd->def;
TypeName *typeName = def->typeName;
Node *transform = def->cooked_default;
HeapTuple tuple;
Form_pg_attribute attTup;
AttrNumber attnum;
Oid targettype;
int32 targettypmod;
Oid targetcollid;
NewColumnValue *newval;
ParseState *pstate = make_parsestate(NULL);
AclResult aclresult;
if (rel->rd_rel->reloftype && !recursing)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot alter column type of typed table")));
/* lookup the attribute so we can check inheritance status */
tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attTup = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = attTup->attnum;
/* Can't alter a system attribute */
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"",
colName)));
/* Don't alter inherited columns */
if (attTup->attinhcount > 0 && !recursing)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot alter inherited column \"%s\"",
colName)));
/* Look up the target type */
typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
aclresult = pg_type_aclcheck(targettype, GetUserId(), ACL_USAGE);
if (aclresult != ACLCHECK_OK)
aclcheck_error_type(aclresult, targettype);
/* And the collation */
targetcollid = GetColumnDefCollation(NULL, def, targettype);
/* make sure datatype is legal for a column */
CheckAttributeType(colName, targettype, targetcollid,
list_make1_oid(rel->rd_rel->reltype),
false);
if (tab->relkind == RELKIND_RELATION)
{
/*
* Set up an expression to transform the old data value to the new
* type. If a USING option was given, use the expression as
* transformed by transformAlterTableStmt, else just take the old
* value and try to coerce it. We do this first so that type
* incompatibility can be detected before we waste effort, and because
* we need the expression to be parsed against the original table row
* type.
*/
if (!transform)
{
transform = (Node *) makeVar(1, attnum,
attTup->atttypid, attTup->atttypmod,
attTup->attcollation,
0);
}
transform = coerce_to_target_type(pstate,
transform, exprType(transform),
targettype, targettypmod,
COERCION_ASSIGNMENT,
COERCE_IMPLICIT_CAST,
-1);
if (transform == NULL)
{
/* error text depends on whether USING was specified or not */
if (def->cooked_default != NULL)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("result of USING clause for column \"%s\""
" cannot be cast automatically to type %s",
colName, format_type_be(targettype)),
errhint("You might need to add an explicit cast.")));
else
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("column \"%s\" cannot be cast automatically to type %s",
colName, format_type_be(targettype)),
/* translator: USING is SQL, don't translate it */
errhint("You might need to specify \"USING %s::%s\".",
quote_identifier(colName),
format_type_with_typemod(targettype,
targettypmod))));
}
/* Fix collations after all else */
assign_expr_collations(pstate, transform);
/* Plan the expr now so we can accurately assess the need to rewrite. */
transform = (Node *) expression_planner((Expr *) transform);
/*
* Add a work queue item to make ATRewriteTable update the column
* contents.
*/
newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
newval->attnum = attnum;
newval->expr = (Expr *) transform;
tab->newvals = lappend(tab->newvals, newval);
if (ATColumnChangeRequiresRewrite(transform, attnum))
tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
}
else if (transform)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table",
RelationGetRelationName(rel))));
if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
tab->relkind == RELKIND_FOREIGN_TABLE)
{
/*
* For composite types, do this check now. Tables will check it later
* when the table is being rewritten.
*/
find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
}
ReleaseSysCache(tuple);
/*
* Recurse manually by queueing a new command for each child, if
* necessary. We cannot apply ATSimpleRecursion here because we need to
* remap attribute numbers in the USING expression, if any.
*
* If we are told not to recurse, there had better not be any child
* tables; else the alter would put them out of step.
*/
if (recurse)
{
Oid relid = RelationGetRelid(rel);
ListCell *child;
List *children;
children = find_all_inheritors(relid, lockmode, NULL);
/*
* find_all_inheritors does the recursive search of the inheritance
* hierarchy, so all we have to do is process all of the relids in the
* list that it returns.
*/
foreach(child, children)
{
Oid childrelid = lfirst_oid(child);
Relation childrel;
if (childrelid == relid)
continue;
/* find_all_inheritors already got lock */
childrel = relation_open(childrelid, NoLock);
CheckTableNotInUse(childrel, "ALTER TABLE");
/*
* Remap the attribute numbers. If no USING expression was
* specified, there is no need for this step.
*/
if (def->cooked_default)
{
AttrNumber *attmap;
bool found_whole_row;
/* create a copy to scribble on */
cmd = copyObject(cmd);
attmap = convert_tuples_by_name_map(RelationGetDescr(childrel),
RelationGetDescr(rel),
gettext_noop("could not convert row type"));
((ColumnDef *) cmd->def)->cooked_default =
map_variable_attnos(def->cooked_default,
1, 0,
attmap, RelationGetDescr(rel)->natts,
&found_whole_row);
if (found_whole_row)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot convert whole-row table reference"),
errdetail("USING expression contains a whole-row table reference.")));
pfree(attmap);
}
ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
relation_close(childrel, NoLock);
}
}
else if (!recursing &&
find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("type of inherited column \"%s\" must be changed in child tables too",
colName)));
if (tab->relkind == RELKIND_COMPOSITE_TYPE)
ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
}
/*
* When the data type of a column is changed, a rewrite might not be required
* if the new type is sufficiently identical to the old one, and the USING
* clause isn't trying to insert some other value. It's safe to skip the
* rewrite if the old type is binary coercible to the new type, or if the
* new type is an unconstrained domain over the old type. In the case of a
* constrained domain, we could get by with scanning the table and checking
* the constraint rather than actually rewriting it, but we don't currently
* try to do that.
*/
static bool
ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
{
Assert(expr != NULL);
for (;;)
{
/* only one varno, so no need to check that */
if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
return false;
else if (IsA(expr, RelabelType))
expr = (Node *) ((RelabelType *) expr)->arg;
else if (IsA(expr, CoerceToDomain))
{
CoerceToDomain *d = (CoerceToDomain *) expr;
if (DomainHasConstraints(d->resulttype))
return true;
expr = (Node *) d->arg;
}
else
return true;
}
}
/*
* ALTER COLUMN .. SET DATA TYPE
*
* Return the address of the modified column.
*/
static ObjectAddress
ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
AlterTableCmd *cmd, LOCKMODE lockmode)
{
char *colName = cmd->name;
ColumnDef *def = (ColumnDef *) cmd->def;
TypeName *typeName = def->typeName;
HeapTuple heapTup;
Form_pg_attribute attTup;
AttrNumber attnum;
HeapTuple typeTuple;
Form_pg_type tform;
Oid targettype;
int32 targettypmod;
Oid targetcollid;
Node *defaultexpr;
Relation attrelation;
Relation depRel;
ScanKeyData key[3];
SysScanDesc scan;
HeapTuple depTup;
ObjectAddress address;
attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
/* Look up the target column */
heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
attnum = attTup->attnum;
/* Check for multiple ALTER TYPE on same column --- can't cope */
if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type of column \"%s\" twice",
colName)));
/* Look up the target type (should not fail, since prep found it) */
typeTuple = typenameType(NULL, typeName, &targettypmod);
tform = (Form_pg_type) GETSTRUCT(typeTuple);
targettype = HeapTupleGetOid(typeTuple);
/* And the collation */
targetcollid = GetColumnDefCollation(NULL, def, targettype);
/*
* If there is a default expression for the column, get it and ensure we
* can coerce it to the new datatype. (We must do this before changing
* the column type, because build_column_default itself will try to
* coerce, and will not issue the error message we want if it fails.)
*
* We remove any implicit coercion steps at the top level of the old
* default expression; this has been agreed to satisfy the principle of
* least surprise. (The conversion to the new column type should act like
* it started from what the user sees as the stored expression, and the
* implicit coercions aren't going to be shown.)
*/
if (attTup->atthasdef)
{
defaultexpr = build_column_default(rel, attnum);
Assert(defaultexpr);
defaultexpr = strip_implicit_coercions(defaultexpr);
defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
defaultexpr, exprType(defaultexpr),
targettype, targettypmod,
COERCION_ASSIGNMENT,
COERCE_IMPLICIT_CAST,
-1);
if (defaultexpr == NULL)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("default for column \"%s\" cannot be cast automatically to type %s",
colName, format_type_be(targettype))));
}
else
defaultexpr = NULL;
/*
* Find everything that depends on the column (constraints, indexes, etc),
* and record enough information to let us recreate the objects.
*
* The actual recreation does not happen here, but only after we have
* performed all the individual ALTER TYPE operations. We have to save
* the info before executing ALTER TYPE, though, else the deparser will
* get confused.
*
* There could be multiple entries for the same object, so we must check
* to ensure we process each one only once. Note: we assume that an index
* that implements a constraint will not show a direct dependency on the
* column.
*/
depRel = heap_open(DependRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
ScanKeyInit(&key[2],
Anum_pg_depend_refobjsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum((int32) attnum));
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
NULL, 3, key);
while (HeapTupleIsValid(depTup = systable_getnext(scan)))
{
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
ObjectAddress foundObject;
/* We don't expect any PIN dependencies on columns */
if (foundDep->deptype == DEPENDENCY_PIN)
elog(ERROR, "cannot alter type of a pinned column");
foundObject.classId = foundDep->classid;
foundObject.objectId = foundDep->objid;
foundObject.objectSubId = foundDep->objsubid;
switch (getObjectClass(&foundObject))
{
case OCLASS_CLASS:
{
char relKind = get_rel_relkind(foundObject.objectId);
if (relKind == RELKIND_INDEX)
{
Assert(foundObject.objectSubId == 0);
if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
{
tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
foundObject.objectId);
tab->changedIndexDefs = lappend(tab->changedIndexDefs,
pg_get_indexdef_string(foundObject.objectId));
}
}
else if (relKind == RELKIND_SEQUENCE)
{
/*
* This must be a SERIAL column's sequence. We need
* not do anything to it.
*/
Assert(foundObject.objectSubId == 0);
}
else
{
/* Not expecting any other direct dependencies... */
elog(ERROR, "unexpected object depending on column: %s",
getObjectDescription(&foundObject));
}
break;
}
case OCLASS_CONSTRAINT:
Assert(foundObject.objectSubId == 0);
if (!list_member_oid(tab->changedConstraintOids,
foundObject.objectId))
{
char *defstring = pg_get_constraintdef_command(foundObject.objectId);
/*
* Put NORMAL dependencies at the front of the list and
* AUTO dependencies at the back. This makes sure that
* foreign-key constraints depending on this column will
* be dropped before unique or primary-key constraints of
* the column; which we must have because the FK
* constraints depend on the indexes belonging to the
* unique constraints.
*/
if (foundDep->deptype == DEPENDENCY_NORMAL)
{
tab->changedConstraintOids =
lcons_oid(foundObject.objectId,
tab->changedConstraintOids);
tab->changedConstraintDefs =
lcons(defstring,
tab->changedConstraintDefs);
}
else
{
tab->changedConstraintOids =
lappend_oid(tab->changedConstraintOids,
foundObject.objectId);
tab->changedConstraintDefs =
lappend(tab->changedConstraintDefs,
defstring);
}
}
break;
case OCLASS_REWRITE:
/* XXX someday see if we can cope with revising views */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type of a column used by a view or rule"),
errdetail("%s depends on column \"%s\"",
getObjectDescription(&foundObject),
colName)));
break;
case OCLASS_TRIGGER:
/*
* A trigger can depend on a column because the column is
* specified as an update target, or because the column is
* used in the trigger's WHEN condition. The first case would
* not require any extra work, but the second case would
* require updating the WHEN expression, which will take a
* significant amount of new code. Since we can't easily tell
* which case applies, we punt for both. FIXME someday.
*/
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type of a column used in a trigger definition"),
errdetail("%s depends on column \"%s\"",
getObjectDescription(&foundObject),
colName)));
break;
case OCLASS_POLICY:
/*
* A policy can depend on a column because the column is
* specified in the policy's USING or WITH CHECK qual
* expressions. It might be possible to rewrite and recheck
* the policy expression, but punt for now. It's certainly
* easy enough to remove and recreate the policy; still, FIXME
* someday.
*/
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter type of a column used in a policy definition"),
errdetail("%s depends on column \"%s\"",
getObjectDescription(&foundObject),
colName)));
break;
case OCLASS_DEFAULT:
/*
* Ignore the column's default expression, since we will fix
* it below.
*/
Assert(defaultexpr);
break;
case OCLASS_PROC:
case OCLASS_TYPE:
case OCLASS_CAST:
case OCLASS_COLLATION:
case OCLASS_CONVERSION:
case OCLASS_LANGUAGE:
case OCLASS_LARGEOBJECT:
case OCLASS_OPERATOR:
case OCLASS_OPCLASS:
case OCLASS_OPFAMILY:
case OCLASS_AMOP:
case OCLASS_AMPROC:
case OCLASS_SCHEMA:
case OCLASS_TSPARSER:
case OCLASS_TSDICT:
case OCLASS_TSTEMPLATE:
case OCLASS_TSCONFIG:
case OCLASS_ROLE:
case OCLASS_DATABASE:
case OCLASS_TBLSPACE:
case OCLASS_FDW:
case OCLASS_FOREIGN_SERVER:
case OCLASS_USER_MAPPING:
case OCLASS_DEFACL:
case OCLASS_EXTENSION:
/*
* We don't expect any of these sorts of objects to depend on
* a column.
*/
elog(ERROR, "unexpected object depending on column: %s",
getObjectDescription(&foundObject));
break;
default:
elog(ERROR, "unrecognized object class: %u",
foundObject.classId);
}
}
systable_endscan(scan);
/*
* Now scan for dependencies of this column on other things. The only
* thing we should find is the dependency on the column datatype, which we
* want to remove, and possibly a collation dependency.
*/
ScanKeyInit(&key[0],
Anum_pg_depend_classid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_objid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
ScanKeyInit(&key[2],
Anum_pg_depend_objsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum((int32) attnum));
scan = systable_beginscan(depRel, DependDependerIndexId, true,
NULL, 3, key);
while (HeapTupleIsValid(depTup = systable_getnext(scan)))
{
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
if (foundDep->deptype != DEPENDENCY_NORMAL)
elog(ERROR, "found unexpected dependency type '%c'",
foundDep->deptype);
if (!(foundDep->refclassid == TypeRelationId &&
foundDep->refobjid == attTup->atttypid) &&
!(foundDep->refclassid == CollationRelationId &&
foundDep->refobjid == attTup->attcollation))
elog(ERROR, "found unexpected dependency for column");
simple_heap_delete(depRel, &depTup->t_self);
}
systable_endscan(scan);
heap_close(depRel, RowExclusiveLock);
/*
* Here we go --- change the recorded column type and collation. (Note
* heapTup is a copy of the syscache entry, so okay to scribble on.)
*/
attTup->atttypid = targettype;
attTup->atttypmod = targettypmod;
attTup->attcollation = targetcollid;
attTup->attndims = list_length(typeName->arrayBounds);
attTup->attlen = tform->typlen;
attTup->attbyval = tform->typbyval;
attTup->attalign = tform->typalign;
attTup->attstorage = tform->typstorage;
ReleaseSysCache(typeTuple);
simple_heap_update(attrelation, &heapTup->t_self, heapTup);
/* keep system catalog indexes current */
CatalogUpdateIndexes(attrelation, heapTup);
heap_close(attrelation, RowExclusiveLock);
/* Install dependencies on new datatype and collation */
add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
/*
* Drop any pg_statistic entry for the column, since it's now wrong type
*/
RemoveStatistics(RelationGetRelid(rel), attnum);
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel), attnum);
/*
* Update the default, if present, by brute force --- remove and re-add
* the default. Probably unsafe to take shortcuts, since the new version
* may well have additional dependencies. (It's okay to do this now,
* rather than after other ALTER TYPE commands, since the default won't
* depend on other column types.)
*/
if (defaultexpr)
{
/* Must make new row visible since it will be updated again */
CommandCounterIncrement();
/*
* We use RESTRICT here for safety, but at present we do not expect
* anything to depend on the default.
*/
RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
true);
StoreAttrDefault(rel, attnum, defaultexpr, true);
}
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
/* Cleanup */
heap_freetuple(heapTup);
return address;
}
/*
* Returns the address of the modified column
*/
static ObjectAddress
ATExecAlterColumnGenericOptions(Relation rel,
const char *colName,
List *options,
LOCKMODE lockmode)
{
Relation ftrel;
Relation attrel;
ForeignServer *server;
ForeignDataWrapper *fdw;
HeapTuple tuple;
HeapTuple newtuple;
bool isnull;
Datum repl_val[Natts_pg_attribute];
bool repl_null[Natts_pg_attribute];
bool repl_repl[Natts_pg_attribute];
Datum datum;
Form_pg_foreign_table fttableform;
Form_pg_attribute atttableform;
AttrNumber attnum;
ObjectAddress address;
if (options == NIL)
return InvalidObjectAddress;
/* First, determine FDW validator associated to the foreign table. */
ftrel = heap_open(ForeignTableRelationId, AccessShareLock);
tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("foreign table \"%s\" does not exist",
RelationGetRelationName(rel))));
fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
server = GetForeignServer(fttableform->ftserver);
fdw = GetForeignDataWrapper(server->fdwid);
heap_close(ftrel, AccessShareLock);
ReleaseSysCache(tuple);
attrel = heap_open(AttributeRelationId, RowExclusiveLock);
tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
colName, RelationGetRelationName(rel))));
/* Prevent them from altering a system attribute */
atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
attnum = atttableform->attnum;
if (attnum <= 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot alter system column \"%s\"", colName)));
/* Initialize buffers for new tuple values */
memset(repl_val, 0, sizeof(repl_val));
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
/* Extract the current options */
datum = SysCacheGetAttr(ATTNAME,
tuple,
Anum_pg_attribute_attfdwoptions,
&isnull);
if (isnull)
datum = PointerGetDatum(NULL);
/* Transform the options */
datum = transformGenericOptions(AttributeRelationId,
datum,
options,
fdw->fdwvalidator);
if (PointerIsValid(DatumGetPointer(datum)))
repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
else
repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
/* Everything looks good - update the tuple */
newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
repl_val, repl_null, repl_repl);
simple_heap_update(attrel, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(attrel, newtuple);
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel),
atttableform->attnum);
ObjectAddressSubSet(address, RelationRelationId,
RelationGetRelid(rel), attnum);
ReleaseSysCache(tuple);
heap_close(attrel, RowExclusiveLock);
heap_freetuple(newtuple);
return address;
}
/*
* Cleanup after we've finished all the ALTER TYPE operations for a
* particular relation. We have to drop and recreate all the indexes
* and constraints that depend on the altered columns.
*/
static void
ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
{
ObjectAddress obj;
ListCell *def_item;
ListCell *oid_item;
/*
* Re-parse the index and constraint definitions, and attach them to the
* appropriate work queue entries. We do this before dropping because in
* the case of a FOREIGN KEY constraint, we might not yet have exclusive
* lock on the table the constraint is attached to, and we need to get
* that before dropping. It's safe because the parser won't actually look
* at the catalogs to detect the existing entry.
*
* We can't rely on the output of deparsing to tell us which relation to
* operate on, because concurrent activity might have made the name
* resolve differently. Instead, we've got to use the OID of the
* constraint or index we're processing to figure out which relation to
* operate on.
*/
forboth(oid_item, tab->changedConstraintOids,
def_item, tab->changedConstraintDefs)
{
Oid oldId = lfirst_oid(oid_item);
HeapTuple tup;
Form_pg_constraint con;
Oid relid;
Oid confrelid;
bool conislocal;
tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
if (!HeapTupleIsValid(tup)) /* should not happen */
elog(ERROR, "cache lookup failed for constraint %u", oldId);
con = (Form_pg_constraint) GETSTRUCT(tup);
relid = con->conrelid;
confrelid = con->confrelid;
conislocal = con->conislocal;
ReleaseSysCache(tup);
/*
* If the constraint is inherited (only), we don't want to inject a
* new definition here; it'll get recreated when ATAddCheckConstraint
* recurses from adding the parent table's constraint. But we had to
* carry the info this far so that we can drop the constraint below.
*/
if (!conislocal)
continue;
ATPostAlterTypeParse(oldId, relid, confrelid,
(char *) lfirst(def_item),
wqueue, lockmode, tab->rewrite);
}
forboth(oid_item, tab->changedIndexOids,
def_item, tab->changedIndexDefs)
{
Oid oldId = lfirst_oid(oid_item);
Oid relid;
relid = IndexGetRelation(oldId, false);
ATPostAlterTypeParse(oldId, relid, InvalidOid,
(char *) lfirst(def_item),
wqueue, lockmode, tab->rewrite);
}
/*
* Now we can drop the existing constraints and indexes --- constraints
* first, since some of them might depend on the indexes. In fact, we
* have to delete FOREIGN KEY constraints before UNIQUE constraints, but
* we already ordered the constraint list to ensure that would happen. It
* should be okay to use DROP_RESTRICT here, since nothing else should be
* depending on these objects.
*/
foreach(oid_item, tab->changedConstraintOids)
{
obj.classId = ConstraintRelationId;
obj.objectId = lfirst_oid(oid_item);
obj.objectSubId = 0;
performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
}
foreach(oid_item, tab->changedIndexOids)
{
obj.classId = RelationRelationId;
obj.objectId = lfirst_oid(oid_item);
obj.objectSubId = 0;
performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
}
/*
* The objects will get recreated during subsequent passes over the work
* queue.
*/
}
static void
ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
List **wqueue, LOCKMODE lockmode, bool rewrite)
{
List *raw_parsetree_list;
List *querytree_list;
ListCell *list_item;
Relation rel;
/*
* We expect that we will get only ALTER TABLE and CREATE INDEX
* statements. Hence, there is no need to pass them through
* parse_analyze() or the rewriter, but instead we need to pass them
* through parse_utilcmd.c to make them ready for execution.
*/
raw_parsetree_list = raw_parser(cmd);
querytree_list = NIL;
foreach(list_item, raw_parsetree_list)
{
Node *stmt = (Node *) lfirst(list_item);
if (IsA(stmt, IndexStmt))
querytree_list = lappend(querytree_list,
transformIndexStmt(oldRelId,
(IndexStmt *) stmt,
cmd));
else if (IsA(stmt, AlterTableStmt))
querytree_list = list_concat(querytree_list,
transformAlterTableStmt(oldRelId,
(AlterTableStmt *) stmt,
cmd));
else
querytree_list = lappend(querytree_list, stmt);
}
/* Caller should already have acquired whatever lock we need. */
rel = relation_open(oldRelId, NoLock);
/*
* Attach each generated command to the proper place in the work queue.
* Note this could result in creation of entirely new work-queue entries.
*
* Also note that we have to tweak the command subtypes, because it turns
* out that re-creation of indexes and constraints has to act a bit
* differently from initial creation.
*/
foreach(list_item, querytree_list)
{
Node *stm = (Node *) lfirst(list_item);
AlteredTableInfo *tab;
tab = ATGetQueueEntry(wqueue, rel);
if (IsA(stm, IndexStmt))
{
IndexStmt *stmt = (IndexStmt *) stm;
AlterTableCmd *newcmd;
if (!rewrite)
TryReuseIndex(oldId, stmt);
/* keep the index's comment */
stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
newcmd = makeNode(AlterTableCmd);
newcmd->subtype = AT_ReAddIndex;
newcmd->def = (Node *) stmt;
tab->subcmds[AT_PASS_OLD_INDEX] =
lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
}
else if (IsA(stm, AlterTableStmt))
{
AlterTableStmt *stmt = (AlterTableStmt *) stm;
ListCell *lcmd;
foreach(lcmd, stmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
if (cmd->subtype == AT_AddIndex)
{
IndexStmt *indstmt;
Oid indoid;
Assert(IsA(cmd->def, IndexStmt));
indstmt = (IndexStmt *) cmd->def;
indoid = get_constraint_index(oldId);
if (!rewrite)
TryReuseIndex(indoid, indstmt);
/* keep any comment on the index */
indstmt->idxcomment = GetComment(indoid,
RelationRelationId, 0);
cmd->subtype = AT_ReAddIndex;
tab->subcmds[AT_PASS_OLD_INDEX] =
lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
/* recreate any comment on the constraint */
RebuildConstraintComment(tab,
AT_PASS_OLD_INDEX,
oldId,
rel, indstmt->idxname);
}
else if (cmd->subtype == AT_AddConstraint)
{
Constraint *con;
Assert(IsA(cmd->def, Constraint));
con = (Constraint *) cmd->def;
con->old_pktable_oid = refRelId;
/* rewriting neither side of a FK */
if (con->contype == CONSTR_FOREIGN &&
!rewrite && tab->rewrite == 0)
TryReuseForeignKey(oldId, con);
cmd->subtype = AT_ReAddConstraint;
tab->subcmds[AT_PASS_OLD_CONSTR] =
lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
/* recreate any comment on the constraint */
RebuildConstraintComment(tab,
AT_PASS_OLD_CONSTR,
oldId,
rel, con->conname);
}
else
elog(ERROR, "unexpected statement subtype: %d",
(int) cmd->subtype);
}
}
else
elog(ERROR, "unexpected statement type: %d",
(int) nodeTag(stm));
}
relation_close(rel, NoLock);
}
/*
* Subroutine for ATPostAlterTypeParse() to recreate a comment entry for
* a constraint that is being re-added.
*/
static void
RebuildConstraintComment(AlteredTableInfo *tab, int pass, Oid objid,
Relation rel, char *conname)
{
CommentStmt *cmd;
char *comment_str;
AlterTableCmd *newcmd;
/* Look for comment for object wanted, and leave if none */
comment_str = GetComment(objid, ConstraintRelationId, 0);
if (comment_str == NULL)
return;
/* Build node CommentStmt */
cmd = makeNode(CommentStmt);
cmd->objtype = OBJECT_TABCONSTRAINT;
cmd->objname = list_make3(
makeString(get_namespace_name(RelationGetNamespace(rel))),
makeString(pstrdup(RelationGetRelationName(rel))),
makeString(pstrdup(conname)));
cmd->objargs = NIL;
cmd->comment = comment_str;
/* Append it to list of commands */
newcmd = makeNode(AlterTableCmd);
newcmd->subtype = AT_ReAddComment;
newcmd->def = (Node *) cmd;
tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
}
/*
* Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
* for the real analysis, then mutates the IndexStmt based on that verdict.
*/
static void
TryReuseIndex(Oid oldId, IndexStmt *stmt)
{
if (CheckIndexCompatible(oldId,
stmt->accessMethod,
stmt->indexParams,
stmt->excludeOpNames))
{
Relation irel = index_open(oldId, NoLock);
stmt->oldNode = irel->rd_node.relNode;
index_close(irel, NoLock);
}
}
/*
* Subroutine for ATPostAlterTypeParse().
*
* Stash the old P-F equality operator into the Constraint node, for possible
* use by ATAddForeignKeyConstraint() in determining whether revalidation of
* this constraint can be skipped.
*/
static void
TryReuseForeignKey(Oid oldId, Constraint *con)
{
HeapTuple tup;
Datum adatum;
bool isNull;
ArrayType *arr;
Oid *rawarr;
int numkeys;
int i;
Assert(con->contype == CONSTR_FOREIGN);
Assert(con->old_conpfeqop == NIL); /* already prepared this node */
tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
if (!HeapTupleIsValid(tup)) /* should not happen */
elog(ERROR, "cache lookup failed for constraint %u", oldId);
adatum = SysCacheGetAttr(CONSTROID, tup,
Anum_pg_constraint_conpfeqop, &isNull);
if (isNull)
elog(ERROR, "null conpfeqop for constraint %u", oldId);
arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
numkeys = ARR_DIMS(arr)[0];
/* test follows the one in ri_FetchConstraintInfo() */
if (ARR_NDIM(arr) != 1 ||
ARR_HASNULL(arr) ||
ARR_ELEMTYPE(arr) != OIDOID)
elog(ERROR, "conpfeqop is not a 1-D Oid array");
rawarr = (Oid *) ARR_DATA_PTR(arr);
/* stash a List of the operator Oids in our Constraint node */
for (i = 0; i < numkeys; i++)
con->old_conpfeqop = lcons_oid(rawarr[i], con->old_conpfeqop);
ReleaseSysCache(tup);
}
/*
* ALTER TABLE OWNER
*
* recursing is true if we are recursing from a table to its indexes,
* sequences, or toast table. We don't allow the ownership of those things to
* be changed separately from the parent table. Also, we can skip permission
* checks (this is necessary not just an optimization, else we'd fail to
* handle toast tables properly).
*
* recursing is also true if ALTER TYPE OWNER is calling us to fix up a
* free-standing composite type.
*/
void
ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
{
Relation target_rel;
Relation class_rel;
HeapTuple tuple;
Form_pg_class tuple_class;
/*
* Get exclusive lock till end of transaction on the target table. Use
* relation_open so that we can work on indexes and sequences.
*/
target_rel = relation_open(relationOid, lockmode);
/* Get its pg_class tuple, too */
class_rel = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relationOid);
tuple_class = (Form_pg_class) GETSTRUCT(tuple);
/* Can we change the ownership of this tuple? */
switch (tuple_class->relkind)
{
case RELKIND_RELATION:
case RELKIND_VIEW:
case RELKIND_MATVIEW:
case RELKIND_FOREIGN_TABLE:
/* ok to change owner */
break;
case RELKIND_INDEX:
if (!recursing)
{
/*
* Because ALTER INDEX OWNER used to be allowed, and in fact
* is generated by old versions of pg_dump, we give a warning
* and do nothing rather than erroring out. Also, to avoid
* unnecessary chatter while restoring those old dumps, say
* nothing at all if the command would be a no-op anyway.
*/
if (tuple_class->relowner != newOwnerId)
ereport(WARNING,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot change owner of index \"%s\"",
NameStr(tuple_class->relname)),
errhint("Change the ownership of the index's table, instead.")));
/* quick hack to exit via the no-op path */
newOwnerId = tuple_class->relowner;
}
break;
case RELKIND_SEQUENCE:
if (!recursing &&
tuple_class->relowner != newOwnerId)
{
/* if it's an owned sequence, disallow changing it by itself */
Oid tableId;
int32 colId;
if (sequenceIsOwned(relationOid, &tableId, &colId))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot change owner of sequence \"%s\"",
NameStr(tuple_class->relname)),
errdetail("Sequence \"%s\" is linked to table \"%s\".",
NameStr(tuple_class->relname),
get_rel_name(tableId))));
}
break;
case RELKIND_COMPOSITE_TYPE:
if (recursing)
break;
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a composite type",
NameStr(tuple_class->relname)),
errhint("Use ALTER TYPE instead.")));
break;
case RELKIND_TOASTVALUE:
if (recursing)
break;
/* FALL THRU */
default:
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, view, sequence, or foreign table",
NameStr(tuple_class->relname))));
}
/*
* If the new owner is the same as the existing owner, consider the
* command to have succeeded. This is for dump restoration purposes.
*/
if (tuple_class->relowner != newOwnerId)
{
Datum repl_val[Natts_pg_class];
bool repl_null[Natts_pg_class];
bool repl_repl[Natts_pg_class];
Acl *newAcl;
Datum aclDatum;
bool isNull;
HeapTuple newtuple;
/* skip permission checks when recursing to index or toast table */
if (!recursing)
{
/* Superusers can always do it */
if (!superuser())
{
Oid namespaceOid = tuple_class->relnamespace;
AclResult aclresult;
/* Otherwise, must be owner of the existing object */
if (!pg_class_ownercheck(relationOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(target_rel));
/* Must be able to become new owner */
check_is_member_of_role(GetUserId(), newOwnerId);
/* New owner must have CREATE privilege on namespace */
aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(namespaceOid));
}
}
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
repl_repl[Anum_pg_class_relowner - 1] = true;
repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
/*
* Determine the modified ACL for the new owner. This is only
* necessary when the ACL is non-null.
*/
aclDatum = SysCacheGetAttr(RELOID, tuple,
Anum_pg_class_relacl,
&isNull);
if (!isNull)
{
newAcl = aclnewowner(DatumGetAclP(aclDatum),
tuple_class->relowner, newOwnerId);
repl_repl[Anum_pg_class_relacl - 1] = true;
repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
}
newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
simple_heap_update(class_rel, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(class_rel, newtuple);
heap_freetuple(newtuple);
/*
* We must similarly update any per-column ACLs to reflect the new
* owner; for neatness reasons that's split out as a subroutine.
*/
change_owner_fix_column_acls(relationOid,
tuple_class->relowner,
newOwnerId);
/*
* Update owner dependency reference, if any. A composite type has
* none, because it's tracked for the pg_type entry instead of here;
* indexes and TOAST tables don't have their own entries either.
*/
if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
tuple_class->relkind != RELKIND_INDEX &&
tuple_class->relkind != RELKIND_TOASTVALUE)
changeDependencyOnOwner(RelationRelationId, relationOid,
newOwnerId);
/*
* Also change the ownership of the table's row type, if it has one
*/
if (tuple_class->relkind != RELKIND_INDEX)
AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
/*
* If we are operating on a table or materialized view, also change
* the ownership of any indexes and sequences that belong to the
* relation, as well as its toast table (if it has one).
*/
if (tuple_class->relkind == RELKIND_RELATION ||
tuple_class->relkind == RELKIND_MATVIEW ||
tuple_class->relkind == RELKIND_TOASTVALUE)
{
List *index_oid_list;
ListCell *i;
/* Find all the indexes belonging to this relation */
index_oid_list = RelationGetIndexList(target_rel);
/* For each index, recursively change its ownership */
foreach(i, index_oid_list)
ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
list_free(index_oid_list);
}
if (tuple_class->relkind == RELKIND_RELATION ||
tuple_class->relkind == RELKIND_MATVIEW)
{
/* If it has a toast table, recurse to change its ownership */
if (tuple_class->reltoastrelid != InvalidOid)
ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
true, lockmode);
/* If it has dependent sequences, recurse to change them too */
change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
}
}
InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
ReleaseSysCache(tuple);
heap_close(class_rel, RowExclusiveLock);
relation_close(target_rel, NoLock);
}
/*
* change_owner_fix_column_acls
*
* Helper function for ATExecChangeOwner. Scan the columns of the table
* and fix any non-null column ACLs to reflect the new owner.
*/
static void
change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
{
Relation attRelation;
SysScanDesc scan;
ScanKeyData key[1];
HeapTuple attributeTuple;
attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_attribute_attrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relationOid));
scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
true, NULL, 1, key);
while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
{
Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
Datum repl_val[Natts_pg_attribute];
bool repl_null[Natts_pg_attribute];
bool repl_repl[Natts_pg_attribute];
Acl *newAcl;
Datum aclDatum;
bool isNull;
HeapTuple newtuple;
/* Ignore dropped columns */
if (att->attisdropped)
continue;
aclDatum = heap_getattr(attributeTuple,
Anum_pg_attribute_attacl,
RelationGetDescr(attRelation),
&isNull);
/* Null ACLs do not require changes */
if (isNull)
continue;
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
newAcl = aclnewowner(DatumGetAclP(aclDatum),
oldOwnerId, newOwnerId);
repl_repl[Anum_pg_attribute_attacl - 1] = true;
repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
newtuple = heap_modify_tuple(attributeTuple,
RelationGetDescr(attRelation),
repl_val, repl_null, repl_repl);
simple_heap_update(attRelation, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(attRelation, newtuple);
heap_freetuple(newtuple);
}
systable_endscan(scan);
heap_close(attRelation, RowExclusiveLock);
}
/*
* change_owner_recurse_to_sequences
*
* Helper function for ATExecChangeOwner. Examines pg_depend searching
* for sequences that are dependent on serial columns, and changes their
* ownership.
*/
static void
change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
{
Relation depRel;
SysScanDesc scan;
ScanKeyData key[2];
HeapTuple tup;
/*
* SERIAL sequences are those having an auto dependency on one of the
* table's columns (we don't care *which* column, exactly).
*/
depRel = heap_open(DependRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relationOid));
/* we leave refobjsubid unspecified */
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
NULL, 2, key);
while (HeapTupleIsValid(tup = systable_getnext(scan)))
{
Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
Relation seqRel;
/* skip dependencies other than auto dependencies on columns */
if (depForm->refobjsubid == 0 ||
depForm->classid != RelationRelationId ||
depForm->objsubid != 0 ||
depForm->deptype != DEPENDENCY_AUTO)
continue;
/* Use relation_open just in case it's an index */
seqRel = relation_open(depForm->objid, lockmode);
/* skip non-sequence relations */
if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
{
/* No need to keep the lock */
relation_close(seqRel, lockmode);
continue;
}
/* We don't need to close the sequence while we alter it. */
ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
/* Now we can close it. Keep the lock till end of transaction. */
relation_close(seqRel, NoLock);
}
systable_endscan(scan);
relation_close(depRel, AccessShareLock);
}
/*
* ALTER TABLE CLUSTER ON
*
* The only thing we have to do is to change the indisclustered bits.
*
* Return the address of the new clustering index.
*/
static ObjectAddress
ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
{
Oid indexOid;
ObjectAddress address;
indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
if (!OidIsValid(indexOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("index \"%s\" for table \"%s\" does not exist",
indexName, RelationGetRelationName(rel))));
/* Check index is valid to cluster on */
check_index_is_clusterable(rel, indexOid, false, lockmode);
/* And do the work */
mark_index_clustered(rel, indexOid, false);
ObjectAddressSet(address,
RelationRelationId, indexOid);
return address;
}
/*
* ALTER TABLE SET WITHOUT CLUSTER
*
* We have to find any indexes on the table that have indisclustered bit
* set and turn it off.
*/
static void
ATExecDropCluster(Relation rel, LOCKMODE lockmode)
{
mark_index_clustered(rel, InvalidOid, false);
}
/*
* ALTER TABLE SET TABLESPACE
*/
static void
ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
{
Oid tablespaceId;
/* Check that the tablespace exists */
tablespaceId = get_tablespace_oid(tablespacename, false);
/* Check permissions except when moving to database's default */
if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
{
AclResult aclresult;
aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
}
/* Save info for Phase 3 to do the real work */
if (OidIsValid(tab->newTableSpace))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("cannot have multiple SET TABLESPACE subcommands")));
tab->newTableSpace = tablespaceId;
}
/*
* Set, reset, or replace reloptions.
*/
static void
ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
LOCKMODE lockmode)
{
Oid relid;
Relation pgclass;
HeapTuple tuple;
HeapTuple newtuple;
Datum datum;
bool isnull;
Datum newOptions;
Datum repl_val[Natts_pg_class];
bool repl_null[Natts_pg_class];
bool repl_repl[Natts_pg_class];
static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
if (defList == NIL && operation != AT_ReplaceRelOptions)
return; /* nothing to do */
pgclass = heap_open(RelationRelationId, RowExclusiveLock);
/* Fetch heap tuple */
relid = RelationGetRelid(rel);
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
if (operation == AT_ReplaceRelOptions)
{
/*
* If we're supposed to replace the reloptions list, we just pretend
* there were none before.
*/
datum = (Datum) 0;
isnull = true;
}
else
{
/* Get the old reloptions */
datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
&isnull);
}
/* Generate new proposed reloptions (text array) */
newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
defList, NULL, validnsps, false,
operation == AT_ResetRelOptions);
/* Validate */
switch (rel->rd_rel->relkind)
{
case RELKIND_RELATION:
case RELKIND_TOASTVALUE:
case RELKIND_MATVIEW:
(void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
break;
case RELKIND_VIEW:
(void) view_reloptions(newOptions, true);
break;
case RELKIND_INDEX:
(void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
break;
default:
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, view, materialized view, index, or TOAST table",
RelationGetRelationName(rel))));
break;
}
/* Special-case validation of view options */
if (rel->rd_rel->relkind == RELKIND_VIEW)
{
Query *view_query = get_view_query(rel);
List *view_options = untransformRelOptions(newOptions);
ListCell *cell;
bool check_option = false;
foreach(cell, view_options)
{
DefElem *defel = (DefElem *) lfirst(cell);
if (pg_strcasecmp(defel->defname, "check_option") == 0)
check_option = true;
}
/*
* If the check option is specified, look to see if the view is
* actually auto-updatable or not.
*/
if (check_option)
{
const char *view_updatable_error =
view_query_is_auto_updatable(view_query, true);
if (view_updatable_error)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
errhint("%s", view_updatable_error)));
}
}
/*
* All we need do here is update the pg_class row; the new options will be
* propagated into relcaches during post-commit cache inval.
*/
memset(repl_val, 0, sizeof(repl_val));
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
if (newOptions != (Datum) 0)
repl_val[Anum_pg_class_reloptions - 1] = newOptions;
else
repl_null[Anum_pg_class_reloptions - 1] = true;
repl_repl[Anum_pg_class_reloptions - 1] = true;
newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
repl_val, repl_null, repl_repl);
simple_heap_update(pgclass, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(pgclass, newtuple);
InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
heap_freetuple(newtuple);
ReleaseSysCache(tuple);
/* repeat the whole exercise for the toast table, if there's one */
if (OidIsValid(rel->rd_rel->reltoastrelid))
{
Relation toastrel;
Oid toastid = rel->rd_rel->reltoastrelid;
toastrel = heap_open(toastid, lockmode);
/* Fetch heap tuple */
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", toastid);
if (operation == AT_ReplaceRelOptions)
{
/*
* If we're supposed to replace the reloptions list, we just
* pretend there were none before.
*/
datum = (Datum) 0;
isnull = true;
}
else
{
/* Get the old reloptions */
datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
&isnull);
}
newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
defList, "toast", validnsps, false,
operation == AT_ResetRelOptions);
(void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
memset(repl_val, 0, sizeof(repl_val));
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
if (newOptions != (Datum) 0)
repl_val[Anum_pg_class_reloptions - 1] = newOptions;
else
repl_null[Anum_pg_class_reloptions - 1] = true;
repl_repl[Anum_pg_class_reloptions - 1] = true;
newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
repl_val, repl_null, repl_repl);
simple_heap_update(pgclass, &newtuple->t_self, newtuple);
CatalogUpdateIndexes(pgclass, newtuple);
InvokeObjectPostAlterHookArg(RelationRelationId,
RelationGetRelid(toastrel), 0,
InvalidOid, true);
heap_freetuple(newtuple);
ReleaseSysCache(tuple);
heap_close(toastrel, NoLock);
}
heap_close(pgclass, RowExclusiveLock);
}
/*
* Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
* rewriting to be done, so we just want to copy the data as fast as possible.
*/
static void
ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
{
Relation rel;
Oid oldTableSpace;
Oid reltoastrelid;
Oid newrelfilenode;
RelFileNode newrnode;
SMgrRelation dstrel;
Relation pg_class;
HeapTuple tuple;
Form_pg_class rd_rel;
ForkNumber forkNum;
List *reltoastidxids = NIL;
ListCell *lc;
/*
* Need lock here in case we are recursing to toast table or index
*/
rel = relation_open(tableOid, lockmode);
/*
* No work if no change in tablespace.
*/
oldTableSpace = rel->rd_rel->reltablespace;
if (newTableSpace == oldTableSpace ||
(newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
{
InvokeObjectPostAlterHook(RelationRelationId,
RelationGetRelid(rel), 0);
relation_close(rel, NoLock);
return;
}
/*
* We cannot support moving mapped relations into different tablespaces.
* (In particular this eliminates all shared catalogs.)
*/
if (RelationIsMapped(rel))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot move system relation \"%s\"",
RelationGetRelationName(rel))));
/* Can't move a non-shared relation into pg_global */
if (newTableSpace == GLOBALTABLESPACE_OID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("only shared relations can be placed in pg_global tablespace")));
/*
* Don't allow moving temp tables of other backends ... their local buffer
* manager is not going to cope.
*/
if (RELATION_IS_OTHER_TEMP(rel))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot move temporary tables of other sessions")));
reltoastrelid = rel->rd_rel->reltoastrelid;
/* Fetch the list of indexes on toast relation if necessary */
if (OidIsValid(reltoastrelid))
{
Relation toastRel = relation_open(reltoastrelid, lockmode);
reltoastidxids = RelationGetIndexList(toastRel);
relation_close(toastRel, lockmode);
}
/* Get a modifiable copy of the relation's pg_class row */
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", tableOid);
rd_rel = (Form_pg_class) GETSTRUCT(tuple);
/*
* Since we copy the file directly without looking at the shared buffers,
* we'd better first flush out any pages of the source relation that are
* in shared buffers. We assume no new changes will be made while we are
* holding exclusive lock on the rel.
*/
FlushRelationBuffers(rel);
/*
* Relfilenodes are not unique in databases across tablespaces, so we need
* to allocate a new one in the new tablespace.
*/
newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
rel->rd_rel->relpersistence);
/* Open old and new relation */
newrnode = rel->rd_node;
newrnode.relNode = newrelfilenode;
newrnode.spcNode = newTableSpace;
dstrel = smgropen(newrnode, rel->rd_backend);
RelationOpenSmgr(rel);
/*
* Create and copy all forks of the relation, and schedule unlinking of
* old physical files.
*
* NOTE: any conflict in relfilenode value will be caught in
* RelationCreateStorage().
*/
RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
/* copy main fork */
copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
rel->rd_rel->relpersistence);
/* copy those extra forks that exist */
for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
{
if (smgrexists(rel->rd_smgr, forkNum))
{
smgrcreate(dstrel, forkNum, false);
/*
* WAL log creation if the relation is persistent, or this is the
* init fork of an unlogged relation.
*/
if (rel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT ||
(rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
forkNum == INIT_FORKNUM))
log_smgrcreate(&newrnode, forkNum);
copy_relation_data(rel->rd_smgr, dstrel, forkNum,
rel->rd_rel->relpersistence);
}
}
/* drop old relation, and close new one */
RelationDropStorage(rel);
smgrclose(dstrel);
/* update the pg_class row */
rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
rd_rel->relfilenode = newrelfilenode;
simple_heap_update(pg_class, &tuple->t_self, tuple);
CatalogUpdateIndexes(pg_class, tuple);
InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
heap_freetuple(tuple);
heap_close(pg_class, RowExclusiveLock);
relation_close(rel, NoLock);
/* Make sure the reltablespace change is visible */
CommandCounterIncrement();
/* Move associated toast relation and/or indexes, too */
if (OidIsValid(reltoastrelid))
ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
foreach(lc, reltoastidxids)
ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
/* Clean up */
list_free(reltoastidxids);
}
/*
* Alter Table ALL ... SET TABLESPACE
*
* Allows a user to move all objects of some type in a given tablespace in the
* current database to another tablespace. Objects can be chosen based on the
* owner of the object also, to allow users to move only their objects.
* The user must have CREATE rights on the new tablespace, as usual. The main
* permissions handling is done by the lower-level table move function.
*
* All to-be-moved objects are locked first. If NOWAIT is specified and the
* lock can't be acquired then we ereport(ERROR).
*/
Oid
AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
{
List *relations = NIL;
ListCell *l;
ScanKeyData key[1];
Relation rel;
HeapScanDesc scan;
HeapTuple tuple;
Oid orig_tablespaceoid;
Oid new_tablespaceoid;
List *role_oids = roleSpecsToIds(stmt->roles);
/* Ensure we were not asked to move something we can't */
if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
stmt->objtype != OBJECT_MATVIEW)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("only tables, indexes, and materialized views exist in tablespaces")));
/* Get the orig and new tablespace OIDs */
orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
/* Can't move shared relations in to or out of pg_global */
/* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
new_tablespaceoid == GLOBALTABLESPACE_OID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot move relations in to or out of pg_global tablespace")));
/*
* Must have CREATE rights on the new tablespace, unless it is the
* database default tablespace (which all users implicitly have CREATE
* rights on).
*/
if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
{
AclResult aclresult;
aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
get_tablespace_name(new_tablespaceoid));
}
/*
* Now that the checks are done, check if we should set either to
* InvalidOid because it is our database's default tablespace.
*/
if (orig_tablespaceoid == MyDatabaseTableSpace)
orig_tablespaceoid = InvalidOid;
if (new_tablespaceoid == MyDatabaseTableSpace)
new_tablespaceoid = InvalidOid;
/* no-op */
if (orig_tablespaceoid == new_tablespaceoid)
return new_tablespaceoid;
/*
* Walk the list of objects in the tablespace and move them. This will
* only find objects in our database, of course.
*/
ScanKeyInit(&key[0],
Anum_pg_class_reltablespace,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(orig_tablespaceoid));
rel = heap_open(RelationRelationId, AccessShareLock);
scan = heap_beginscan_catalog(rel, 1, key);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
Oid relOid = HeapTupleGetOid(tuple);
Form_pg_class relForm;
relForm = (Form_pg_class) GETSTRUCT(tuple);
/*
* Do not move objects in pg_catalog as part of this, if an admin
* really wishes to do so, they can issue the individual ALTER
* commands directly.
*
* Also, explicitly avoid any shared tables, temp tables, or TOAST
* (TOAST will be moved with the main table).
*/
if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
isAnyTempNamespace(relForm->relnamespace) ||
relForm->relnamespace == PG_TOAST_NAMESPACE)
continue;
/* Only move the object type requested */
if ((stmt->objtype == OBJECT_TABLE &&
relForm->relkind != RELKIND_RELATION) ||
(stmt->objtype == OBJECT_INDEX &&
relForm->relkind != RELKIND_INDEX) ||
(stmt->objtype == OBJECT_MATVIEW &&
relForm->relkind != RELKIND_MATVIEW))
continue;
/* Check if we are only moving objects owned by certain roles */
if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
continue;
/*
* Handle permissions-checking here since we are locking the tables
* and also to avoid doing a bunch of work only to fail part-way. Note
* that permissions will also be checked by AlterTableInternal().
*
* Caller must be considered an owner on the table to move it.
*/
if (!pg_class_ownercheck(relOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
NameStr(relForm->relname));
if (stmt->nowait &&
!ConditionalLockRelationOid(relOid, AccessExclusiveLock))
ereport(ERROR,
(errcode(ERRCODE_OBJECT_IN_USE),
errmsg("aborting because lock on relation \"%s.%s\" is not available",
get_namespace_name(relForm->relnamespace),
NameStr(relForm->relname))));
else
LockRelationOid(relOid, AccessExclusiveLock);
/* Add to our list of objects to move */
relations = lappend_oid(relations, relOid);
}
heap_endscan(scan);
heap_close(rel, AccessShareLock);
if (relations == NIL)
ereport(NOTICE,
(errcode(ERRCODE_NO_DATA_FOUND),
errmsg("no matching relations in tablespace \"%s\" found",
orig_tablespaceoid == InvalidOid ? "(database default)" :
get_tablespace_name(orig_tablespaceoid))));
/* Everything is locked, loop through and move all of the relations. */
foreach(l, relations)
{
List *cmds = NIL;
AlterTableCmd *cmd = makeNode(AlterTableCmd);
cmd->subtype = AT_SetTableSpace;
cmd->name = stmt->new_tablespacename;
cmds = lappend(cmds, cmd);
EventTriggerAlterTableStart((Node *) stmt);
/* OID is set by AlterTableInternal */
AlterTableInternal(lfirst_oid(l), cmds, false);
EventTriggerAlterTableEnd();
}
return new_tablespaceoid;
}
/*
* Copy data, block by block
*/
static void
copy_relation_data(SMgrRelation src, SMgrRelation dst,
ForkNumber forkNum, char relpersistence)
{
char *buf;
Page page;
bool use_wal;
bool copying_initfork;
BlockNumber nblocks;
BlockNumber blkno;
/*
* palloc the buffer so that it's MAXALIGN'd. If it were just a local
* char[] array, the compiler might align it on any byte boundary, which
* can seriously hurt transfer speed to and from the kernel; not to
* mention possibly making log_newpage's accesses to the page header fail.
*/
buf = (char *) palloc(BLCKSZ);
page = (Page) buf;
/*
* The init fork for an unlogged relation in many respects has to be
* treated the same as normal relation, changes need to be WAL logged and
* it needs to be synced to disk.
*/
copying_initfork = relpersistence == RELPERSISTENCE_UNLOGGED &&
forkNum == INIT_FORKNUM;
/*
* We need to log the copied data in WAL iff WAL archiving/streaming is
* enabled AND it's a permanent relation.
*/
use_wal = XLogIsNeeded() &&
(relpersistence == RELPERSISTENCE_PERMANENT || copying_initfork);
nblocks = smgrnblocks(src, forkNum);
for (blkno = 0; blkno < nblocks; blkno++)
{
/* If we got a cancel signal during the copy of the data, quit */
CHECK_FOR_INTERRUPTS();
smgrread(src, forkNum, blkno, buf);
if (!PageIsVerified(page, blkno))
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg("invalid page in block %u of relation %s",
blkno,
relpathbackend(src->smgr_rnode.node,
src->smgr_rnode.backend,
forkNum))));
/*
* WAL-log the copied page. Unfortunately we don't know what kind of a
* page this is, so we have to log the full page including any unused
* space.
*/
if (use_wal)
log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page, false);
PageSetChecksumInplace(page, blkno);
/*
* Now write the page. We say isTemp = true even if it's not a temp
* rel, because there's no need for smgr to schedule an fsync for this
* write; we'll do it ourselves below.
*/
smgrextend(dst, forkNum, blkno, buf, true);
}
pfree(buf);
/*
* If the rel is WAL-logged, must fsync before commit. We use heap_sync
* to ensure that the toast table gets fsync'd too. (For a temp or
* unlogged rel we don't care since the data will be gone after a crash
* anyway.)
*
* It's obvious that we must do this when not WAL-logging the copy. It's
* less obvious that we have to do it even if we did WAL-log the copied
* pages. The reason is that since we're copying outside shared buffers, a
* CHECKPOINT occurring during the copy has no way to flush the previously
* written data to disk (indeed it won't know the new rel even exists). A
* crash later on would replay WAL from the checkpoint, therefore it
* wouldn't replay our earlier WAL entries. If we do not fsync those pages
* here, they might still not be on disk when the crash occurs.
*/
if (relpersistence == RELPERSISTENCE_PERMANENT || copying_initfork)
smgrimmedsync(dst, forkNum);
}
/*
* ALTER TABLE ENABLE/DISABLE TRIGGER
*
* We just pass this off to trigger.c.
*/
static void
ATExecEnableDisableTrigger(Relation rel, char *trigname,
char fires_when, bool skip_system, LOCKMODE lockmode)
{
EnableDisableTrigger(rel, trigname, fires_when, skip_system);
}
/*
* ALTER TABLE ENABLE/DISABLE RULE
*
* We just pass this off to rewriteDefine.c.
*/
static void
ATExecEnableDisableRule(Relation rel, char *trigname,
char fires_when, LOCKMODE lockmode)
{
EnableDisableRule(rel, trigname, fires_when);
}
/*
* ALTER TABLE INHERIT
*
* Add a parent to the child's parents. This verifies that all the columns and
* check constraints of the parent appear in the child and that they have the
* same data types and expressions.
*/
static void
ATPrepAddInherit(Relation child_rel)
{
if (child_rel->rd_rel->reloftype)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot change inheritance of typed table")));
}
/*
* Return the address of the new parent relation.
*/
static ObjectAddress
ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
{
Relation parent_rel,
catalogRelation;
SysScanDesc scan;
ScanKeyData key;
HeapTuple inheritsTuple;
int32 inhseqno;
List *children;
ObjectAddress address;
/*
* A self-exclusive lock is needed here. See the similar case in
* MergeAttributes() for a full explanation.
*/
parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
/*
* Must be owner of both parent and child -- child was checked by
* ATSimplePermissions call in ATPrepCmd
*/
ATSimplePermissions(parent_rel, ATT_TABLE | ATT_FOREIGN_TABLE);
/* Permanent rels cannot inherit from temporary ones */
if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot inherit from temporary relation \"%s\"",
RelationGetRelationName(parent_rel))));
/* If parent rel is temp, it must belong to this session */
if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
!parent_rel->rd_islocaltemp)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot inherit from temporary relation of another session")));
/* Ditto for the child */
if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
!child_rel->rd_islocaltemp)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot inherit to temporary relation of another session")));
/*
* Check for duplicates in the list of parents, and determine the highest
* inhseqno already present; we'll use the next one for the new parent.
* (Note: get RowExclusiveLock because we will write pg_inherits below.)
*
* Note: we do not reject the case where the child already inherits from
* the parent indirectly; CREATE TABLE doesn't reject comparable cases.
*/
catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
ScanKeyInit(&key,
Anum_pg_inherits_inhrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(child_rel)));
scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
true, NULL, 1, &key);
/* inhseqno sequences start at 1 */
inhseqno = 0;
while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
{
Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
if (inh->inhparent == RelationGetRelid(parent_rel))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" would be inherited from more than once",
RelationGetRelationName(parent_rel))));
if (inh->inhseqno > inhseqno)
inhseqno = inh->inhseqno;
}
systable_endscan(scan);
/*
* Prevent circularity by seeing if proposed parent inherits from child.
* (In particular, this disallows making a rel inherit from itself.)
*
* This is not completely bulletproof because of race conditions: in
* multi-level inheritance trees, someone else could concurrently be
* making another inheritance link that closes the loop but does not join
* either of the rels we have locked. Preventing that seems to require
* exclusive locks on the entire inheritance tree, which is a cure worse
* than the disease. find_all_inheritors() will cope with circularity
* anyway, so don't sweat it too much.
*
* We use weakest lock we can on child's children, namely AccessShareLock.
*/
children = find_all_inheritors(RelationGetRelid(child_rel),
AccessShareLock, NULL);
if (list_member_oid(children, RelationGetRelid(parent_rel)))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("circular inheritance not allowed"),
errdetail("\"%s\" is already a child of \"%s\".",
parent->relname,
RelationGetRelationName(child_rel))));
/* If parent has OIDs then child must have OIDs */
if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
RelationGetRelationName(child_rel),
RelationGetRelationName(parent_rel))));
/* Match up the columns and bump attinhcount as needed */
MergeAttributesIntoExisting(child_rel, parent_rel);
/* Match up the constraints and bump coninhcount as needed */
MergeConstraintsIntoExisting(child_rel, parent_rel);
/*
* OK, it looks valid. Make the catalog entries that show inheritance.
*/
StoreCatalogInheritance1(RelationGetRelid(child_rel),
RelationGetRelid(parent_rel),
inhseqno + 1,
catalogRelation);
ObjectAddressSet(address, RelationRelationId,
RelationGetRelid(parent_rel));
/* Now we're done with pg_inherits */
heap_close(catalogRelation, RowExclusiveLock);
/* keep our lock on the parent relation until commit */
heap_close(parent_rel, NoLock);
return address;
}
/*
* Obtain the source-text form of the constraint expression for a check
* constraint, given its pg_constraint tuple
*/
static char *
decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
{
Form_pg_constraint con;
bool isnull;
Datum attr;
Datum expr;
con = (Form_pg_constraint) GETSTRUCT(contup);
attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
if (isnull)
elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
expr = DirectFunctionCall2(pg_get_expr, attr,
ObjectIdGetDatum(con->conrelid));
return TextDatumGetCString(expr);
}
/*
* Determine whether two check constraints are functionally equivalent
*
* The test we apply is to see whether they reverse-compile to the same
* source string. This insulates us from issues like whether attributes
* have the same physical column numbers in parent and child relations.
*/
static bool
constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
{
Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
if (acon->condeferrable != bcon->condeferrable ||
acon->condeferred != bcon->condeferred ||
strcmp(decompile_conbin(a, tupleDesc),
decompile_conbin(b, tupleDesc)) != 0)
return false;
else
return true;
}
/*
* Check columns in child table match up with columns in parent, and increment
* their attinhcount.
*
* Called by ATExecAddInherit
*
* Currently all parent columns must be found in child. Missing columns are an
* error. One day we might consider creating new columns like CREATE TABLE
* does. However, that is widely unpopular --- in the common use case of
* partitioned tables it's a foot-gun.
*
* The data type must match exactly. If the parent column is NOT NULL then
* the child must be as well. Defaults are not compared, however.
*/
static void
MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
{
Relation attrrel;
AttrNumber parent_attno;
int parent_natts;
TupleDesc tupleDesc;
HeapTuple tuple;
attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
tupleDesc = RelationGetDescr(parent_rel);
parent_natts = tupleDesc->natts;
for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
{
Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
char *attributeName = NameStr(attribute->attname);
/* Ignore dropped columns in the parent. */
if (attribute->attisdropped)
continue;
/* Find same column in child (matching on column name). */
tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
attributeName);
if (HeapTupleIsValid(tuple))
{
/* Check they are same type, typmod, and collation */
Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
if (attribute->atttypid != childatt->atttypid ||
attribute->atttypmod != childatt->atttypmod)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table \"%s\" has different type for column \"%s\"",
RelationGetRelationName(child_rel),
attributeName)));
if (attribute->attcollation != childatt->attcollation)
ereport(ERROR,
(errcode(ERRCODE_COLLATION_MISMATCH),
errmsg("child table \"%s\" has different collation for column \"%s\"",
RelationGetRelationName(child_rel),
attributeName)));
/*
* Check child doesn't discard NOT NULL property. (Other
* constraints are checked elsewhere.)
*/
if (attribute->attnotnull && !childatt->attnotnull)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("column \"%s\" in child table must be marked NOT NULL",
attributeName)));
/*
* OK, bump the child column's inheritance count. (If we fail
* later on, this change will just roll back.)
*/
childatt->attinhcount++;
simple_heap_update(attrrel, &tuple->t_self, tuple);
CatalogUpdateIndexes(attrrel, tuple);
heap_freetuple(tuple);
}
else
{
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table is missing column \"%s\"",
attributeName)));
}
}
/*
* If the parent has an OID column, so must the child, and we'd better
* update the child's attinhcount and attislocal the same as for normal
* columns. We needn't check data type or not-nullness though.
*/
if (tupleDesc->tdhasoid)
{
/*
* Here we match by column number not name; the match *must* be the
* system column, not some random column named "oid".
*/
tuple = SearchSysCacheCopy2(ATTNUM,
ObjectIdGetDatum(RelationGetRelid(child_rel)),
Int16GetDatum(ObjectIdAttributeNumber));
if (HeapTupleIsValid(tuple))
{
Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
/* See comments above; these changes should be the same */
childatt->attinhcount++;
simple_heap_update(attrrel, &tuple->t_self, tuple);
CatalogUpdateIndexes(attrrel, tuple);
heap_freetuple(tuple);
}
else
{
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table is missing column \"%s\"",
"oid")));
}
}
heap_close(attrrel, RowExclusiveLock);
}
/*
* Check constraints in child table match up with constraints in parent,
* and increment their coninhcount.
*
* Constraints that are marked ONLY in the parent are ignored.
*
* Called by ATExecAddInherit
*
* Currently all constraints in parent must be present in the child. One day we
* may consider adding new constraints like CREATE TABLE does.
*
* XXX This is O(N^2) which may be an issue with tables with hundreds of
* constraints. As long as tables have more like 10 constraints it shouldn't be
* a problem though. Even 100 constraints ought not be the end of the world.
*
* XXX See MergeWithExistingConstraint too if you change this code.
*/
static void
MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
{
Relation catalog_relation;
TupleDesc tuple_desc;
SysScanDesc parent_scan;
ScanKeyData parent_key;
HeapTuple parent_tuple;
catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
tuple_desc = RelationGetDescr(catalog_relation);
/* Outer loop scans through the parent's constraint definitions */
ScanKeyInit(&parent_key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(parent_rel)));
parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
true, NULL, 1, &parent_key);
while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
{
Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
SysScanDesc child_scan;
ScanKeyData child_key;
HeapTuple child_tuple;
bool found = false;
if (parent_con->contype != CONSTRAINT_CHECK)
continue;
/* if the parent's constraint is marked NO INHERIT, it's not inherited */
if (parent_con->connoinherit)
continue;
/* Search for a child constraint matching this one */
ScanKeyInit(&child_key,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(child_rel)));
child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
true, NULL, 1, &child_key);
while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
{
Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
HeapTuple child_copy;
if (child_con->contype != CONSTRAINT_CHECK)
continue;
if (strcmp(NameStr(parent_con->conname),
NameStr(child_con->conname)) != 0)
continue;
if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
RelationGetRelationName(child_rel),
NameStr(parent_con->conname))));
/* If the child constraint is "no inherit" then cannot merge */
if (child_con->connoinherit)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
NameStr(child_con->conname),
RelationGetRelationName(child_rel))));
/*
* If the child constraint is "not valid" then cannot merge with a
* valid parent constraint
*/
if (parent_con->convalidated && !child_con->convalidated)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
NameStr(child_con->conname),
RelationGetRelationName(child_rel))));
/*
* OK, bump the child constraint's inheritance count. (If we fail
* later on, this change will just roll back.)
*/
child_copy = heap_copytuple(child_tuple);
child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
child_con->coninhcount++;
simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
CatalogUpdateIndexes(catalog_relation, child_copy);
heap_freetuple(child_copy);
found = true;
break;
}
systable_endscan(child_scan);
if (!found)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("child table is missing constraint \"%s\"",
NameStr(parent_con->conname))));
}
systable_endscan(parent_scan);
heap_close(catalog_relation, RowExclusiveLock);
}
/*
* ALTER TABLE NO INHERIT
*
* Drop a parent from the child's parents. This just adjusts the attinhcount
* and attislocal of the columns and removes the pg_inherit and pg_depend
* entries.
*
* If attinhcount goes to 0 then attislocal gets set to true. If it goes back
* up attislocal stays true, which means if a child is ever removed from a
* parent then its columns will never be automatically dropped which may
* surprise. But at least we'll never surprise by dropping columns someone
* isn't expecting to be dropped which would actually mean data loss.
*
* coninhcount and conislocal for inherited constraints are adjusted in
* exactly the same way.
*
* Return value is the address of the relation that is no longer parent.
*/
static ObjectAddress
ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
{
Relation parent_rel;
Oid parent_oid;
Relation catalogRelation;
SysScanDesc scan;
ScanKeyData key[3];
HeapTuple inheritsTuple,
attributeTuple,
constraintTuple;
List *connames;
bool found = false;
ObjectAddress address;
/*
* AccessShareLock on the parent is probably enough, seeing that DROP
* TABLE doesn't lock parent tables at all. We need some lock since we'll
* be inspecting the parent's schema.
*/
parent_rel = heap_openrv(parent, AccessShareLock);
/*
* We don't bother to check ownership of the parent table --- ownership of
* the child is presumed enough rights.
*/
/*
* Find and destroy the pg_inherits entry linking the two, or error out if
* there is none.
*/
catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_inherits_inhrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
true, NULL, 1, key);
while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
{
Oid inhparent;
inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
if (inhparent == RelationGetRelid(parent_rel))
{
simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
found = true;
break;
}
}
systable_endscan(scan);
heap_close(catalogRelation, RowExclusiveLock);
if (!found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("relation \"%s\" is not a parent of relation \"%s\"",
RelationGetRelationName(parent_rel),
RelationGetRelationName(rel))));
/*
* Search through child columns looking for ones matching parent rel
*/
catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_attribute_attrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
true, NULL, 1, key);
while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
{
Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
/* Ignore if dropped or not inherited */
if (att->attisdropped)
continue;
if (att->attinhcount <= 0)
continue;
if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
NameStr(att->attname)))
{
/* Decrement inhcount and possibly set islocal to true */
HeapTuple copyTuple = heap_copytuple(attributeTuple);
Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
copy_att->attinhcount--;
if (copy_att->attinhcount == 0)
copy_att->attislocal = true;
simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
CatalogUpdateIndexes(catalogRelation, copyTuple);
heap_freetuple(copyTuple);
}
}
systable_endscan(scan);
heap_close(catalogRelation, RowExclusiveLock);
/*
* Likewise, find inherited check constraints and disinherit them. To do
* this, we first need a list of the names of the parent's check
* constraints. (We cheat a bit by only checking for name matches,
* assuming that the expressions will match.)
*/
catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(parent_rel)));
scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
true, NULL, 1, key);
connames = NIL;
while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
{
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
if (con->contype == CONSTRAINT_CHECK)
connames = lappend(connames, pstrdup(NameStr(con->conname)));
}
systable_endscan(scan);
/* Now scan the child's constraints */
ScanKeyInit(&key[0],
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
true, NULL, 1, key);
while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
{
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
bool match;
ListCell *lc;
if (con->contype != CONSTRAINT_CHECK)
continue;
match = false;
foreach(lc, connames)
{
if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
{
match = true;
break;
}
}
if (match)
{
/* Decrement inhcount and possibly set islocal to true */
HeapTuple copyTuple = heap_copytuple(constraintTuple);
Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
if (copy_con->coninhcount <= 0) /* shouldn't happen */
elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
RelationGetRelid(rel), NameStr(copy_con->conname));
copy_con->coninhcount--;
if (copy_con->coninhcount == 0)
copy_con->conislocal = true;
simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
CatalogUpdateIndexes(catalogRelation, copyTuple);
heap_freetuple(copyTuple);
}
}
parent_oid = RelationGetRelid(parent_rel);
systable_endscan(scan);
heap_close(catalogRelation, RowExclusiveLock);
drop_parent_dependency(RelationGetRelid(rel),
RelationRelationId,
RelationGetRelid(parent_rel));
/*
* Post alter hook of this inherits. Since object_access_hook doesn't take
* multiple object identifiers, we relay oid of parent relation using
* auxiliary_id argument.
*/
InvokeObjectPostAlterHookArg(InheritsRelationId,
RelationGetRelid(rel), 0,
RelationGetRelid(parent_rel), false);
/* keep our lock on the parent relation until commit */
heap_close(parent_rel, NoLock);
ObjectAddressSet(address, RelationRelationId, parent_oid);
return address;
}
/*
* Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
* INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
* heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
* be TypeRelationId). There's no convenient way to do this, so go trawling
* through pg_depend.
*/
static void
drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
{
Relation catalogRelation;
SysScanDesc scan;
ScanKeyData key[3];
HeapTuple depTuple;
catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_pg_depend_classid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_objid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid));
ScanKeyInit(&key[2],
Anum_pg_depend_objsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum(0));
scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
NULL, 3, key);
while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
{
Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
if (dep->refclassid == refclassid &&
dep->refobjid == refobjid &&
dep->refobjsubid == 0 &&
dep->deptype == DEPENDENCY_NORMAL)
simple_heap_delete(catalogRelation, &depTuple->t_self);
}
systable_endscan(scan);
heap_close(catalogRelation, RowExclusiveLock);
}
/*
* ALTER TABLE OF
*
* Attach a table to a composite type, as though it had been created with CREATE
* TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
* subject table must not have inheritance parents. These restrictions ensure
* that you cannot create a configuration impossible with CREATE TABLE OF alone.
*
* The address of the type is returned.
*/
static ObjectAddress
ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
{
Oid relid = RelationGetRelid(rel);
Type typetuple;
Oid typeid;
Relation inheritsRelation,
relationRelation;
SysScanDesc scan;
ScanKeyData key;
AttrNumber table_attno,
type_attno;
TupleDesc typeTupleDesc,
tableTupleDesc;
ObjectAddress tableobj,
typeobj;
HeapTuple classtuple;
/* Validate the type. */
typetuple = typenameType(NULL, ofTypename, NULL);
check_of_type(typetuple);
typeid = HeapTupleGetOid(typetuple);
/* Fail if the table has any inheritance parents. */
inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
ScanKeyInit(&key,
Anum_pg_inherits_inhrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid));
scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
true, NULL, 1, &key);
if (HeapTupleIsValid(systable_getnext(scan)))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("typed tables cannot inherit")));
systable_endscan(scan);
heap_close(inheritsRelation, AccessShareLock);
/*
* Check the tuple descriptors for compatibility. Unlike inheritance, we
* require that the order also match. However, attnotnull need not match.
* Also unlike inheritance, we do not require matching relhasoids.
*/
typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
tableTupleDesc = RelationGetDescr(rel);
table_attno = 1;
for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
{
Form_pg_attribute type_attr,
table_attr;
const char *type_attname,
*table_attname;
/* Get the next non-dropped type attribute. */
type_attr = typeTupleDesc->attrs[type_attno - 1];
if (type_attr->attisdropped)
continue;
type_attname = NameStr(type_attr->attname);
/* Get the next non-dropped table attribute. */
do
{
if (table_attno > tableTupleDesc->natts)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table is missing column \"%s\"",
type_attname)));
table_attr = tableTupleDesc->attrs[table_attno++ - 1];
} while (table_attr->attisdropped);
table_attname = NameStr(table_attr->attname);
/* Compare name. */
if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table has column \"%s\" where type requires \"%s\"",
table_attname, type_attname)));
/* Compare type. */
if (table_attr->atttypid != type_attr->atttypid ||
table_attr->atttypmod != type_attr->atttypmod ||
table_attr->attcollation != type_attr->attcollation)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table \"%s\" has different type for column \"%s\"",
RelationGetRelationName(rel), type_attname)));
}
DecrTupleDescRefCount(typeTupleDesc);
/* Any remaining columns at the end of the table had better be dropped. */
for (; table_attno <= tableTupleDesc->natts; table_attno++)
{
Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
if (!table_attr->attisdropped)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table has extra column \"%s\"",
NameStr(table_attr->attname))));
}
/* If the table was already typed, drop the existing dependency. */
if (rel->rd_rel->reloftype)
drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
/* Record a dependency on the new type. */
tableobj.classId = RelationRelationId;
tableobj.objectId = relid;
tableobj.objectSubId = 0;
typeobj.classId = TypeRelationId;
typeobj.objectId = typeid;
typeobj.objectSubId = 0;
recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
/* Update pg_class.reloftype */
relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(classtuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
CatalogUpdateIndexes(relationRelation, classtuple);
InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
heap_freetuple(classtuple);
heap_close(relationRelation, RowExclusiveLock);
ReleaseSysCache(typetuple);
return typeobj;
}
/*
* ALTER TABLE NOT OF
*
* Detach a typed table from its originating type. Just clear reloftype and
* remove the dependency.
*/
static void
ATExecDropOf(Relation rel, LOCKMODE lockmode)
{
Oid relid = RelationGetRelid(rel);
Relation relationRelation;
HeapTuple tuple;
if (!OidIsValid(rel->rd_rel->reloftype))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a typed table",
RelationGetRelationName(rel))));
/*
* We don't bother to check ownership of the type --- ownership of the
* table is presumed enough rights. No lock required on the type, either.
*/
drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
/* Clear pg_class.reloftype */
relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
simple_heap_update(relationRelation, &tuple->t_self, tuple);
CatalogUpdateIndexes(relationRelation, tuple);
InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
heap_freetuple(tuple);
heap_close(relationRelation, RowExclusiveLock);
}
/*
* relation_mark_replica_identity: Update a table's replica identity
*
* Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
* index. Otherwise, it should be InvalidOid.
*/
static void
relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
bool is_internal)
{
Relation pg_index;
Relation pg_class;
HeapTuple pg_class_tuple;
HeapTuple pg_index_tuple;
Form_pg_class pg_class_form;
Form_pg_index pg_index_form;
ListCell *index;
/*
* Check whether relreplident has changed, and update it if so.
*/
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
pg_class_tuple = SearchSysCacheCopy1(RELOID,
ObjectIdGetDatum(RelationGetRelid(rel)));
if (!HeapTupleIsValid(pg_class_tuple))
elog(ERROR, "cache lookup failed for relation \"%s\"",
RelationGetRelationName(rel));
pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
if (pg_class_form->relreplident != ri_type)
{
pg_class_form->relreplident = ri_type;
simple_heap_update(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
CatalogUpdateIndexes(pg_class, pg_class_tuple);
}
heap_close(pg_class, RowExclusiveLock);
heap_freetuple(pg_class_tuple);
/*
* Check whether the correct index is marked indisreplident; if so, we're
* done.
*/
if (OidIsValid(indexOid))
{
Assert(ri_type == REPLICA_IDENTITY_INDEX);
pg_index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexOid));
if (!HeapTupleIsValid(pg_index_tuple))
elog(ERROR, "cache lookup failed for index %u", indexOid);
pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
if (pg_index_form->indisreplident)
{
ReleaseSysCache(pg_index_tuple);
return;
}
ReleaseSysCache(pg_index_tuple);
}
/*
* Clear the indisreplident flag from any index that had it previously,
* and set it for any index that should have it now.
*/
pg_index = heap_open(IndexRelationId, RowExclusiveLock);
foreach(index, RelationGetIndexList(rel))
{
Oid thisIndexOid = lfirst_oid(index);
bool dirty = false;
pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
ObjectIdGetDatum(thisIndexOid));
if (!HeapTupleIsValid(pg_index_tuple))
elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
/*
* Unset the bit if set. We know it's wrong because we checked this
* earlier.
*/
if (pg_index_form->indisreplident)
{
dirty = true;
pg_index_form->indisreplident = false;
}
else if (thisIndexOid == indexOid)
{
dirty = true;
pg_index_form->indisreplident = true;
}
if (dirty)
{
simple_heap_update(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
CatalogUpdateIndexes(pg_index, pg_index_tuple);
InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
InvalidOid, is_internal);
}
heap_freetuple(pg_index_tuple);
}
heap_close(pg_index, RowExclusiveLock);
}
/*
* ALTER TABLE <name> REPLICA IDENTITY ...
*/
static void
ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
{
Oid indexOid;
Relation indexRel;
int key;
if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
{
relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
return;
}
else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
{
relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
return;
}
else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
{
relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
return;
}
else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
{
/* fallthrough */ ;
}
else
elog(ERROR, "unexpected identity type %u", stmt->identity_type);
/* Check that the index exists */
indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
if (!OidIsValid(indexOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("index \"%s\" for table \"%s\" does not exist",
stmt->name, RelationGetRelationName(rel))));
indexRel = index_open(indexOid, ShareLock);
/* Check that the index is on the relation we're altering. */
if (indexRel->rd_index == NULL ||
indexRel->rd_index->indrelid != RelationGetRelid(rel))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not an index for table \"%s\"",
RelationGetRelationName(indexRel),
RelationGetRelationName(rel))));
/* The AM must support uniqueness, and the index must in fact be unique. */
if (!indexRel->rd_am->amcanunique || !indexRel->rd_index->indisunique)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot use non-unique index \"%s\" as replica identity",
RelationGetRelationName(indexRel))));
/* Deferred indexes are not guaranteed to be always unique. */
if (!indexRel->rd_index->indimmediate)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot use non-immediate index \"%s\" as replica identity",
RelationGetRelationName(indexRel))));
/* Expression indexes aren't supported. */
if (RelationGetIndexExpressions(indexRel) != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot use expression index \"%s\" as replica identity",
RelationGetRelationName(indexRel))));
/* Predicate indexes aren't supported. */
if (RelationGetIndexPredicate(indexRel) != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot use partial index \"%s\" as replica identity",
RelationGetRelationName(indexRel))));
/* And neither are invalid indexes. */
if (!IndexIsValid(indexRel->rd_index))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot use invalid index \"%s\" as replica identity",
RelationGetRelationName(indexRel))));
/* Check index for nullable columns. */
for (key = 0; key < indexRel->rd_index->indnatts; key++)
{
int16 attno = indexRel->rd_index->indkey.values[key];
Form_pg_attribute attr;
/* Allow OID column to be indexed; it's certainly not nullable */
if (attno == ObjectIdAttributeNumber)
continue;
/*
* Reject any other system columns. (Going forward, we'll disallow
* indexes containing such columns in the first place, but they might
* exist in older branches.)
*/
if (attno <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
RelationGetRelationName(indexRel), attno)));
attr = rel->rd_att->attrs[attno - 1];
if (!attr->attnotnull)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
RelationGetRelationName(indexRel),
NameStr(attr->attname))));
}
/* This index is suitable for use as a replica identity. Mark it. */
relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
index_close(indexRel, NoLock);
}
/*
* ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
*/
static void
ATExecEnableRowSecurity(Relation rel)
{
Relation pg_class;
Oid relid;
HeapTuple tuple;
relid = RelationGetRelid(rel);
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = true;
simple_heap_update(pg_class, &tuple->t_self, tuple);
/* keep catalog indexes current */
CatalogUpdateIndexes(pg_class, tuple);
heap_close(pg_class, RowExclusiveLock);
heap_freetuple(tuple);
}
static void
ATExecDisableRowSecurity(Relation rel)
{
Relation pg_class;
Oid relid;
HeapTuple tuple;
relid = RelationGetRelid(rel);
/* Pull the record for this relation and update it */
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = false;
simple_heap_update(pg_class, &tuple->t_self, tuple);
/* keep catalog indexes current */
CatalogUpdateIndexes(pg_class, tuple);
heap_close(pg_class, RowExclusiveLock);
heap_freetuple(tuple);
}
/*
* ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
*/
static void
ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
{
Relation pg_class;
Oid relid;
HeapTuple tuple;
relid = RelationGetRelid(rel);
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
simple_heap_update(pg_class, &tuple->t_self, tuple);
/* keep catalog indexes current */
CatalogUpdateIndexes(pg_class, tuple);
heap_close(pg_class, RowExclusiveLock);
heap_freetuple(tuple);
}
/*
* ALTER FOREIGN TABLE <name> OPTIONS (...)
*/
static void
ATExecGenericOptions(Relation rel, List *options)
{
Relation ftrel;
ForeignServer *server;
ForeignDataWrapper *fdw;
HeapTuple tuple;
bool isnull;
Datum repl_val[Natts_pg_foreign_table];
bool repl_null[Natts_pg_foreign_table];
bool repl_repl[Natts_pg_foreign_table];
Datum datum;
Form_pg_foreign_table tableform;
if (options == NIL)
return;
ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("foreign table \"%s\" does not exist",
RelationGetRelationName(rel))));
tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
server = GetForeignServer(tableform->ftserver);
fdw = GetForeignDataWrapper(server->fdwid);
memset(repl_val, 0, sizeof(repl_val));
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
/* Extract the current options */
datum = SysCacheGetAttr(FOREIGNTABLEREL,
tuple,
Anum_pg_foreign_table_ftoptions,
&isnull);
if (isnull)
datum = PointerGetDatum(NULL);
/* Transform the options */
datum = transformGenericOptions(ForeignTableRelationId,
datum,
options,
fdw->fdwvalidator);
if (PointerIsValid(DatumGetPointer(datum)))
repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
else
repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
/* Everything looks good - update the tuple */
tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
repl_val, repl_null, repl_repl);
simple_heap_update(ftrel, &tuple->t_self, tuple);
CatalogUpdateIndexes(ftrel, tuple);
/*
* Invalidate relcache so that all sessions will refresh any cached plans
* that might depend on the old options.
*/
CacheInvalidateRelcache(rel);
InvokeObjectPostAlterHook(ForeignTableRelationId,
RelationGetRelid(rel), 0);
heap_close(ftrel, RowExclusiveLock);
heap_freetuple(tuple);
}
/*
* Preparation phase for SET LOGGED/UNLOGGED
*
* This verifies that we're not trying to change a temp table. Also,
* existing foreign key constraints are checked to avoid ending up with
* permanent tables referencing unlogged tables.
*
* Return value is false if the operation is a no-op (in which case the
* checks are skipped), otherwise true.
*/
static bool
ATPrepChangePersistence(Relation rel, bool toLogged)
{
Relation pg_constraint;
HeapTuple tuple;
SysScanDesc scan;
ScanKeyData skey[1];
/*
* Disallow changing status for a temp table. Also verify whether we can
* get away with doing nothing; in such cases we don't need to run the
* checks below, either.
*/
switch (rel->rd_rel->relpersistence)
{
case RELPERSISTENCE_TEMP:
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot change logged status of table \"%s\" because it is temporary",
RelationGetRelationName(rel)),
errtable(rel)));
break;
case RELPERSISTENCE_PERMANENT:
if (toLogged)
/* nothing to do */
return false;
break;
case RELPERSISTENCE_UNLOGGED:
if (!toLogged)
/* nothing to do */
return false;
break;
}
/*
* Check existing foreign key constraints to preserve the invariant that
* permanent tables cannot reference unlogged ones. Self-referencing
* foreign keys can safely be ignored.
*/
pg_constraint = heap_open(ConstraintRelationId, AccessShareLock);
/*
* Scan conrelid if changing to permanent, else confrelid. This also
* determines whether a useful index exists.
*/
ScanKeyInit(&skey[0],
toLogged ? Anum_pg_constraint_conrelid :
Anum_pg_constraint_confrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
scan = systable_beginscan(pg_constraint,
toLogged ? ConstraintRelidIndexId : InvalidOid,
true, NULL, 1, skey);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
if (con->contype == CONSTRAINT_FOREIGN)
{
Oid foreignrelid;
Relation foreignrel;
/* the opposite end of what we used as scankey */
foreignrelid = toLogged ? con->confrelid : con->conrelid;
/* ignore if self-referencing */
if (RelationGetRelid(rel) == foreignrelid)
continue;
foreignrel = relation_open(foreignrelid, AccessShareLock);
if (toLogged)
{
if (foreignrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
RelationGetRelationName(rel),
RelationGetRelationName(foreignrel)),
errtableconstraint(rel, NameStr(con->conname))));
}
else
{
if (foreignrel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
RelationGetRelationName(rel),
RelationGetRelationName(foreignrel)),
errtableconstraint(rel, NameStr(con->conname))));
}
relation_close(foreignrel, AccessShareLock);
}
}
systable_endscan(scan);
heap_close(pg_constraint, AccessShareLock);
return true;
}
/*
* Execute ALTER TABLE SET SCHEMA
*/
ObjectAddress
AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
{
Relation rel;
Oid relid;
Oid oldNspOid;
Oid nspOid;
RangeVar *newrv;
ObjectAddresses *objsMoved;
ObjectAddress myself;
relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
stmt->missing_ok, false,
RangeVarCallbackForAlterRelation,
(void *) stmt);
if (!OidIsValid(relid))
{
ereport(NOTICE,
(errmsg("relation \"%s\" does not exist, skipping",
stmt->relation->relname)));
return InvalidObjectAddress;
}
rel = relation_open(relid, NoLock);
oldNspOid = RelationGetNamespace(rel);
/* If it's an owned sequence, disallow moving it by itself. */
if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
{
Oid tableId;
int32 colId;
if (sequenceIsOwned(relid, &tableId, &colId))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot move an owned sequence into another schema"),
errdetail("Sequence \"%s\" is linked to table \"%s\".",
RelationGetRelationName(rel),
get_rel_name(tableId))));
}
/* Get and lock schema OID and check its permissions. */
newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
/* common checks on switching namespaces */
CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
objsMoved = new_object_addresses();
AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
free_object_addresses(objsMoved);
ObjectAddressSet(myself, RelationRelationId, relid);
if (oldschema)
*oldschema = oldNspOid;
/* close rel, but keep lock until commit */
relation_close(rel, NoLock);
return myself;
}
/*
* The guts of relocating a table or materialized view to another namespace:
* besides moving the relation itself, its dependent objects are relocated to
* the new schema.
*/
void
AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
ObjectAddresses *objsMoved)
{
Relation classRel;
Assert(objsMoved != NULL);
/* OK, modify the pg_class row and pg_depend entry */
classRel = heap_open(RelationRelationId, RowExclusiveLock);
AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
nspOid, true, objsMoved);
/* Fix the table's row type too */
AlterTypeNamespaceInternal(rel->rd_rel->reltype,
nspOid, false, false, objsMoved);
/* Fix other dependent stuff */
if (rel->rd_rel->relkind == RELKIND_RELATION ||
rel->rd_rel->relkind == RELKIND_MATVIEW)
{
AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
objsMoved, AccessExclusiveLock);
AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
false, objsMoved);
}
heap_close(classRel, RowExclusiveLock);
}
/*
* The guts of relocating a relation to another namespace: fix the pg_class
* entry, and the pg_depend entry if any. Caller must already have
* opened and write-locked pg_class.
*/
void
AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
Oid oldNspOid, Oid newNspOid,
bool hasDependEntry,
ObjectAddresses *objsMoved)
{
HeapTuple classTup;
Form_pg_class classForm;
ObjectAddress thisobj;
classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
if (!HeapTupleIsValid(classTup))
elog(ERROR, "cache lookup failed for relation %u", relOid);
classForm = (Form_pg_class) GETSTRUCT(classTup);
Assert(classForm->relnamespace == oldNspOid);
thisobj.classId = RelationRelationId;
thisobj.objectId = relOid;
thisobj.objectSubId = 0;
/*
* Do nothing when there's nothing to do.
*/
if (!object_address_present(&thisobj, objsMoved))
{
/* check for duplicate name (more friendly than unique-index failure) */
if (get_relname_relid(NameStr(classForm->relname),
newNspOid) != InvalidOid)
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" already exists in schema \"%s\"",
NameStr(classForm->relname),
get_namespace_name(newNspOid))));
/* classTup is a copy, so OK to scribble on */
classForm->relnamespace = newNspOid;
simple_heap_update(classRel, &classTup->t_self, classTup);
CatalogUpdateIndexes(classRel, classTup);
/* Update dependency on schema if caller said so */
if (hasDependEntry &&
changeDependencyFor(RelationRelationId,
relOid,
NamespaceRelationId,
oldNspOid,
newNspOid) != 1)
elog(ERROR, "failed to change schema dependency for relation \"%s\"",
NameStr(classForm->relname));
add_exact_object_address(&thisobj, objsMoved);
InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
}
heap_freetuple(classTup);
}
/*
* Move all indexes for the specified relation to another namespace.
*
* Note: we assume adequate permission checking was done by the caller,
* and that the caller has a suitable lock on the owning relation.
*/
static void
AlterIndexNamespaces(Relation classRel, Relation rel,
Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
{
List *indexList;
ListCell *l;
indexList = RelationGetIndexList(rel);
foreach(l, indexList)
{
Oid indexOid = lfirst_oid(l);
ObjectAddress thisobj;
thisobj.classId = RelationRelationId;
thisobj.objectId = indexOid;
thisobj.objectSubId = 0;
/*
* Note: currently, the index will not have its own dependency on the
* namespace, so we don't need to do changeDependencyFor(). There's no
* row type in pg_type, either.
*
* XXX this objsMoved test may be pointless -- surely we have a single
* dependency link from a relation to each index?
*/
if (!object_address_present(&thisobj, objsMoved))
{
AlterRelationNamespaceInternal(classRel, indexOid,
oldNspOid, newNspOid,
false, objsMoved);
add_exact_object_address(&thisobj, objsMoved);
}
}
list_free(indexList);
}
/*
* Move all SERIAL-column sequences of the specified relation to another
* namespace.
*
* Note: we assume adequate permission checking was done by the caller,
* and that the caller has a suitable lock on the owning relation.
*/
static void
AlterSeqNamespaces(Relation classRel, Relation rel,
Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
LOCKMODE lockmode)
{
Relation depRel;
SysScanDesc scan;
ScanKeyData key[2];
HeapTuple tup;
/*
* SERIAL sequences are those having an auto dependency on one of the
* table's columns (we don't care *which* column, exactly).
*/
depRel = heap_open(DependRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(RelationGetRelid(rel)));
/* we leave refobjsubid unspecified */
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
NULL, 2, key);
while (HeapTupleIsValid(tup = systable_getnext(scan)))
{
Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
Relation seqRel;
/* skip dependencies other than auto dependencies on columns */
if (depForm->refobjsubid == 0 ||
depForm->classid != RelationRelationId ||
depForm->objsubid != 0 ||
depForm->deptype != DEPENDENCY_AUTO)
continue;
/* Use relation_open just in case it's an index */
seqRel = relation_open(depForm->objid, lockmode);
/* skip non-sequence relations */
if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
{
/* No need to keep the lock */
relation_close(seqRel, lockmode);
continue;
}
/* Fix the pg_class and pg_depend entries */
AlterRelationNamespaceInternal(classRel, depForm->objid,
oldNspOid, newNspOid,
true, objsMoved);
/*
* Sequences have entries in pg_type. We need to be careful to move
* them to the new namespace, too.
*/
AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
newNspOid, false, false, objsMoved);
/* Now we can close it. Keep the lock till end of transaction. */
relation_close(seqRel, NoLock);
}
systable_endscan(scan);
relation_close(depRel, AccessShareLock);
}
/*
* This code supports
* CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
*
* Because we only support this for TEMP tables, it's sufficient to remember
* the state in a backend-local data structure.
*/
/*
* Register a newly-created relation's ON COMMIT action.
*/
void
register_on_commit_action(Oid relid, OnCommitAction action)
{
OnCommitItem *oc;
MemoryContext oldcxt;
/*
* We needn't bother registering the relation unless there is an ON COMMIT
* action we need to take.
*/
if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
return;
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
oc->relid = relid;
oc->oncommit = action;
oc->creating_subid = GetCurrentSubTransactionId();
oc->deleting_subid = InvalidSubTransactionId;
on_commits = lcons(oc, on_commits);
MemoryContextSwitchTo(oldcxt);
}
/*
* Unregister any ON COMMIT action when a relation is deleted.
*
* Actually, we only mark the OnCommitItem entry as to be deleted after commit.
*/
void
remove_on_commit_action(Oid relid)
{
ListCell *l;
foreach(l, on_commits)
{
OnCommitItem *oc = (OnCommitItem *) lfirst(l);
if (oc->relid == relid)
{
oc->deleting_subid = GetCurrentSubTransactionId();
break;
}
}
}
/*
* Perform ON COMMIT actions.
*
* This is invoked just before actually committing, since it's possible
* to encounter errors.
*/
void
PreCommit_on_commit_actions(void)
{
ListCell *l;
List *oids_to_truncate = NIL;
foreach(l, on_commits)
{
OnCommitItem *oc = (OnCommitItem *) lfirst(l);
/* Ignore entry if already dropped in this xact */
if (oc->deleting_subid != InvalidSubTransactionId)
continue;
switch (oc->oncommit)
{
case ONCOMMIT_NOOP:
case ONCOMMIT_PRESERVE_ROWS:
/* Do nothing (there shouldn't be such entries, actually) */
break;
case ONCOMMIT_DELETE_ROWS:
/*
* If this transaction hasn't accessed any temporary
* relations, we can skip truncating ON COMMIT DELETE ROWS
* tables, as they must still be empty.
*/
if (MyXactAccessedTempRel)
oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
break;
case ONCOMMIT_DROP:
{
ObjectAddress object;
object.classId = RelationRelationId;
object.objectId = oc->relid;
object.objectSubId = 0;
/*
* Since this is an automatic drop, rather than one
* directly initiated by the user, we pass the
* PERFORM_DELETION_INTERNAL flag.
*/
performDeletion(&object,
DROP_CASCADE, PERFORM_DELETION_INTERNAL);
/*
* Note that table deletion will call
* remove_on_commit_action, so the entry should get marked
* as deleted.
*/
Assert(oc->deleting_subid != InvalidSubTransactionId);
break;
}
}
}
if (oids_to_truncate != NIL)
{
heap_truncate(oids_to_truncate);
CommandCounterIncrement(); /* XXX needed? */
}
}
/*
* Post-commit or post-abort cleanup for ON COMMIT management.
*
* All we do here is remove no-longer-needed OnCommitItem entries.
*
* During commit, remove entries that were deleted during this transaction;
* during abort, remove those created during this transaction.
*/
void
AtEOXact_on_commit_actions(bool isCommit)
{
ListCell *cur_item;
ListCell *prev_item;
prev_item = NULL;
cur_item = list_head(on_commits);
while (cur_item != NULL)
{
OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
oc->creating_subid != InvalidSubTransactionId)
{
/* cur_item must be removed */
on_commits = list_delete_cell(on_commits, cur_item, prev_item);
pfree(oc);
if (prev_item)
cur_item = lnext(prev_item);
else
cur_item = list_head(on_commits);
}
else
{
/* cur_item must be preserved */
oc->creating_subid = InvalidSubTransactionId;
oc->deleting_subid = InvalidSubTransactionId;
prev_item = cur_item;
cur_item = lnext(prev_item);
}
}
}
/*
* Post-subcommit or post-subabort cleanup for ON COMMIT management.
*
* During subabort, we can immediately remove entries created during this
* subtransaction. During subcommit, just relabel entries marked during
* this subtransaction as being the parent's responsibility.
*/
void
AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
SubTransactionId parentSubid)
{
ListCell *cur_item;
ListCell *prev_item;
prev_item = NULL;
cur_item = list_head(on_commits);
while (cur_item != NULL)
{
OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
if (!isCommit && oc->creating_subid == mySubid)
{
/* cur_item must be removed */
on_commits = list_delete_cell(on_commits, cur_item, prev_item);
pfree(oc);
if (prev_item)
cur_item = lnext(prev_item);
else
cur_item = list_head(on_commits);
}
else
{
/* cur_item must be preserved */
if (oc->creating_subid == mySubid)
oc->creating_subid = parentSubid;
if (oc->deleting_subid == mySubid)
oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
prev_item = cur_item;
cur_item = lnext(prev_item);
}
}
}
/*
* This is intended as a callback for RangeVarGetRelidExtended(). It allows
* the relation to be locked only if (1) it's a plain table, materialized
* view, or TOAST table and (2) the current user is the owner (or the
* superuser). This meets the permission-checking needs of CLUSTER, REINDEX
* TABLE, and REFRESH MATERIALIZED VIEW; we expose it here so that it can be
* used by all.
*/
void
RangeVarCallbackOwnsTable(const RangeVar *relation,
Oid relId, Oid oldRelId, void *arg)
{
char relkind;
/* Nothing to do if the relation was not found. */
if (!OidIsValid(relId))
return;
/*
* If the relation does exist, check whether it's an index. But note that
* the relation might have been dropped between the time we did the name
* lookup and now. In that case, there's nothing to do.
*/
relkind = get_rel_relkind(relId);
if (!relkind)
return;
if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
relkind != RELKIND_MATVIEW)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table or materialized view", relation->relname)));
/* Check permissions */
if (!pg_class_ownercheck(relId, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
}
/*
* Callback to RangeVarGetRelidExtended(), similar to
* RangeVarCallbackOwnsTable() but without checks on the type of the relation.
*/
void
RangeVarCallbackOwnsRelation(const RangeVar *relation,
Oid relId, Oid oldRelId, void *arg)
{
HeapTuple tuple;
/* Nothing to do if the relation was not found. */
if (!OidIsValid(relId))
return;
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
if (!HeapTupleIsValid(tuple)) /* should not happen */
elog(ERROR, "cache lookup failed for relation %u", relId);
if (!pg_class_ownercheck(relId, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
relation->relname);
if (!allowSystemTableMods &&
IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
relation->relname)));
ReleaseSysCache(tuple);
}
/*
* Common RangeVarGetRelid callback for rename, set schema, and alter table
* processing.
*/
static void
RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
void *arg)
{
Node *stmt = (Node *) arg;
ObjectType reltype;
HeapTuple tuple;
Form_pg_class classform;
AclResult aclresult;
char relkind;
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
return; /* concurrently dropped */
classform = (Form_pg_class) GETSTRUCT(tuple);
relkind = classform->relkind;
/* Must own relation. */
if (!pg_class_ownercheck(relid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
/* No system table modifications unless explicitly allowed. */
if (!allowSystemTableMods && IsSystemClass(relid, classform))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
rv->relname)));
/*
* Extract the specified relation type from the statement parse tree.
*
* Also, for ALTER .. RENAME, check permissions: the user must (still)
* have CREATE rights on the containing namespace.
*/
if (IsA(stmt, RenameStmt))
{
aclresult = pg_namespace_aclcheck(classform->relnamespace,
GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(classform->relnamespace));
reltype = ((RenameStmt *) stmt)->renameType;
}
else if (IsA(stmt, AlterObjectSchemaStmt))
reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
else if (IsA(stmt, AlterTableStmt))
reltype = ((AlterTableStmt *) stmt)->relkind;
else
{
reltype = OBJECT_TABLE; /* placate compiler */
elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
}
/*
* For compatibility with prior releases, we allow ALTER TABLE to be used
* with most other types of relations (but not composite types). We allow
* similar flexibility for ALTER INDEX in the case of RENAME, but not
* otherwise. Otherwise, the user must select the correct form of the
* command for the relation at issue.
*/
if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a sequence", rv->relname)));
if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a view", rv->relname)));
if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a materialized view", rv->relname)));
if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a foreign table", rv->relname)));
if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a composite type", rv->relname)));
if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX
&& !IsA(stmt, RenameStmt))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not an index", rv->relname)));
/*
* Don't allow ALTER TABLE on composite types. We want people to use ALTER
* TYPE for that.
*/
if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a composite type", rv->relname),
errhint("Use ALTER TYPE instead.")));
/*
* Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
* to a different schema, such as indexes and TOAST tables.
*/
if (IsA(stmt, AlterObjectSchemaStmt) &&
relkind != RELKIND_RELATION &&
relkind != RELKIND_VIEW &&
relkind != RELKIND_MATVIEW &&
relkind != RELKIND_SEQUENCE &&
relkind != RELKIND_FOREIGN_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, view, materialized view, sequence, or foreign table",
rv->relname)));
ReleaseSysCache(tuple);
}
|
876966.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67b.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-67b.tmpl.c
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Positive integer
* Sinks: memcpy
* BadSink : Copy strings using memcpy() with the length of data
* Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifdef _WIN32
# include <winsock2.h>
# include <windows.h>
# include <direct.h>
# pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
# define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
# define INVALID_SOCKET -1
# define SOCKET_ERROR -1
# define CLOSE_SOCKET close
# define SOCKET int
#endif
#define TCP_PORT 27015
/* Must be at least 8 for atoi() to work properly */
#define CHAR_ARRAY_SIZE 8
typedef struct _CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67_struct_type
{
short a;
} CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67_struct_type;
#ifndef OMITBAD
void CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67b_bad_sink(CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67_struct_type my_struct)
{
short data = my_struct.a;
{
char src[100];
char dest[100] = "";
memset(src, 'A', 100-1);
src[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
memcpy(dest, src, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67b_goodG2B_sink(CWE194_Unexpected_Sign_Extension__connect_socket_memcpy_67_struct_type my_struct)
{
short data = my_struct.a;
{
char src[100];
char dest[100] = "";
memset(src, 'A', 100-1);
src[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
memcpy(dest, src, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITGOOD */
|
742982.c | /*
* pcfdemo - demonstrate PCF font loading/display for Nano-X
*/
#include <stdio.h>
#include <stdlib.h>
#define MWINCLUDECOLORS
#include "nano-X.h"
GR_FONT_ID font = 0;
GR_FONT_INFO finfo;
unsigned int first_char = 0;
unsigned int lines = 8;
unsigned int line_width = 32;
unsigned int chars_to_show;
unsigned int border = 10;
unsigned int spacer = 2;
static void
draw_string(GR_WINDOW_ID wid)
{
int count = 0;
int x = border;
int y = border;
unsigned int start, end;
unsigned int ch;
GR_GC_ID gc = GrNewGC();
GrSetGCBackground(gc, GR_RGB(0, 0, 0));
GrSetGCFont(gc, font);
if (first_char > finfo.lastchar)
first_char = 0;
if (first_char + chars_to_show <= finfo.firstchar)
first_char = (finfo.firstchar / line_width) * line_width;
start = first_char;
end = first_char + chars_to_show;
GrError("drawing chars %d to %d\n", start, end - 1);
for (ch = start; ch < end; ch++) {
GrSetGCForeground(gc, GR_RGB(64, 64, 64));
GrFillRect(wid, gc, x-1, y-1, finfo.maxwidth+2, finfo.height+2);
GrSetGCForeground(gc, GR_RGB(255, 255, 255));
if (ch >= finfo.firstchar && ch <= finfo.lastchar)
GrText(wid, gc, x, y, &ch, 1, GR_TFTOP | GR_TFUC32);
if (++count >= line_width) {
x = border;
y += finfo.height + spacer;
count = 0;
} else
x += finfo.maxwidth + spacer;
}
GrDestroyGC(gc);
}
int
main(int argc, char **argv)
{
GR_WINDOW_ID main_wid;
GR_TIMEOUT timeout;
int width, height;
if (argc != 2)
return 1;
if (GrOpen() < 0)
return 1;
font = GrCreateFontEx(argv[1], 12, 12, 0);
if (!font)
GrError("Unable to load %s\n", argv[1]);
GrGetFontInfo(font, &finfo);
GrError("font_id = %d\n", font);
GrError("First char = %d, last char = %d\n", finfo.firstchar, finfo.lastchar);
GrError("Max width = %d, max height = %d\n", finfo.maxwidth, finfo.height);
GrError("baseline = ascent = %d, descent = %d\n", finfo.baseline, finfo.descent);
GrError("max ascent = %d, max descent = %d\n", finfo.maxascent, finfo.maxdescent);
GrError("linespacing = %d, fixed = %s\n", finfo.linespacing, finfo.fixed? "yes": "no");
// finfo.firstchar = 0; /* force display of undefined chars, test with jiskan24.pcf.gz*/
/* determine window metrics*/
width = (finfo.maxwidth + spacer) * line_width + 2 * border - spacer;
if (width > 640) {
line_width /= 2;
lines *= 2;
width = (finfo.maxwidth + 2) * line_width + 2 * border - spacer;
}
height = lines * (finfo.height + spacer) + 2 * border - spacer;
chars_to_show = lines * line_width;
/* create the main application window*/
main_wid = GrNewWindowEx(GR_WM_PROPS_APPWINDOW, argv[1],
GR_ROOT_WINDOW_ID, 0, 0, width, height, BLACK);
GrSelectEvents(main_wid, GR_EVENT_MASK_EXPOSURE|GR_EVENT_MASK_CLOSE_REQ);
GrMapWindow(main_wid);
if (finfo.lastchar >= chars_to_show)
timeout = 8 * 1000;
else timeout = 0;
while (1) {
GR_EVENT event;
GrGetNextEventTimeout(&event, timeout);
if (event.type == GR_EVENT_TYPE_TIMEOUT) {
first_char += chars_to_show;
draw_string(main_wid);
}
if (event.type == GR_EVENT_TYPE_EXPOSURE)
draw_string(main_wid);
if(event.type == GR_EVENT_TYPE_CLOSE_REQ) {
GrClose();
return 0;
}
}
}
|
264511.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_loop_53d.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__src.string.label.xml
Template File: sources-sink-53d.tmpl.c
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: loop
* BadSink : Copy data to string using a loop
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_loop_53d_bad_sink(wchar_t * data)
{
{
wchar_t dest[50] = L"";
size_t i, data_len;
data_len = wcslen(data);
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
for (i = 0; i < data_len; i++)
{
dest[i] = data[i];
}
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_loop_53d_goodG2B_sink(wchar_t * data)
{
{
wchar_t dest[50] = L"";
size_t i, data_len;
data_len = wcslen(data);
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
for (i = 0; i < data_len; i++)
{
dest[i] = data[i];
}
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
}
}
#endif /* OMITGOOD */
|
445529.c | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "opengles.h"
typedef void (APIENTRY *glCopyImageSubDataOESPROC) (jint, jint, jint, jint, jint, jint, jint, jint, jint, jint, jint, jint, jint, jint, jint);
EXTERN_C_ENTER
JNIEXPORT void JNICALL Java_org_lwjgl_opengles_OESCopyImage_glCopyImageSubDataOES(JNIEnv *__env, jclass clazz, jint srcName, jint srcTarget, jint srcLevel, jint srcX, jint srcY, jint srcZ, jint dstName, jint dstTarget, jint dstLevel, jint dstX, jint dstY, jint dstZ, jint srcWidth, jint srcHeight, jint srcDepth) {
glCopyImageSubDataOESPROC glCopyImageSubDataOES = (glCopyImageSubDataOESPROC)tlsGetFunction(779);
UNUSED_PARAM(clazz)
glCopyImageSubDataOES(srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth);
}
EXTERN_C_EXIT
|
552798.c | #include <lnkdump.h>
#pragma hdrstop
void ReadString( HANDLE hFile, LPVOID * lpVoid, BOOL bUnicode )
{
USHORT cch;
DWORD dwBytesRead;
if (bUnicode)
{
LPWSTR lpWStr = NULL;
ReadFile( hFile, (LPVOID)&cch, sizeof(cch), &dwBytesRead, NULL );
lpWStr = (LPWSTR)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, (cch+1)*sizeof(WCHAR) );
if (lpWStr) {
ReadFile( hFile, (LPVOID)lpWStr, cch*sizeof(WCHAR), &dwBytesRead, NULL );
lpWStr[cch] = L'\0';
}
*(PDWORD_PTR)lpVoid = (DWORD_PTR)lpWStr;
}
else
{
LPSTR lpStr = NULL;
ReadFile( hFile, (LPVOID)&cch, sizeof(cch), &dwBytesRead, NULL );
lpStr = (LPSTR)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, (cch+1) );
if (lpStr) {
ReadFile( hFile, (LPVOID)lpStr, cch, &dwBytesRead, NULL );
lpStr[cch] = '\0';
}
*(PDWORD_PTR)lpVoid = (DWORD_PTR)lpStr;
}
}
int __cdecl main( int argc, char *argv[])
{
HANDLE hFile;
CShellLink csl;
CShellLink * this = &csl;
DWORD cbSize, cbTotal, cbToRead, dwBytesRead;
SYSTEMTIME st;
LPSTR pTemp = NULL;
this->pidl = 0;
this->pli = NULL;
memset( this, 0, sizeof(CShellLink) );
if (argc!=2)
{
printf("usage: lnkdump filename.lnk\n" );
return(1);
}
// Try to open the file
hFile = CreateFile( argv[1],
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hFile == INVALID_HANDLE_VALUE)
{
printf( "lnkdump: unable to open file %s, err %d\n",
argv[1],
GetLastError()
);
return(1);
}
// Now, read out data...
ReadFile( hFile, (LPVOID)&this->sld, sizeof(this->sld), &dwBytesRead, NULL );
// read all of the members
if (this->sld.dwFlags & SLDF_HAS_ID_LIST)
{
// Read the size of the IDLIST
cbSize = 0; // need to zero out to get HIWORD 0 'cause USHORT is only 2 bytes
ReadFile( hFile, (LPVOID)&cbSize, sizeof(USHORT), &dwBytesRead, NULL );
if (cbSize)
{
SetFilePointer(hFile,cbSize,NULL,FILE_CURRENT);
}
else
{
printf( "Error readling PIDL out of link!\n" );
return( 1 );
}
}
// BUGBUG: this part is not unicode ready, talk to daviddi
if (this->sld.dwFlags & (SLDF_HAS_LINK_INFO))
{
LPVOID pli;
ReadFile( hFile, (LPVOID)&cbSize, sizeof(cbSize), &dwBytesRead, NULL );
if (cbSize >= sizeof(cbSize))
{
cbSize -= sizeof(cbSize);
SetFilePointer(hFile,cbSize,NULL,FILE_CURRENT);
}
}
if (this->sld.dwFlags & SLDF_HAS_NAME)
ReadString( hFile, &this->pszName, this->sld.dwFlags & SLDF_UNICODE);
if (this->sld.dwFlags & SLDF_HAS_RELPATH)
ReadString( hFile, &this->pszRelPath, this->sld.dwFlags & SLDF_UNICODE);
if (this->sld.dwFlags & SLDF_HAS_WORKINGDIR)
ReadString( hFile, &this->pszWorkingDir, this->sld.dwFlags & SLDF_UNICODE);
if (this->sld.dwFlags & SLDF_HAS_ARGS)
ReadString( hFile, &this->pszArgs, this->sld.dwFlags & SLDF_UNICODE);
if (this->sld.dwFlags & SLDF_HAS_ICONLOCATION)
ReadString( hFile, &this->pszIconLocation, this->sld.dwFlags & SLDF_UNICODE);
// Read in extra data sections
this->pExtraData = NULL;
cbTotal = 0;
while (TRUE)
{
LPSTR pReadData = NULL;
cbSize = 0;
ReadFile( hFile, (LPVOID)&cbSize, sizeof(cbSize), &dwBytesRead, NULL );
if (cbSize < sizeof(cbSize))
break;
if (pTemp)
{
pTemp = (void *)HeapReAlloc( GetProcessHeap(),
HEAP_ZERO_MEMORY,
this->pExtraData,
cbTotal + cbSize + sizeof(DWORD)
);
if (pTemp)
{
this->pExtraData = (LPDBLIST)pTemp;
}
}
else
{
(LPVOID)this->pExtraData = pTemp = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, cbTotal + cbSize + sizeof(DWORD) );
}
if (!pTemp)
break;
cbToRead = cbSize - sizeof(cbSize);
pReadData = pTemp + cbTotal;
ReadFile( hFile, (LPVOID)(pReadData + sizeof(cbSize)), cbToRead, &dwBytesRead, NULL );
if (dwBytesRead==cbToRead)
{
// got all of the extra data, comit it
*((UNALIGNED DWORD *)pReadData) = cbSize;
cbTotal += cbSize;
}
else
break;
}
printf( "\n===== Dump of link file (%s) =====\n\n", argv[1] );
printf( "[Shell Link Data (sld)]\n" );
printf( " cbSize = 0x%08X\n", this->sld.cbSize );
printf( " GUID = {%08lX-%04X-%04X-%02X%02X-%02X%02X%02x%02x%02x%02x}\n",
this->sld.clsid.Data1, this->sld.clsid.Data2, this->sld.clsid.Data3,
this->sld.clsid.Data4[0], this->sld.clsid.Data4[1],
this->sld.clsid.Data4[2], this->sld.clsid.Data4[3],
this->sld.clsid.Data4[4], this->sld.clsid.Data4[5],
this->sld.clsid.Data4[6], this->sld.clsid.Data4[7]
);
printf( " dwFlags = 0x%08X\n", this->sld.dwFlags );
if (this->sld.dwFlags & SLDF_HAS_ID_LIST)
printf( " SLDF_HAS_ID_LIST is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_LINK_INFO)
printf( " SLDF_HAS_LINK_INFO is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_NAME)
printf( " SLDF_HAS_NAME is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_RELPATH)
printf( " SLDF_HAS_RELPATH is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_WORKINGDIR)
printf( " SLDF_HAS_WORKINGDIR is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_ARGS)
printf( " SLDF_HAS_ARGS is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_ICONLOCATION)
printf( " SLDF_HAS_ICONLOCATION is set.\n" );
if (this->sld.dwFlags & SLDF_HAS_EXP_SZ)
printf( " SLDF_HAS_EXP_SZ is set.\n" );
if (this->sld.dwFlags & SLDF_RUN_IN_SEPARATE)
printf( " SLDF_RUN_IN_SEPARATE is set.\n" );
if (this->sld.dwFlags & SLDF_UNICODE)
printf( " SLDF_HAS_UNICODE is set.\n" );
if (this->sld.dwFlags & SLDF_FORCE_NO_LINKINFO)
printf( " SLDF_FORCE_NO_LINKINFO is set.\n" );
printf( " dwFileAttributes = 0x%08X\n", this->sld.dwFileAttributes );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
printf( " FILE_ATTRIBUTE_READONLY is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
printf( " FILE_ATTRIBUTE_HIDDEN is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
printf( " FILE_ATTRIBUTE_SYSTEM is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
printf( " FILE_ATTRIBUTE_DIRECTORY is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
printf( " FILE_ATTRIBUTE_ARCHIVE is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
printf( " FILE_ATTRIBUTE_NORMAL is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)
printf( " FILE_ATTRIBUTE_TEMPORARY is set.\n" );
if (this->sld.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
printf( " FILE_ATTRIBUTE_COMPRESSED is set.\n" );
FileTimeToSystemTime( &this->sld.ftCreationTime, &st );
printf(" ftCreationTime = %02d:%02d:%02d, %02d/%02d/%04d\n", st.wHour, st.wMinute, st.wSecond, st.wMonth, st.wDay, st.wYear );
FileTimeToSystemTime( &this->sld.ftLastAccessTime, &st );
printf(" ftLastAccessTime = %02d:%02d:%02d, %02d/%02d/%04d\n", st.wHour, st.wMinute, st.wSecond, st.wMonth, st.wDay, st.wYear );
FileTimeToSystemTime( &this->sld.ftLastWriteTime, &st );
printf(" ftLastWriteTime = %02d:%02d:%02d, %02d/%02d/%04d\n", st.wHour, st.wMinute, st.wSecond, st.wMonth, st.wDay, st.wYear );
printf(" nFileSizeLow = %d bytes\n", this->sld.nFileSizeLow );
printf(" iIcon = %d\n", this->sld.iIcon );
printf(" wHotkey = 0x08%X\n", this->sld.wHotkey );
printf(" dwRes1 = 0x08%X\n", this->sld.dwRes1 );
printf(" dwRes2 = 0x08%X\n", this->sld.dwRes2 );
printf("\n[Strings]\n");
if (this->pszName)
{
printf( " pszName = " );
if (this->sld.dwFlags & SLDF_UNICODE)
{
CHAR szTemp[ 256 ];
WideCharToMultiByte( CP_ACP, 0,
(LPWSTR)this->pszName,
-1,
szTemp,
256,
NULL,
NULL
);
printf( "(UNICODE) %s\n", szTemp );
}
else
printf( "%s\n", (LPSTR)this->pszName );
}
if (this->pszRelPath)
{
printf( " pszRelPath = " );
if (this->sld.dwFlags & SLDF_UNICODE)
{
CHAR szTemp[ 256 ];
WideCharToMultiByte( CP_ACP, 0,
(LPWSTR)this->pszRelPath,
-1,
szTemp,
256,
NULL,
NULL
);
printf( "(UNICODE) %s\n", szTemp );
}
else
printf( "%s\n", (LPSTR)this->pszRelPath );
}
if (this->pszWorkingDir)
{
printf( " pszWorkingDir = " );
if (this->sld.dwFlags & SLDF_UNICODE)
{
CHAR szTemp[ 256 ];
WideCharToMultiByte( CP_ACP, 0,
(LPWSTR)this->pszWorkingDir,
-1,
szTemp,
256,
NULL,
NULL
);
printf( "(UNICODE) %s\n", szTemp );
}
else
printf( "%s\n", (LPSTR)this->pszWorkingDir );
}
if (this->pszArgs)
{
printf( " pszArgs = " );
if (this->sld.dwFlags & SLDF_UNICODE)
{
CHAR szTemp[ 256 ];
WideCharToMultiByte( CP_ACP, 0,
(LPWSTR)this->pszArgs,
-1,
szTemp,
256,
NULL,
NULL
);
printf( "(UNICODE) %s\n", szTemp );
}
else
printf( "%s\n", (LPSTR)this->pszArgs );
}
if (this->pszIconLocation)
{
printf( " pszIconLocation = " );
if (this->sld.dwFlags & SLDF_UNICODE)
{
CHAR szTemp[ 256 ];
WideCharToMultiByte( CP_ACP, 0,
(LPWSTR)this->pszIconLocation,
-1,
szTemp,
256,
NULL,
NULL
);
printf( "(UNICODE) %s\n", szTemp );
}
else
printf( "%s\n", (LPSTR)this->pszIconLocation );
}
if (this->pExtraData)
{
LPEXP_SZ_LINK lpData = (LPEXP_SZ_LINK)this->pExtraData;
while( lpData && lpData->cbSize!=0 )
{
switch( lpData->dwSignature )
{
case EXP_SZ_LINK_SIG:
{
CHAR szTemp[ 256 ];
printf("\n[Extra Data -- EXP_SZ_LINK_SIG info]\n");
printf(" cbSize = 0x%X bytes\n", lpData->cbSize );
printf(" dwSignature = 0x%X\n", lpData->dwSignature );
printf(" szTarget = %s\n", lpData->szTarget );
WideCharToMultiByte( CP_ACP, 0, lpData->swzTarget, -1, szTemp, 256, NULL, NULL );
printf(" swzTarget = (UNICODE) %s\n\n", szTemp );
}
break;
case NT_CONSOLE_PROPS_SIG:
{
CHAR szTemp[ 256 ];
INT i;
LPNT_CONSOLE_PROPS lpConData = (LPNT_CONSOLE_PROPS)lpData;
printf("\n[Extra Data -- NT_CONSOLE_PROPS_SIG info]\n");
printf(" cbSize = 0x%X bytes\n", lpConData->cbSize );
printf(" dwSignature = 0x%X\n", lpConData->dwSignature );
printf(" wFillAttribute = 0x%04X\n", lpConData->wFillAttribute );
printf(" wPopupFillAttribute = 0x%04X\n", lpConData->wPopupFillAttribute );
printf(" dwScreenBufferSize = (%d , %d)\n", lpConData->dwScreenBufferSize.X, lpConData->dwScreenBufferSize.Y );
printf(" dwWindowSize = (%d , %d)\n", lpConData->dwWindowSize.X, lpConData->dwWindowSize.Y );
printf(" dwWindowOrigin = (%d , %d)\n", lpConData->dwWindowOrigin.X, lpConData->dwWindowOrigin.Y );
printf(" nFont = %d\n", lpConData->nFont );
printf(" nInputBufferSize = %d\n", lpConData->nInputBufferSize );
printf(" dwFontSize = (%d , %d)\n", lpConData->dwFontSize.X, lpConData->dwFontSize.Y );
printf(" uFontFamily = 0x%08X\n", lpConData->uFontFamily );
printf(" uFontWeight = 0x%08X\n", lpConData->uFontWeight );
WideCharToMultiByte( CP_ACP, 0, lpConData->FaceName, LF_FACESIZE, szTemp, LF_FACESIZE, NULL, NULL );
szTemp[ LF_FACESIZE ] = (CHAR)0;
printf(" FaceName = %s\n", szTemp );
printf(" uCursorSize = %d\n", lpConData->uCursorSize );
printf(" bFullScreen = %s\n", lpConData->bFullScreen ? "TRUE" : "FALSE" );
printf(" bQuickEdit = %s\n", lpConData->bQuickEdit ? "TRUE" : "FALSE" );
printf(" bInsertMode = %s\n", lpConData->bInsertMode ? "TRUE" : "FALSE" );
printf(" bAutoPosition = %s\n", lpConData->bAutoPosition ? "TRUE" : "FALSE" );
printf(" uHistoryBufferSize = %d\n", lpConData->uHistoryBufferSize );
printf(" uNumHistoryBuffers = %d\n", lpConData->uNumberOfHistoryBuffers );
printf(" bHistoryNoDup = %s\n", lpConData->bHistoryNoDup ? "TRUE" : "FALSE" );
printf(" ColorTable = [" );
i=0;
while( i < 16 )
{
printf("\n ");
printf("0x%08X ", lpConData->ColorTable[i++]);
printf("0x%08X ", lpConData->ColorTable[i++]);
printf("0x%08X ", lpConData->ColorTable[i++]);
printf("0x%08X ", lpConData->ColorTable[i++]);
}
printf( "]\n\n" );
}
break;
case NT_FE_CONSOLE_PROPS_SIG:
{
LPNT_FE_CONSOLE_PROPS lpFEConData = (LPNT_FE_CONSOLE_PROPS)lpData;
printf("\n[Extra Data -- NT_FE_CONSOLE_PROPS_SIG info]\n");
printf(" cbSize = 0x%X bytes\n", lpFEConData->cbSize );
printf(" dwSignature = 0x%X\n", lpFEConData->dwSignature );
printf(" CodePage = %d\n\n", lpFEConData->uCodePage );
}
break;
case EXP_DARWIN_ID_SIG:
{
CHAR szTemp[ 256 ];
LPEXP_DARWIN_LINK lpDarwin = (LPEXP_DARWIN_LINK)lpData;
printf("\n[Extra Data -- EXP_DARWIN_ID_SIG info]\n");
printf(" szDarwinID = %s\n", lpDarwin->szDarwinID );
WideCharToMultiByte( CP_ACP, 0, lpDarwin->szwDarwinID, -1, szTemp, 256, NULL, NULL );
printf(" szwDarwinID = (UNICODE) %s\n\n", szTemp );
}
break;
case EXP_SPECIAL_FOLDER_SIG:
{
LPEXP_SPECIAL_FOLDER lpFolder = (LPEXP_SPECIAL_FOLDER)lpData;
printf("\n[Extra Data -- EXP_SPECIAL_FOLDER_SIG info]\n");
printf(" idSpecialFolder = 0x%X\n", lpFolder->idSpecialFolder );
printf(" cbOffset = 0x%X\n\n", lpFolder->cbOffset );
}
break;
#ifdef WINNT
case EXP_TRACKER_SIG:
{
LPEXP_TRACKER lpTracker = (LPEXP_TRACKER)lpData;
WCHAR wszGUID[ MAX_PATH ];
printf("\n[Extra Data -- EXP_TRACKER_SIG info]\n");
#if 0
// BUGBUG (reinerf) - traker info looks like a byte-array, how do we dump it?
printf(" abTracker = 0x%X\n", lpTracker->abTracker);
#endif
}
#endif
} // end swtich
(LPBYTE)lpData += lpData->cbSize;
}
LocalFree( this->pExtraData );
}
if (this->pidl)
LocalFree( (HLOCAL)this->pidl );
if (this->pli)
LocalFree( this->pli );
if (this->pszName)
HeapFree( GetProcessHeap(), 0, this->pszName );
if (this->pszRelPath)
HeapFree( GetProcessHeap(), 0, this->pszRelPath );
if (this->pszWorkingDir)
HeapFree( GetProcessHeap(), 0, this->pszWorkingDir );
if (this->pszArgs)
HeapFree( GetProcessHeap(), 0, this->pszArgs );
if (this->pszIconLocation)
HeapFree( GetProcessHeap(), 0, this->pszIconLocation );
return(0);
}
|
234959.c | #include "cerberus.h"
/* PR tree-optimization/49712 */
int a[2], b, c, d, e;
void
foo (int x, int y)
{
}
int
bar (void)
{
int i;
for (; d <= 0; d = 1)
for (i = 0; i < 4; i++)
for (e = 0; e; e = 1)
;
return 0;
}
int
main (void)
{
for (b = 0; b < 2; b++)
while (c)
foo (a[b] = 0, bar ());
return 0;
}
|
801268.c | /* Serialport functions for debugging
*
* Copyright (c) 2000 Axis Communications AB
*
* Authors: Bjorn Wesen
*
* Exports:
* console_print_etrax(char *buf)
* int getDebugChar()
* putDebugChar(int)
* enableDebugIRQ()
* init_etrax_debug()
*
* $Log: debugport.c,v $
* Revision 1.11 2003/07/07 09:53:36 starvik
* Revert all the 2.5.74 merge changes to make the console work again
*
* Revision 1.9 2003/02/17 17:07:23 starvik
* Solved the problem with corrupted debug output (from Linux 2.4)
* * Wait until DMA, FIFO and pipe is empty before and after transmissions
* * Buffer data until a FIFO flush can be triggered.
*
* Revision 1.8 2003/01/22 06:48:36 starvik
* Fixed warnings issued by GCC 3.2.1
*
* Revision 1.7 2002/12/12 08:26:32 starvik
* Don't use C-comments inside CVS comments
*
* Revision 1.6 2002/12/11 15:42:02 starvik
* Extracted v10 (ETRAX 100LX) specific stuff from arch/cris/kernel/
*
* Revision 1.5 2002/11/20 06:58:03 starvik
* Compiles with kgdb
*
* Revision 1.4 2002/11/19 14:35:24 starvik
* Changes from linux 2.4
* Changed struct initializer syntax to the currently prefered notation
*
* Revision 1.3 2002/11/06 09:47:03 starvik
* Modified for new interrupt macros
*
* Revision 1.2 2002/01/21 15:21:50 bjornw
* Update for kdev_t changes
*
* Revision 1.6 2001/04/17 13:58:39 orjanf
* * Renamed CONFIG_KGDB to CONFIG_ETRAX_KGDB.
*
* Revision 1.5 2001/03/26 14:22:05 bjornw
* Namechange of some config options
*
* Revision 1.4 2000/10/06 12:37:26 bjornw
* Use physical addresses when talking to DMA
*
*
*/
#include <linux/config.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/major.h>
#include <linux/delay.h>
#include <asm/system.h>
#include <asm/arch/svinto.h>
#include <asm/io.h> /* Get SIMCOUT. */
/* Which serial-port is our debug port ? */
#if defined(CONFIG_ETRAX_DEBUG_PORT0) || defined(CONFIG_ETRAX_DEBUG_PORT_NULL)
#define DEBUG_PORT_IDX 0
#define DEBUG_OCMD R_DMA_CH6_CMD
#define DEBUG_FIRST R_DMA_CH6_FIRST
#define DEBUG_OCLRINT R_DMA_CH6_CLR_INTR
#define DEBUG_STATUS R_DMA_CH6_STATUS
#define DEBUG_READ R_SERIAL0_READ
#define DEBUG_WRITE R_SERIAL0_TR_DATA
#define DEBUG_TR_CTRL R_SERIAL0_TR_CTRL
#define DEBUG_REC_CTRL R_SERIAL0_REC_CTRL
#define DEBUG_IRQ IO_STATE(R_IRQ_MASK1_SET, ser0_data, set)
#define DEBUG_DMA_IRQ_CLR IO_STATE(R_IRQ_MASK2_CLR, dma6_descr, clr)
#endif
#ifdef CONFIG_ETRAX_DEBUG_PORT1
#define DEBUG_PORT_IDX 1
#define DEBUG_OCMD R_DMA_CH8_CMD
#define DEBUG_FIRST R_DMA_CH8_FIRST
#define DEBUG_OCLRINT R_DMA_CH8_CLR_INTR
#define DEBUG_STATUS R_DMA_CH8_STATUS
#define DEBUG_READ R_SERIAL1_READ
#define DEBUG_WRITE R_SERIAL1_TR_DATA
#define DEBUG_TR_CTRL R_SERIAL1_TR_CTRL
#define DEBUG_REC_CTRL R_SERIAL1_REC_CTRL
#define DEBUG_IRQ IO_STATE(R_IRQ_MASK1_SET, ser1_data, set)
#define DEBUG_DMA_IRQ_CLR IO_STATE(R_IRQ_MASK2_CLR, dma8_descr, clr)
#endif
#ifdef CONFIG_ETRAX_DEBUG_PORT2
#define DEBUG_PORT_IDX 2
#define DEBUG_OCMD R_DMA_CH2_CMD
#define DEBUG_FIRST R_DMA_CH2_FIRST
#define DEBUG_OCLRINT R_DMA_CH2_CLR_INTR
#define DEBUG_STATUS R_DMA_CH2_STATUS
#define DEBUG_READ R_SERIAL2_READ
#define DEBUG_WRITE R_SERIAL2_TR_DATA
#define DEBUG_TR_CTRL R_SERIAL2_TR_CTRL
#define DEBUG_REC_CTRL R_SERIAL2_REC_CTRL
#define DEBUG_IRQ IO_STATE(R_IRQ_MASK1_SET, ser2_data, set)
#define DEBUG_DMA_IRQ_CLR IO_STATE(R_IRQ_MASK2_CLR, dma2_descr, clr)
#endif
#ifdef CONFIG_ETRAX_DEBUG_PORT3
#define DEBUG_PORT_IDX 3
#define DEBUG_OCMD R_DMA_CH4_CMD
#define DEBUG_FIRST R_DMA_CH4_FIRST
#define DEBUG_OCLRINT R_DMA_CH4_CLR_INTR
#define DEBUG_STATUS R_DMA_CH4_STATUS
#define DEBUG_READ R_SERIAL3_READ
#define DEBUG_WRITE R_SERIAL3_TR_DATA
#define DEBUG_TR_CTRL R_SERIAL3_TR_CTRL
#define DEBUG_REC_CTRL R_SERIAL3_REC_CTRL
#define DEBUG_IRQ IO_STATE(R_IRQ_MASK1_SET, ser3_data, set)
#define DEBUG_DMA_IRQ_CLR IO_STATE(R_IRQ_MASK2_CLR, dma4_descr, clr)
#endif
#define MIN_SIZE 32 /* Size that triggers the FIFO to flush characters to interface */
/* Write a string of count length to the console (debug port) using DMA, polled
* for completion. Interrupts are disabled during the whole process. Some
* caution needs to be taken to not interfere with ttyS business on this port.
*/
static void
console_write(struct console *co, const char *buf, unsigned int len)
{
static struct etrax_dma_descr descr;
static struct etrax_dma_descr descr2;
static char tmp_buf[MIN_SIZE];
static int tmp_size = 0;
unsigned long flags;
#ifdef CONFIG_ETRAX_DEBUG_PORT_NULL
/* no debug printout at all */
return;
#endif
#ifdef CONFIG_SVINTO_SIM
/* no use to simulate the serial debug output */
SIMCOUT(buf,len);
return;
#endif
local_save_flags(flags);
local_irq_disable();
#ifdef CONFIG_ETRAX_KGDB
/* kgdb needs to output debug info using the gdb protocol */
putDebugString(buf, len);
local_irq_restore(flags);
return;
#endif
/* To make this work together with the real serial port driver
* we have to make sure that everything is flushed when we leave
* here. The following steps are made to assure this:
* 1. Wait until DMA stops, FIFO is empty and serial port pipeline empty.
* 2. Write at least half the FIFO to trigger flush to serial port.
* 3. Wait until DMA stops, FIFO is empty and serial port pipeline empty.
*/
/* Do we have enough characters to make the DMA/FIFO happy? */
if (tmp_size + len < MIN_SIZE)
{
int size = min((int)(MIN_SIZE - tmp_size),(int)len);
memcpy(&tmp_buf[tmp_size], buf, size);
tmp_size += size;
len -= size;
/* Pad with space if complete line */
if (tmp_buf[tmp_size-1] == '\n')
{
memset(&tmp_buf[tmp_size-1], ' ', MIN_SIZE - tmp_size);
tmp_buf[MIN_SIZE - 1] = '\n';
tmp_size = MIN_SIZE;
len = 0;
}
else
{
/* Wait for more characters */
local_irq_restore(flags);
return;
}
}
/* make sure the transmitter is enabled.
* NOTE: this overrides any setting done in ttySx, to 8N1, no auto-CTS.
* in the future, move the tr/rec_ctrl shadows from etrax100ser.c to
* shadows.c and use it here as well...
*/
*DEBUG_TR_CTRL = 0x40;
while(*DEBUG_OCMD & 7); /* Until DMA is not running */
while(*DEBUG_STATUS & 0x7f); /* wait until output FIFO is empty as well */
udelay(200); /* Wait for last two characters to leave the serial transmitter */
if (tmp_size)
{
descr.ctrl = len ? 0 : d_eop | d_wait | d_eol;
descr.sw_len = tmp_size;
descr.buf = virt_to_phys(tmp_buf);
descr.next = virt_to_phys(&descr2);
descr2.ctrl = d_eop | d_wait | d_eol;
descr2.sw_len = len;
descr2.buf = virt_to_phys((char*)buf);
}
else
{
descr.ctrl = d_eop | d_wait | d_eol;
descr.sw_len = len;
descr.buf = virt_to_phys((char*)buf);
}
*DEBUG_FIRST = virt_to_phys(&descr); /* write to R_DMAx_FIRST */
*DEBUG_OCMD = 1; /* dma command start -> R_DMAx_CMD */
/* wait until the output dma channel is ready again */
while(*DEBUG_OCMD & 7);
while(*DEBUG_STATUS & 0x7f);
udelay(200);
tmp_size = 0;
local_irq_restore(flags);
}
/* legacy function */
void
console_print_etrax(const char *buf)
{
console_write(NULL, buf, strlen(buf));
}
/* Use polling to get a single character FROM the debug port */
int
getDebugChar(void)
{
unsigned long readval;
do {
readval = *DEBUG_READ;
} while(!(readval & IO_MASK(R_SERIAL0_READ, data_avail)));
return (readval & IO_MASK(R_SERIAL0_READ, data_in));
}
/* Use polling to put a single character to the debug port */
void
putDebugChar(int val)
{
while(!(*DEBUG_READ & IO_MASK(R_SERIAL0_READ, tr_ready))) ;
;
*DEBUG_WRITE = val;
}
/* Enable irq for receiving chars on the debug port, used by kgdb */
void
enableDebugIRQ(void)
{
*R_IRQ_MASK1_SET = DEBUG_IRQ;
/* use R_VECT_MASK directly, since we really bypass Linux normal
* IRQ handling in kgdb anyway, we don't need to use enable_irq
*/
*R_VECT_MASK_SET = IO_STATE(R_VECT_MASK_SET, serial, set);
*DEBUG_REC_CTRL = IO_STATE(R_SERIAL0_REC_CTRL, rec_enable, enable);
}
static kdev_t
console_device(struct console *c)
{
return mk_kdev(TTY_MAJOR, 64 + c->index);
}
static int __init
console_setup(struct console *co, char *options)
{
return 0;
}
static struct console sercons = {
.name = "ttyS",
.write = console_write,
.read = NULL,
.device = console_device,
.unblank = NULL,
.setup = console_setup,
.flags = CON_PRINTBUFFER,
.index = DEBUG_PORT_IDX,
.cflag = 0,
.next = NULL
};
/*
* Register console (for printk's etc)
*/
void __init
init_etrax_debug(void)
{
register_console(&sercons);
}
|
594610.c | /*
* Copyright (c) 2004-2010 The Trustees of Indiana University.
* All rights reserved.
* Copyright (c) 2004-2011 The Trustees of the University of Tennessee.
* All rights reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNIST_H */
#include "opal/mca/mca.h"
#include "opal/mca/base/base.h"
#include "opal/util/output.h"
#include "opal/util/opal_environ.h"
#include "ompi/mca/crcp/crcp.h"
#include "ompi/mca/crcp/base/base.h"
#include "crcp_bkmrk.h"
#include "crcp_bkmrk_pml.h"
/*
* Coord module
*/
static ompi_crcp_base_module_t loc_module = {
/** Initialization Function */
ompi_crcp_bkmrk_module_init,
/** Finalization Function */
ompi_crcp_bkmrk_module_finalize,
/** Quiesce interface */
ompi_crcp_bkmrk_quiesce_start,
ompi_crcp_bkmrk_quiesce_end,
/** PML Wrapper */
NULL, /* ompi_crcp_bkmrk_pml_enable, */
NULL, /* ompi_crcp_bkmrk_pml_add_comm, */
NULL, /* ompi_crcp_bkmrk_pml_del_comm, */
ompi_crcp_bkmrk_pml_add_procs,
ompi_crcp_bkmrk_pml_del_procs,
NULL, /* ompi_crcp_bkmrk_pml_progress, */
ompi_crcp_bkmrk_pml_iprobe,
ompi_crcp_bkmrk_pml_probe,
ompi_crcp_bkmrk_pml_isend_init,
ompi_crcp_bkmrk_pml_isend,
ompi_crcp_bkmrk_pml_send,
ompi_crcp_bkmrk_pml_irecv_init,
ompi_crcp_bkmrk_pml_irecv,
ompi_crcp_bkmrk_pml_recv,
ompi_crcp_bkmrk_pml_dump,
ompi_crcp_bkmrk_pml_start,
ompi_crcp_bkmrk_pml_ft_event,
/* Request Functions */
ompi_crcp_bkmrk_request_complete,
/* BTL Wrapper Functions */
NULL, /* btl_add_procs */
NULL, /* btl_del_procs */
NULL, /* btl_register */
NULL, /* btl_finalize */
NULL, /* btl_alloc */
NULL, /* btl_free */
NULL, /* btl_prepare_src */
NULL, /* btl_prepare_dst */
NULL, /* btl_send */
NULL, /* btl_put */
NULL, /* btl_get */
NULL, /* btl_dump */
NULL /* btl_ft_event */
};
/************************************
* Locally Global vars & functions :)
************************************/
/************************
* Function Definitions
************************/
/*
* MCA Functions
*/
int ompi_crcp_bkmrk_component_query(mca_base_module_t **module, int *priority)
{
opal_output_verbose(10, mca_crcp_bkmrk_component.super.output_handle,
"crcp:bkmrk: component_query()");
*priority = mca_crcp_bkmrk_component.super.priority;
*module = (mca_base_module_t *)&loc_module;
return OMPI_SUCCESS;
}
int ompi_crcp_bkmrk_module_init(void)
{
opal_output_verbose(10, mca_crcp_bkmrk_component.super.output_handle,
"crcp:bkmrk: module_init()");
ompi_crcp_bkmrk_pml_init();
return OMPI_SUCCESS;
}
int ompi_crcp_bkmrk_module_finalize(void)
{
opal_output_verbose(10, mca_crcp_bkmrk_component.super.output_handle,
"crcp:bkmrk: module_finalize()");
ompi_crcp_bkmrk_pml_finalize();
return OMPI_SUCCESS;
}
int ompi_crcp_bkmrk_quiesce_start(MPI_Info *info)
{
OPAL_OUTPUT_VERBOSE((10, mca_crcp_bkmrk_component.super.output_handle,
"crcp:bkmrk: quiesce_start(--)"));
#if 0
if( OMPI_SUCCESS != (ret = ompi_crcp_bkmrk_pml_quiesce_start(QUIESCE_TAG_CKPT)) ) {
;
}
return OMPI_SUCCESS;
#else
return OMPI_ERR_NOT_IMPLEMENTED;
#endif
}
int ompi_crcp_bkmrk_quiesce_end(MPI_Info *info)
{
OPAL_OUTPUT_VERBOSE((10, mca_crcp_bkmrk_component.super.output_handle,
"crcp:bkmrk: quiesce_end(--)"));
#if 0
if( OMPI_SUCCESS != (ret = ompi_crcp_bkmrk_pml_quiesce_end(QUIESCE_TAG_CONTINUE) ) ) {
;
}
return OMPI_SUCCESS;
#else
return OMPI_ERR_NOT_IMPLEMENTED;
#endif
}
/******************
* Local functions
******************/
|
415961.c | /* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CJWTKitBoringSSL_x509.h>
#include <limits.h>
#include <CJWTKitBoringSSL_asn1.h>
#include <CJWTKitBoringSSL_digest.h>
#include <CJWTKitBoringSSL_dsa.h>
#include <CJWTKitBoringSSL_evp.h>
#include <CJWTKitBoringSSL_mem.h>
#include <CJWTKitBoringSSL_rsa.h>
#include <CJWTKitBoringSSL_stack.h>
int X509_verify(X509 *a, EVP_PKEY *r)
{
if (X509_ALGOR_cmp(a->sig_alg, a->cert_info->signature)) {
OPENSSL_PUT_ERROR(X509, X509_R_SIGNATURE_ALGORITHM_MISMATCH);
return 0;
}
return (ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF), a->sig_alg,
a->signature, a->cert_info, r));
}
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r)
{
return (ASN1_item_verify(ASN1_ITEM_rptr(X509_REQ_INFO),
a->sig_alg, a->signature, a->req_info, r));
}
int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
x->cert_info->enc.modified = 1;
return (ASN1_item_sign(ASN1_ITEM_rptr(X509_CINF), x->cert_info->signature,
x->sig_alg, x->signature, x->cert_info, pkey, md));
}
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx)
{
x->cert_info->enc.modified = 1;
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CINF),
x->cert_info->signature,
x->sig_alg, x->signature, x->cert_info, ctx);
}
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md)
{
return (ASN1_item_sign(ASN1_ITEM_rptr(X509_REQ_INFO), x->sig_alg, NULL,
x->signature, x->req_info, pkey, md));
}
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx)
{
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_REQ_INFO),
x->sig_alg, NULL, x->signature, x->req_info,
ctx);
}
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md)
{
x->crl->enc.modified = 1;
return (ASN1_item_sign(ASN1_ITEM_rptr(X509_CRL_INFO), x->crl->sig_alg,
x->sig_alg, x->signature, x->crl, pkey, md));
}
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx)
{
x->crl->enc.modified = 1;
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CRL_INFO),
x->crl->sig_alg, x->sig_alg, x->signature,
x->crl, ctx);
}
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md)
{
return (ASN1_item_sign(ASN1_ITEM_rptr(NETSCAPE_SPKAC), x->sig_algor, NULL,
x->signature, x->spkac, pkey, md));
}
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *x, EVP_PKEY *pkey)
{
return (ASN1_item_verify(ASN1_ITEM_rptr(NETSCAPE_SPKAC), x->sig_algor,
x->signature, x->spkac, pkey));
}
#ifndef OPENSSL_NO_FP_API
X509 *d2i_X509_fp(FILE *fp, X509 **x509)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509), fp, x509);
}
int i2d_X509_fp(FILE *fp, X509 *x509)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509), fp, x509);
}
#endif
X509 *d2i_X509_bio(BIO *bp, X509 **x509)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509), bp, x509);
}
int i2d_X509_bio(BIO *bp, X509 *x509)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509), bp, x509);
}
#ifndef OPENSSL_NO_FP_API
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl);
}
int i2d_X509_CRL_fp(FILE *fp, X509_CRL *crl)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl);
}
#endif
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl);
}
int i2d_X509_CRL_bio(BIO *bp, X509_CRL *crl)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl);
}
#ifndef OPENSSL_NO_FP_API
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_REQ), fp, req);
}
int i2d_X509_REQ_fp(FILE *fp, X509_REQ *req)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_REQ), fp, req);
}
#endif
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509_REQ), bp, req);
}
int i2d_X509_REQ_bio(BIO *bp, X509_REQ *req)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_REQ), bp, req);
}
#ifndef OPENSSL_NO_FP_API
#define IMPLEMENT_D2I_FP(type, name, bio_func) \
type *name(FILE *fp, type **obj) { \
BIO *bio = BIO_new_fp(fp, BIO_NOCLOSE); \
if (bio == NULL) { \
return NULL; \
} \
type *ret = bio_func(bio, obj); \
BIO_free(bio); \
return ret; \
}
#define IMPLEMENT_I2D_FP(type, name, bio_func) \
int name(FILE *fp, type *obj) { \
BIO *bio = BIO_new_fp(fp, BIO_NOCLOSE); \
if (bio == NULL) { \
return 0; \
} \
int ret = bio_func(bio, obj); \
BIO_free(bio); \
return ret; \
}
IMPLEMENT_D2I_FP(RSA, d2i_RSAPrivateKey_fp, d2i_RSAPrivateKey_bio)
IMPLEMENT_I2D_FP(RSA, i2d_RSAPrivateKey_fp, i2d_RSAPrivateKey_bio)
IMPLEMENT_D2I_FP(RSA, d2i_RSAPublicKey_fp, d2i_RSAPublicKey_bio)
IMPLEMENT_I2D_FP(RSA, i2d_RSAPublicKey_fp, i2d_RSAPublicKey_bio)
IMPLEMENT_D2I_FP(RSA, d2i_RSA_PUBKEY_fp, d2i_RSA_PUBKEY_bio)
IMPLEMENT_I2D_FP(RSA, i2d_RSA_PUBKEY_fp, i2d_RSA_PUBKEY_bio)
#endif
#define IMPLEMENT_D2I_BIO(type, name, d2i_func) \
type *name(BIO *bio, type **obj) { \
uint8_t *data; \
size_t len; \
if (!BIO_read_asn1(bio, &data, &len, 100 * 1024)) { \
return NULL; \
} \
const uint8_t *ptr = data; \
type *ret = d2i_func(obj, &ptr, (long)len); \
OPENSSL_free(data); \
return ret; \
}
#define IMPLEMENT_I2D_BIO(type, name, i2d_func) \
int name(BIO *bio, type *obj) { \
uint8_t *data = NULL; \
int len = i2d_func(obj, &data); \
if (len < 0) { \
return 0; \
} \
int ret = BIO_write_all(bio, data, len); \
OPENSSL_free(data); \
return ret; \
}
IMPLEMENT_D2I_BIO(RSA, d2i_RSAPrivateKey_bio, d2i_RSAPrivateKey)
IMPLEMENT_I2D_BIO(RSA, i2d_RSAPrivateKey_bio, i2d_RSAPrivateKey)
IMPLEMENT_D2I_BIO(RSA, d2i_RSAPublicKey_bio, d2i_RSAPublicKey)
IMPLEMENT_I2D_BIO(RSA, i2d_RSAPublicKey_bio, i2d_RSAPublicKey)
IMPLEMENT_D2I_BIO(RSA, d2i_RSA_PUBKEY_bio, d2i_RSA_PUBKEY)
IMPLEMENT_I2D_BIO(RSA, i2d_RSA_PUBKEY_bio, i2d_RSA_PUBKEY)
#ifndef OPENSSL_NO_DSA
# ifndef OPENSSL_NO_FP_API
IMPLEMENT_D2I_FP(DSA, d2i_DSAPrivateKey_fp, d2i_DSAPrivateKey_bio)
IMPLEMENT_I2D_FP(DSA, i2d_DSAPrivateKey_fp, i2d_DSAPrivateKey_bio)
IMPLEMENT_D2I_FP(DSA, d2i_DSA_PUBKEY_fp, d2i_DSA_PUBKEY_bio)
IMPLEMENT_I2D_FP(DSA, i2d_DSA_PUBKEY_fp, i2d_DSA_PUBKEY_bio)
# endif
IMPLEMENT_D2I_BIO(DSA, d2i_DSAPrivateKey_bio, d2i_DSAPrivateKey)
IMPLEMENT_I2D_BIO(DSA, i2d_DSAPrivateKey_bio, i2d_DSAPrivateKey)
IMPLEMENT_D2I_BIO(DSA, d2i_DSA_PUBKEY_bio, d2i_DSA_PUBKEY)
IMPLEMENT_I2D_BIO(DSA, i2d_DSA_PUBKEY_bio, i2d_DSA_PUBKEY)
#endif
#ifndef OPENSSL_NO_FP_API
IMPLEMENT_D2I_FP(EC_KEY, d2i_ECPrivateKey_fp, d2i_ECPrivateKey_bio)
IMPLEMENT_I2D_FP(EC_KEY, i2d_ECPrivateKey_fp, i2d_ECPrivateKey_bio)
IMPLEMENT_D2I_FP(EC_KEY, d2i_EC_PUBKEY_fp, d2i_EC_PUBKEY_bio)
IMPLEMENT_I2D_FP(EC_KEY, i2d_EC_PUBKEY_fp, i2d_EC_PUBKEY_bio)
#endif
IMPLEMENT_D2I_BIO(EC_KEY, d2i_ECPrivateKey_bio, d2i_ECPrivateKey)
IMPLEMENT_I2D_BIO(EC_KEY, i2d_ECPrivateKey_bio, i2d_ECPrivateKey)
IMPLEMENT_D2I_BIO(EC_KEY, d2i_EC_PUBKEY_bio, d2i_EC_PUBKEY)
IMPLEMENT_I2D_BIO(EC_KEY, i2d_EC_PUBKEY_bio, i2d_EC_PUBKEY)
int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
ASN1_BIT_STRING *key;
key = X509_get0_pubkey_bitstr(data);
if (!key)
return 0;
return EVP_Digest(key->data, key->length, md, len, type, NULL);
}
int X509_digest(const X509 *data, const EVP_MD *type, unsigned char *md,
unsigned int *len)
{
return (ASN1_item_digest
(ASN1_ITEM_rptr(X509), type, (char *)data, md, len));
}
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
return (ASN1_item_digest
(ASN1_ITEM_rptr(X509_CRL), type, (char *)data, md, len));
}
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
return (ASN1_item_digest
(ASN1_ITEM_rptr(X509_REQ), type, (char *)data, md, len));
}
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
return (ASN1_item_digest
(ASN1_ITEM_rptr(X509_NAME), type, (char *)data, md, len));
}
#ifndef OPENSSL_NO_FP_API
IMPLEMENT_D2I_FP(X509_SIG, d2i_PKCS8_fp, d2i_PKCS8_bio)
IMPLEMENT_I2D_FP(X509_SIG, i2d_PKCS8_fp, i2d_PKCS8_bio)
#endif
IMPLEMENT_D2I_BIO(X509_SIG, d2i_PKCS8_bio, d2i_X509_SIG)
IMPLEMENT_I2D_BIO(X509_SIG, i2d_PKCS8_bio, i2d_X509_SIG)
#ifndef OPENSSL_NO_FP_API
IMPLEMENT_D2I_FP(PKCS8_PRIV_KEY_INFO, d2i_PKCS8_PRIV_KEY_INFO_fp,
d2i_PKCS8_PRIV_KEY_INFO_bio)
IMPLEMENT_I2D_FP(PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO_fp,
i2d_PKCS8_PRIV_KEY_INFO_bio)
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, EVP_PKEY *key)
{
PKCS8_PRIV_KEY_INFO *p8inf;
int ret;
p8inf = EVP_PKEY2PKCS8(key);
if (!p8inf)
return 0;
ret = i2d_PKCS8_PRIV_KEY_INFO_fp(fp, p8inf);
PKCS8_PRIV_KEY_INFO_free(p8inf);
return ret;
}
IMPLEMENT_D2I_FP(EVP_PKEY, d2i_PrivateKey_fp, d2i_PrivateKey_bio)
IMPLEMENT_I2D_FP(EVP_PKEY, i2d_PrivateKey_fp, i2d_PrivateKey_bio)
IMPLEMENT_D2I_FP(EVP_PKEY, d2i_PUBKEY_fp, d2i_PUBKEY_bio)
IMPLEMENT_I2D_FP(EVP_PKEY, i2d_PUBKEY_fp, i2d_PUBKEY_bio)
IMPLEMENT_D2I_BIO(PKCS8_PRIV_KEY_INFO, d2i_PKCS8_PRIV_KEY_INFO_bio,
d2i_PKCS8_PRIV_KEY_INFO)
IMPLEMENT_I2D_BIO(PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO_bio,
i2d_PKCS8_PRIV_KEY_INFO)
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, EVP_PKEY *key)
{
PKCS8_PRIV_KEY_INFO *p8inf;
int ret;
p8inf = EVP_PKEY2PKCS8(key);
if (!p8inf)
return 0;
ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf);
PKCS8_PRIV_KEY_INFO_free(p8inf);
return ret;
}
#endif
IMPLEMENT_D2I_BIO(EVP_PKEY, d2i_PrivateKey_bio, d2i_AutoPrivateKey)
IMPLEMENT_I2D_BIO(EVP_PKEY, i2d_PrivateKey_bio, i2d_PrivateKey)
IMPLEMENT_D2I_BIO(EVP_PKEY, d2i_PUBKEY_bio, d2i_PUBKEY)
IMPLEMENT_I2D_BIO(EVP_PKEY, i2d_PUBKEY_bio, i2d_PUBKEY)
IMPLEMENT_D2I_BIO(DH, d2i_DHparams_bio, d2i_DHparams)
IMPLEMENT_I2D_BIO(const DH, i2d_DHparams_bio, i2d_DHparams)
|
595598.c |
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif
#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
#include "kernel/operators.h"
#include "kernel/array.h"
#include "kernel/concat.h"
#include "kernel/fcall.h"
#include "kernel/exception.h"
#include "kernel/string.h"
/**
* Phalcon\Mvc\Model\MetaData
*
* <p>Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc.
* this component collect them and store for further querying by Phalcon\Mvc\Model.
* Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data.</p>
*
* <p>A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:</p>
*
* <code>
* $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
* $attributes = $metaData->getAttributes(new Robots());
* print_r($attributes);
* </code>
*
*/
ZEPHIR_INIT_CLASS(Phalcon_Mvc_Model_MetaData) {
ZEPHIR_REGISTER_CLASS(Phalcon\\Mvc\\Model, MetaData, phalcon, mvc_model_metadata, phalcon_mvc_model_metadata_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS);
zend_declare_property_null(phalcon_mvc_model_metadata_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC);
zend_declare_property_null(phalcon_mvc_model_metadata_ce, SL("_strategy"), ZEND_ACC_PROTECTED TSRMLS_CC);
zend_declare_property_null(phalcon_mvc_model_metadata_ce, SL("_metaData"), ZEND_ACC_PROTECTED TSRMLS_CC);
zend_declare_property_null(phalcon_mvc_model_metadata_ce, SL("_columnMap"), ZEND_ACC_PROTECTED TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_ATTRIBUTES"), 0 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_PRIMARY_KEY"), 1 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_NON_PRIMARY_KEY"), 2 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_NOT_NULL"), 3 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DATA_TYPES"), 4 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DATA_TYPES_NUMERIC"), 5 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DATE_AT"), 6 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DATE_IN"), 7 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_IDENTITY_COLUMN"), 8 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DATA_TYPES_BIND"), 9 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_AUTOMATIC_DEFAULT_INSERT"), 10 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_AUTOMATIC_DEFAULT_UPDATE"), 11 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_DEFAULT_VALUES"), 12 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_EMPTY_STRING_VALUES"), 13 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_COLUMN_MAP"), 0 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_metadata_ce, SL("MODELS_REVERSE_COLUMN_MAP"), 1 TSRMLS_CC);
zend_class_implements(phalcon_mvc_model_metadata_ce TSRMLS_CC, 1, phalcon_di_injectionawareinterface_ce);
return SUCCESS;
}
/**
* Initialize the metadata for certain table
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, _initialize) {
zephir_fcall_cache_entry *_2 = NULL;
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *key, *table, *schema, *strategy = NULL, *className, *metaData, *data = NULL, *modelMetadata = NULL, *modelColumnMap = NULL, *dependencyInjector = NULL, *keyName, *prefixKey = NULL, *_0, *_1, *_3;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 4, 0, &model, &key, &table, &schema);
ZEPHIR_INIT_VAR(strategy);
ZVAL_NULL(strategy);
ZEPHIR_INIT_VAR(className);
zephir_get_class(className, model, 0 TSRMLS_CC);
if (Z_TYPE_P(key) != IS_NULL) {
ZEPHIR_OBS_VAR(metaData);
zephir_read_property_this(&metaData, this_ptr, SL("_metaData"), PH_NOISY_CC);
if (!(zephir_array_isset(metaData, key))) {
ZEPHIR_INIT_VAR(prefixKey);
ZEPHIR_CONCAT_SV(prefixKey, "meta-", key);
ZEPHIR_CALL_METHOD(&data, this_ptr, "read", NULL, 0, prefixKey);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_NULL) {
zephir_update_property_array(this_ptr, SL("_metaData"), key, data TSRMLS_CC);
} else {
if ((zephir_method_exists_ex(model, SS("metadata") TSRMLS_CC) == SUCCESS)) {
ZEPHIR_CALL_METHOD(&modelMetadata, model, "metadata", NULL, 0);
zephir_check_call_status();
if (Z_TYPE_P(modelMetadata) != IS_ARRAY) {
ZEPHIR_INIT_VAR(_0);
object_init_ex(_0, phalcon_mvc_model_exception_ce);
ZEPHIR_INIT_VAR(_1);
ZEPHIR_CONCAT_SV(_1, "Invalid meta-data for model ", className);
ZEPHIR_CALL_METHOD(NULL, _0, "__construct", NULL, 9, _1);
zephir_check_call_status();
zephir_throw_exception_debug(_0, "phalcon/mvc/model/metadata.zep", 119 TSRMLS_CC);
ZEPHIR_MM_RESTORE();
return;
}
} else {
ZEPHIR_OBS_VAR(dependencyInjector);
zephir_read_property_this(&dependencyInjector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC);
ZEPHIR_CALL_METHOD(&strategy, this_ptr, "getstrategy", &_2, 0);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&modelMetadata, strategy, "getmetadata", NULL, 0, model, dependencyInjector);
zephir_check_call_status();
}
zephir_update_property_array(this_ptr, SL("_metaData"), key, modelMetadata TSRMLS_CC);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "write", NULL, 0, prefixKey, modelMetadata);
zephir_check_call_status();
}
}
}
if (!(ZEPHIR_GLOBAL(orm).column_renaming)) {
RETURN_MM_NULL();
}
ZEPHIR_INIT_VAR(keyName);
zephir_fast_strtolower(keyName, className);
_3 = zephir_fetch_nproperty_this(this_ptr, SL("_columnMap"), PH_NOISY_CC);
if (zephir_array_isset(_3, keyName)) {
RETURN_MM_NULL();
}
ZEPHIR_INIT_NVAR(prefixKey);
ZEPHIR_CONCAT_SV(prefixKey, "map-", keyName);
ZEPHIR_CALL_METHOD(&data, this_ptr, "read", NULL, 0, prefixKey);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_NULL) {
zephir_update_property_array(this_ptr, SL("_columnMap"), keyName, data TSRMLS_CC);
RETURN_MM_NULL();
}
if (Z_TYPE_P(strategy) != IS_OBJECT) {
ZEPHIR_OBS_NVAR(dependencyInjector);
zephir_read_property_this(&dependencyInjector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC);
ZEPHIR_CALL_METHOD(&strategy, this_ptr, "getstrategy", &_2, 0);
zephir_check_call_status();
}
ZEPHIR_CALL_METHOD(&modelColumnMap, strategy, "getcolumnmaps", NULL, 0, model, dependencyInjector);
zephir_check_call_status();
zephir_update_property_array(this_ptr, SL("_columnMap"), keyName, modelColumnMap TSRMLS_CC);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "write", NULL, 0, prefixKey, modelColumnMap);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
/**
* Sets the DependencyInjector container
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, setDI) {
zval *dependencyInjector;
zephir_fetch_params(0, 1, 0, &dependencyInjector);
zephir_update_property_this(this_ptr, SL("_dependencyInjector"), dependencyInjector TSRMLS_CC);
}
/**
* Returns the DependencyInjector container
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getDI) {
RETURN_MEMBER(this_ptr, "_dependencyInjector");
}
/**
* Set the meta-data extraction strategy
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, setStrategy) {
zval *strategy;
zephir_fetch_params(0, 1, 0, &strategy);
zephir_update_property_this(this_ptr, SL("_strategy"), strategy TSRMLS_CC);
}
/**
* Return the strategy to obtain the meta-data
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getStrategy) {
int ZEPHIR_LAST_CALL_STATUS;
zval *strategy = NULL;
ZEPHIR_MM_GROW();
ZEPHIR_OBS_VAR(strategy);
zephir_read_property_this(&strategy, this_ptr, SL("_strategy"), PH_NOISY_CC);
if (Z_TYPE_P(strategy) == IS_NULL) {
ZEPHIR_INIT_NVAR(strategy);
object_init_ex(strategy, phalcon_mvc_model_metadata_strategy_introspection_ce);
if (zephir_has_constructor(strategy TSRMLS_CC)) {
ZEPHIR_CALL_METHOD(NULL, strategy, "__construct", NULL, 0);
zephir_check_call_status();
}
zephir_update_property_this(this_ptr, SL("_strategy"), strategy TSRMLS_CC);
}
RETURN_CCTOR(strategy);
}
/**
* Reads the complete meta-data for certain model
*
*<code>
* print_r($metaData->readMetaData(new Robots());
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, readMetaData) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *source = NULL, *schema = NULL, *key, *_0, *_1, *_2, *_3;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_CALL_METHOD(&source, model, "getsource", NULL, 0);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&schema, model, "getschema", NULL, 0);
zephir_check_call_status();
ZEPHIR_INIT_VAR(_0);
zephir_get_class(_0, model, 1 TSRMLS_CC);
ZEPHIR_INIT_VAR(key);
ZEPHIR_CONCAT_VSVV(key, _0, "-", schema, source);
_1 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
if (!(zephir_array_isset(_1, key))) {
ZEPHIR_CALL_METHOD(NULL, this_ptr, "_initialize", NULL, 10, model, key, source, schema);
zephir_check_call_status();
}
_2 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
zephir_array_fetch(&_3, _2, key, PH_NOISY | PH_READONLY, "phalcon/mvc/model/metadata.zep", 249 TSRMLS_CC);
RETURN_CTOR(_3);
}
/**
* Reads meta-data for certain model
*
*<code>
* print_r($metaData->readMetaDataIndex(new Robots(), 0);
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, readMetaDataIndex) {
int index, ZEPHIR_LAST_CALL_STATUS;
zval *model, *index_param = NULL, *source = NULL, *schema = NULL, *key, *metaData, *_0, *_1, *_2, *_3, *_4, *_5;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &index_param);
index = zephir_get_intval(index_param);
ZEPHIR_CALL_METHOD(&source, model, "getsource", NULL, 0);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&schema, model, "getschema", NULL, 0);
zephir_check_call_status();
ZEPHIR_INIT_VAR(_0);
zephir_get_class(_0, model, 1 TSRMLS_CC);
ZEPHIR_INIT_VAR(key);
ZEPHIR_CONCAT_VSVV(key, _0, "-", schema, source);
ZEPHIR_OBS_VAR(metaData);
_1 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
zephir_array_fetch(&_2, _1, key, PH_READONLY, "phalcon/mvc/model/metadata.zep", 271 TSRMLS_CC);
if (zephir_array_isset_long_fetch(&metaData, _2, index, 0 TSRMLS_CC)) {
RETURN_CCTOR(metaData);
}
ZEPHIR_CALL_METHOD(NULL, this_ptr, "_initialize", NULL, 10, model, key, source, schema);
zephir_check_call_status();
_3 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
zephir_array_fetch(&_4, _3, key, PH_NOISY | PH_READONLY, "phalcon/mvc/model/metadata.zep", 276 TSRMLS_CC);
zephir_array_fetch_long(&_5, _4, index, PH_NOISY | PH_READONLY, "phalcon/mvc/model/metadata.zep", 276 TSRMLS_CC);
RETURN_CTOR(_5);
}
/**
* Writes meta-data for certain model using a MODEL_* constant
*
*<code>
* print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, writeMetaDataIndex) {
zend_bool _0, _1;
int index, ZEPHIR_LAST_CALL_STATUS;
zval *model, *index_param = NULL, *data, *metaData, *source = NULL, *schema = NULL, *key, *_2, *_3;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 3, 0, &model, &index_param, &data);
index = zephir_get_intval(index_param);
_0 = Z_TYPE_P(data) != IS_ARRAY;
if (_0) {
_0 = Z_TYPE_P(data) != IS_STRING;
}
_1 = _0;
if (_1) {
_1 = Z_TYPE_P(data) != IS_BOOL;
}
if (_1) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "Invalid data for index", "phalcon/mvc/model/metadata.zep", 291);
return;
}
ZEPHIR_CALL_METHOD(&source, model, "getsource", NULL, 0);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&schema, model, "getschema", NULL, 0);
zephir_check_call_status();
ZEPHIR_INIT_VAR(_2);
zephir_get_class(_2, model, 1 TSRMLS_CC);
ZEPHIR_INIT_VAR(key);
ZEPHIR_CONCAT_VSVV(key, _2, "-", schema, source);
_3 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
if (!(zephir_array_isset(_3, key))) {
ZEPHIR_CALL_METHOD(NULL, this_ptr, "_initialize", NULL, 10, model, key, source, schema);
zephir_check_call_status();
}
ZEPHIR_OBS_VAR(metaData);
zephir_read_property_this(&metaData, this_ptr, SL("_metaData"), PH_NOISY_CC);
zephir_array_update_multi(&metaData, &data TSRMLS_CC, SL("zl"), 2, key, index);
zephir_update_property_this(this_ptr, SL("_metaData"), metaData TSRMLS_CC);
ZEPHIR_MM_RESTORE();
}
/**
* Reads the ordered/reversed column map for certain model
*
*<code>
* print_r($metaData->readColumnMap(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, readColumnMap) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *keyName, *data = NULL, *_0, *_1, *_2, *_3, *_4;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
if (!(ZEPHIR_GLOBAL(orm).column_renaming)) {
RETURN_MM_NULL();
}
ZEPHIR_INIT_VAR(keyName);
zephir_get_class(keyName, model, 1 TSRMLS_CC);
ZEPHIR_OBS_VAR(data);
_0 = zephir_fetch_nproperty_this(this_ptr, SL("_columnMap"), PH_NOISY_CC);
if (!(zephir_array_isset_fetch(&data, _0, keyName, 0 TSRMLS_CC))) {
ZEPHIR_INIT_VAR(_1);
ZVAL_NULL(_1);
ZEPHIR_INIT_VAR(_2);
ZVAL_NULL(_2);
ZEPHIR_INIT_VAR(_3);
ZVAL_NULL(_3);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "_initialize", NULL, 10, model, _1, _2, _3);
zephir_check_call_status();
_4 = zephir_fetch_nproperty_this(this_ptr, SL("_columnMap"), PH_NOISY_CC);
ZEPHIR_OBS_NVAR(data);
zephir_array_fetch(&data, _4, keyName, PH_NOISY, "phalcon/mvc/model/metadata.zep", 329 TSRMLS_CC);
}
RETURN_CCTOR(data);
}
/**
* Reads column-map information for certain model using a MODEL_* constant
*
*<code>
* print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, readColumnMapIndex) {
int index, ZEPHIR_LAST_CALL_STATUS;
zval *model, *index_param = NULL, *keyName, *columnMapModel = NULL, *map, *_0, *_1, *_2, *_3, *_4;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &index_param);
index = zephir_get_intval(index_param);
if (!(ZEPHIR_GLOBAL(orm).column_renaming)) {
RETURN_MM_NULL();
}
ZEPHIR_INIT_VAR(keyName);
zephir_get_class(keyName, model, 1 TSRMLS_CC);
ZEPHIR_OBS_VAR(columnMapModel);
_0 = zephir_fetch_nproperty_this(this_ptr, SL("_columnMap"), PH_NOISY_CC);
if (!(zephir_array_isset_fetch(&columnMapModel, _0, keyName, 0 TSRMLS_CC))) {
ZEPHIR_INIT_VAR(_1);
ZVAL_NULL(_1);
ZEPHIR_INIT_VAR(_2);
ZVAL_NULL(_2);
ZEPHIR_INIT_VAR(_3);
ZVAL_NULL(_3);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "_initialize", NULL, 10, model, _1, _2, _3);
zephir_check_call_status();
_4 = zephir_fetch_nproperty_this(this_ptr, SL("_columnMap"), PH_NOISY_CC);
ZEPHIR_OBS_NVAR(columnMapModel);
zephir_array_fetch(&columnMapModel, _4, keyName, PH_NOISY, "phalcon/mvc/model/metadata.zep", 354 TSRMLS_CC);
}
zephir_array_isset_long_fetch(&map, columnMapModel, index, 1 TSRMLS_CC);
RETURN_CTOR(map);
}
/**
* Returns table attributes names (fields)
*
*<code>
* print_r($metaData->getAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 0);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 374);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns an array of fields which are part of the primary key
*
*<code>
* print_r($metaData->getPrimaryKeyAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getPrimaryKeyAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 1);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 391);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns an array of fields which are not part of the primary key
*
*<code>
* print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getNonPrimaryKeyAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 2);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 408);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns an array of not null attributes
*
*<code>
* print_r($metaData->getNotNullAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getNotNullAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 3);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 425);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns attributes and their data types
*
*<code>
* print_r($metaData->getDataTypes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getDataTypes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 4);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 442);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns attributes which types are numerical
*
*<code>
* print_r($metaData->getDataTypesNumeric(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getDataTypesNumeric) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 5);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 459);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns the name of identity field (if one is present)
*
*<code>
* print_r($metaData->getIdentityField(new Robots()));
*</code>
*
* @param Phalcon\Mvc\ModelInterface model
* @return string
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getIdentityField) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 8);
ZEPHIR_RETURN_CALL_METHOD(this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
RETURN_MM();
}
/**
* Returns attributes and their bind data types
*
*<code>
* print_r($metaData->getBindTypes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getBindTypes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 9);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 491);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns attributes that must be ignored from the INSERT SQL generation
*
*<code>
* print_r($metaData->getAutomaticCreateAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getAutomaticCreateAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 10);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 508);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns attributes that must be ignored from the UPDATE SQL generation
*
*<code>
* print_r($metaData->getAutomaticUpdateAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getAutomaticUpdateAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 11);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 525);
return;
}
RETURN_CCTOR(data);
}
/**
* Set the attributes that must be ignored from the INSERT SQL generation
*
*<code>
* $metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, setAutomaticCreateAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *attributes = NULL;
zval *model, *attributes_param = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &attributes_param);
zephir_get_arrval(attributes, attributes_param);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 10);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "writemetadataindex", NULL, 12, model, &_0, attributes);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
/**
* Set the attributes that must be ignored from the UPDATE SQL generation
*
*<code>
* $metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, setAutomaticUpdateAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *attributes = NULL;
zval *model, *attributes_param = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &attributes_param);
zephir_get_arrval(attributes, attributes_param);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 11);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "writemetadataindex", NULL, 12, model, &_0, attributes);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
/**
* Set the attributes that allow empty string values
*
*<code>
* $metaData->setEmptyStringAttributes(new Robots(), array('name' => true));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, setEmptyStringAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *attributes = NULL;
zval *model, *attributes_param = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &attributes_param);
zephir_get_arrval(attributes, attributes_param);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 13);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "writemetadataindex", NULL, 12, model, &_0, attributes);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
/**
* Returns attributes allow empty strings
*
*<code>
* print_r($metaData->getEmptyStringAttributes(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getEmptyStringAttributes) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 13);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 578);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns attributes (which have default values) and their default values
*
*<code>
* print_r($metaData->getDefaultValues(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getDefaultValues) {
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 12);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readmetadataindex", NULL, 11, model, &_0);
zephir_check_call_status();
if (Z_TYPE_P(data) != IS_ARRAY) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 595);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns the column map if any
*
*<code>
* print_r($metaData->getColumnMap(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getColumnMap) {
zend_bool _1;
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 0);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readcolumnmapindex", NULL, 13, model, &_0);
zephir_check_call_status();
_1 = Z_TYPE_P(data) != IS_NULL;
if (_1) {
_1 = Z_TYPE_P(data) != IS_ARRAY;
}
if (_1) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 613);
return;
}
RETURN_CCTOR(data);
}
/**
* Returns the reverse column map if any
*
*<code>
* print_r($metaData->getReverseColumnMap(new Robots()));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, getReverseColumnMap) {
zend_bool _1;
int ZEPHIR_LAST_CALL_STATUS;
zval *model, *data = NULL, _0;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &model);
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 1);
ZEPHIR_CALL_METHOD(&data, this_ptr, "readcolumnmapindex", NULL, 13, model, &_0);
zephir_check_call_status();
_1 = Z_TYPE_P(data) != IS_NULL;
if (_1) {
_1 = Z_TYPE_P(data) != IS_ARRAY;
}
if (_1) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "The meta-data is invalid or is corrupt", "phalcon/mvc/model/metadata.zep", 631);
return;
}
RETURN_CCTOR(data);
}
/**
* Check if a model has certain attribute
*
*<code>
* var_dump($metaData->hasAttribute(new Robots(), 'name'));
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, hasAttribute) {
int ZEPHIR_LAST_CALL_STATUS;
zval *attribute = NULL;
zval *model, *attribute_param = NULL, *columnMap = NULL, *_0 = NULL, *_1;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &model, &attribute_param);
zephir_get_strval(attribute, attribute_param);
ZEPHIR_CALL_METHOD(&columnMap, this_ptr, "getreversecolumnmap", NULL, 0, model);
zephir_check_call_status();
if (Z_TYPE_P(columnMap) == IS_ARRAY) {
RETURN_MM_BOOL(zephir_array_isset(columnMap, attribute));
} else {
ZEPHIR_CALL_METHOD(&_0, this_ptr, "readmetadata", NULL, 14, model);
zephir_check_call_status();
zephir_array_fetch_long(&_1, _0, 4, PH_READONLY, "phalcon/mvc/model/metadata.zep", 651 TSRMLS_CC);
RETURN_MM_BOOL(zephir_array_isset(_1, attribute));
}
}
/**
* Checks if the internal meta-data container is empty
*
*<code>
* var_dump($metaData->isEmpty());
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, isEmpty) {
zval *_0;
_0 = zephir_fetch_nproperty_this(this_ptr, SL("_metaData"), PH_NOISY_CC);
RETURN_BOOL(zephir_fast_count_int(_0 TSRMLS_CC) == 0);
}
/**
* Resets internal meta-data in order to regenerate it
*
*<code>
* $metaData->reset();
*</code>
*/
PHP_METHOD(Phalcon_Mvc_Model_MetaData, reset) {
zval *_0, *_1;
ZEPHIR_MM_GROW();
ZEPHIR_INIT_VAR(_0);
array_init(_0);
zephir_update_property_this(this_ptr, SL("_metaData"), _0 TSRMLS_CC);
ZEPHIR_INIT_VAR(_1);
array_init(_1);
zephir_update_property_this(this_ptr, SL("_columnMap"), _1 TSRMLS_CC);
ZEPHIR_MM_RESTORE();
}
|
734104.c | /***************************************************************************/
/* */
/* t1objs.c */
/* */
/* Type 1 objects manager (body). */
/* */
/* Copyright 1996-2017 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_CALC_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_TRUETYPE_IDS_H
#include "t1gload.h"
#include "t1load.h"
#include "t1errors.h"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "t1afm.h"
#endif
#include FT_SERVICE_POSTSCRIPT_CMAPS_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1objs
/*************************************************************************/
/* */
/* SIZE FUNCTIONS */
/* */
/*************************************************************************/
static PSH_Globals_Funcs
T1_Size_Get_Globals_Funcs( T1_Size size )
{
T1_Face face = (T1_Face)size->root.face;
PSHinter_Service pshinter = (PSHinter_Service)face->pshinter;
FT_Module module;
module = FT_Get_Module( size->root.face->driver->root.library,
"pshinter" );
return ( module && pshinter && pshinter->get_globals_funcs )
? pshinter->get_globals_funcs( module )
: 0;
}
FT_LOCAL_DEF( void )
T1_Size_Done( FT_Size t1size ) /* T1_Size */
{
T1_Size size = (T1_Size)t1size;
if ( t1size->internal->module_data )
{
PSH_Globals_Funcs funcs;
funcs = T1_Size_Get_Globals_Funcs( size );
if ( funcs )
funcs->destroy( (PSH_Globals)t1size->internal->module_data );
t1size->internal->module_data = NULL;
}
}
FT_LOCAL_DEF( FT_Error )
T1_Size_Init( FT_Size t1size ) /* T1_Size */
{
T1_Size size = (T1_Size)t1size;
FT_Error error = FT_Err_Ok;
PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size );
if ( funcs )
{
PSH_Globals globals;
T1_Face face = (T1_Face)size->root.face;
error = funcs->create( size->root.face->memory,
&face->type1.private_dict, &globals );
if ( !error )
t1size->internal->module_data = globals;
}
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_Size_Request( FT_Size t1size, /* T1_Size */
FT_Size_Request req )
{
T1_Size size = (T1_Size)t1size;
PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size );
FT_Request_Metrics( size->root.face, req );
if ( funcs )
funcs->set_scale( (PSH_Globals)t1size->internal->module_data,
size->root.metrics.x_scale,
size->root.metrics.y_scale,
0, 0 );
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* SLOT FUNCTIONS */
/* */
/*************************************************************************/
FT_LOCAL_DEF( void )
T1_GlyphSlot_Done( FT_GlyphSlot slot )
{
slot->internal->glyph_hints = NULL;
}
FT_LOCAL_DEF( FT_Error )
T1_GlyphSlot_Init( FT_GlyphSlot slot )
{
T1_Face face;
PSHinter_Service pshinter;
face = (T1_Face)slot->face;
pshinter = (PSHinter_Service)face->pshinter;
if ( pshinter )
{
FT_Module module;
module = FT_Get_Module( slot->face->driver->root.library,
"pshinter" );
if ( module )
{
T1_Hints_Funcs funcs;
funcs = pshinter->get_t1_funcs( module );
slot->internal->glyph_hints = (void*)funcs;
}
}
return 0;
}
/*************************************************************************/
/* */
/* FACE FUNCTIONS */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* T1_Face_Done */
/* */
/* <Description> */
/* The face object destructor. */
/* */
/* <Input> */
/* face :: A typeless pointer to the face object to destroy. */
/* */
FT_LOCAL_DEF( void )
T1_Face_Done( FT_Face t1face ) /* T1_Face */
{
T1_Face face = (T1_Face)t1face;
FT_Memory memory;
T1_Font type1;
if ( !face )
return;
memory = face->root.memory;
type1 = &face->type1;
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
/* release multiple masters information */
FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) );
if ( face->buildchar )
{
FT_FREE( face->buildchar );
face->buildchar = NULL;
face->len_buildchar = 0;
}
T1_Done_Blend( face );
face->blend = NULL;
#endif
/* release font info strings */
{
PS_FontInfo info = &type1->font_info;
FT_FREE( info->version );
FT_FREE( info->notice );
FT_FREE( info->full_name );
FT_FREE( info->family_name );
FT_FREE( info->weight );
}
/* release top dictionary */
FT_FREE( type1->charstrings_len );
FT_FREE( type1->charstrings );
FT_FREE( type1->glyph_names );
FT_FREE( type1->subrs );
FT_FREE( type1->subrs_len );
ft_hash_num_free( type1->subrs_hash, memory );
FT_FREE( type1->subrs_hash );
FT_FREE( type1->subrs_block );
FT_FREE( type1->charstrings_block );
FT_FREE( type1->glyph_names_block );
FT_FREE( type1->encoding.char_index );
FT_FREE( type1->encoding.char_name );
FT_FREE( type1->font_name );
#ifndef T1_CONFIG_OPTION_NO_AFM
/* release afm data if present */
if ( face->afm_data )
T1_Done_Metrics( memory, (AFM_FontInfo)face->afm_data );
#endif
/* release unicode map, if any */
#if 0
FT_FREE( face->unicode_map_rec.maps );
face->unicode_map_rec.num_maps = 0;
face->unicode_map = NULL;
#endif
face->root.family_name = NULL;
face->root.style_name = NULL;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Face_Init */
/* */
/* <Description> */
/* The face object constructor. */
/* */
/* <Input> */
/* stream :: input stream where to load font data. */
/* */
/* face_index :: The index of the font face in the resource. */
/* */
/* num_params :: Number of additional generic parameters. Ignored. */
/* */
/* params :: Additional generic parameters. Ignored. */
/* */
/* <InOut> */
/* face :: The face record to build. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Face_Init( FT_Stream stream,
FT_Face t1face, /* T1_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
T1_Face face = (T1_Face)t1face;
FT_Error error;
FT_Service_PsCMaps psnames;
PSAux_Service psaux;
T1_Font type1 = &face->type1;
PS_FontInfo info = &type1->font_info;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_UNUSED( stream );
face->root.num_faces = 1;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
face->psnames = psnames;
face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"psaux" );
psaux = (PSAux_Service)face->psaux;
if ( !psaux )
{
FT_ERROR(( "T1_Face_Init: cannot access `psaux' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
face->pshinter = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"pshinter" );
FT_TRACE2(( "Type 1 driver\n" ));
/* open the tokenizer; this will also check the font format */
error = T1_Open_Face( face );
if ( error )
goto Exit;
/* if we just wanted to check the format, leave successfully now */
if ( face_index < 0 )
goto Exit;
/* check the face index */
if ( ( face_index & 0xFFFF ) > 0 )
{
FT_ERROR(( "T1_Face_Init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* now load the font program into the face object */
/* initialize the face object fields */
/* set up root face fields */
{
FT_Face root = (FT_Face)&face->root;
root->num_glyphs = type1->num_glyphs;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_SCALABLE |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_GLYPH_NAMES |
FT_FACE_FLAG_HINTER;
if ( info->is_fixed_pitch )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
if ( face->blend )
root->face_flags |= FT_FACE_FLAG_MULTIPLE_MASTERS;
/* The following code to extract the family and the style is very */
/* simplistic and might get some things wrong. For a full-featured */
/* algorithm you might have a look at the whitepaper given at */
/* */
/* http://blogs.msdn.com/text/archive/2007/04/23/wpf-font-selection-model.aspx */
/* get style name -- be careful, some broken fonts only */
/* have a `/FontName' dictionary entry! */
root->family_name = info->family_name;
root->style_name = NULL;
if ( root->family_name )
{
char* full = info->full_name;
char* family = root->family_name;
if ( full )
{
FT_Bool the_same = TRUE;
while ( *full )
{
if ( *full == *family )
{
family++;
full++;
}
else
{
if ( *full == ' ' || *full == '-' )
full++;
else if ( *family == ' ' || *family == '-' )
family++;
else
{
the_same = FALSE;
if ( !*family )
root->style_name = full;
break;
}
}
}
if ( the_same )
root->style_name = (char *)"Regular";
}
}
else
{
/* do we have a `/FontName'? */
if ( type1->font_name )
root->family_name = type1->font_name;
}
if ( !root->style_name )
{
if ( info->weight )
root->style_name = info->weight;
else
/* assume `Regular' style because we don't know better */
root->style_name = (char *)"Regular";
}
/* compute style flags */
root->style_flags = 0;
if ( info->italic_angle )
root->style_flags |= FT_STYLE_FLAG_ITALIC;
if ( info->weight )
{
if ( !ft_strcmp( info->weight, "Bold" ) ||
!ft_strcmp( info->weight, "Black" ) )
root->style_flags |= FT_STYLE_FLAG_BOLD;
}
/* no embedded bitmap support */
root->num_fixed_sizes = 0;
root->available_sizes = NULL;
root->bbox.xMin = type1->font_bbox.xMin >> 16;
root->bbox.yMin = type1->font_bbox.yMin >> 16;
/* no `U' suffix here to 0xFFFF! */
root->bbox.xMax = ( type1->font_bbox.xMax + 0xFFFF ) >> 16;
root->bbox.yMax = ( type1->font_bbox.yMax + 0xFFFF ) >> 16;
/* Set units_per_EM if we didn't set it in t1_parse_font_matrix. */
if ( !root->units_per_EM )
root->units_per_EM = 1000;
root->ascender = (FT_Short)( root->bbox.yMax );
root->descender = (FT_Short)( root->bbox.yMin );
root->height = (FT_Short)( ( root->units_per_EM * 12 ) / 10 );
if ( root->height < root->ascender - root->descender )
root->height = (FT_Short)( root->ascender - root->descender );
/* now compute the maximum advance width */
root->max_advance_width =
(FT_Short)( root->bbox.xMax );
{
FT_Pos max_advance;
error = T1_Compute_Max_Advance( face, &max_advance );
/* in case of error, keep the standard width */
if ( !error )
root->max_advance_width = (FT_Short)FIXED_TO_INT( max_advance );
else
error = FT_Err_Ok; /* clear error */
}
root->max_advance_height = root->height;
root->underline_position = (FT_Short)info->underline_position;
root->underline_thickness = (FT_Short)info->underline_thickness;
}
{
FT_Face root = &face->root;
if ( psnames )
{
FT_CharMapRec charmap;
T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes;
FT_CMap_Class clazz;
charmap.face = root;
/* first of all, try to synthesize a Unicode charmap */
charmap.platform_id = TT_PLATFORM_MICROSOFT;
charmap.encoding_id = TT_MS_ID_UNICODE_CS;
charmap.encoding = FT_ENCODING_UNICODE;
error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL );
if ( error &&
FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) )
goto Exit;
error = FT_Err_Ok;
/* now, generate an Adobe Standard encoding when appropriate */
charmap.platform_id = TT_PLATFORM_ADOBE;
clazz = NULL;
switch ( type1->encoding_type )
{
case T1_ENCODING_TYPE_STANDARD:
charmap.encoding = FT_ENCODING_ADOBE_STANDARD;
charmap.encoding_id = TT_ADOBE_ID_STANDARD;
clazz = cmap_classes->standard;
break;
case T1_ENCODING_TYPE_EXPERT:
charmap.encoding = FT_ENCODING_ADOBE_EXPERT;
charmap.encoding_id = TT_ADOBE_ID_EXPERT;
clazz = cmap_classes->expert;
break;
case T1_ENCODING_TYPE_ARRAY:
charmap.encoding = FT_ENCODING_ADOBE_CUSTOM;
charmap.encoding_id = TT_ADOBE_ID_CUSTOM;
clazz = cmap_classes->custom;
break;
case T1_ENCODING_TYPE_ISOLATIN1:
charmap.encoding = FT_ENCODING_ADOBE_LATIN_1;
charmap.encoding_id = TT_ADOBE_ID_LATIN_1;
clazz = cmap_classes->unicode;
break;
default:
;
}
if ( clazz )
error = FT_CMap_New( clazz, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if (root->num_charmaps)
root->charmap = root->charmaps[0];
#endif
}
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Driver_Init */
/* */
/* <Description> */
/* Initializes a given Type 1 driver object. */
/* */
/* <Input> */
/* driver :: A handle to the target driver object. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Driver_Init( FT_Module driver )
{
FT_UNUSED( driver );
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Driver_Done */
/* */
/* <Description> */
/* Finalizes a given Type 1 driver. */
/* */
/* <Input> */
/* driver :: A handle to the target Type 1 driver. */
/* */
FT_LOCAL_DEF( void )
T1_Driver_Done( FT_Module driver )
{
FT_UNUSED( driver );
}
/* END */
|
713642.c | /**
******************************************************************************
* @file stm32f7xx_hal_spdifrx.c
* @author MCD Application Team
* @brief This file provides firmware functions to manage the following
* functionalities of the SPDIFRX audio interface:
* + Initialization and Configuration
* + Data transfers functions
* + DMA transfers management
* + Interrupts and flags management
@verbatim
===============================================================================
##### How to use this driver #####
===============================================================================
[..]
The SPDIFRX HAL driver can be used as follow:
(#) Declare SPDIFRX_HandleTypeDef handle structure.
(#) Initialize the SPDIFRX low level resources by implement the HAL_SPDIFRX_MspInit() API:
(##) Enable the SPDIFRX interface clock.
(##) SPDIFRX pins configuration:
(+++) Enable the clock for the SPDIFRX GPIOs.
(+++) Configure these SPDIFRX pins as alternate function pull-up.
(##) NVIC configuration if you need to use interrupt process (HAL_SPDIFRX_ReceiveControlFlow_IT() and HAL_SPDIFRX_ReceiveDataFlow_IT() API's).
(+++) Configure the SPDIFRX interrupt priority.
(+++) Enable the NVIC SPDIFRX IRQ handle.
(##) DMA Configuration if you need to use DMA process (HAL_SPDIFRX_ReceiveDataFlow_DMA() and HAL_SPDIFRX_ReceiveControlFlow_DMA() API's).
(+++) Declare a DMA handle structure for the reception of the Data Flow channel.
(+++) Declare a DMA handle structure for the reception of the Control Flow channel.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure CtrlRx/DataRx with the required parameters.
(+++) Configure the DMA Channel.
(+++) Associate the initialized DMA handle to the SPDIFRX DMA CtrlRx/DataRx handle.
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the
DMA CtrlRx/DataRx channel.
(#) Program the input selection, re-tries number, wait for activity, channel status selection, data format, stereo mode and masking of user bits
using HAL_SPDIFRX_Init() function.
-@- The specific SPDIFRX interrupts (RXNE/CSRNE and Error Interrupts) will be managed using the macros
__SPDIFRX_ENABLE_IT() and __SPDIFRX_DISABLE_IT() inside the receive process.
-@- Make sure that ck_spdif clock is configured.
(#) Three operation modes are available within this driver :
*** Polling mode for reception operation (for debug purpose) ***
================================================================
[..]
(+) Receive data flow in blocking mode using HAL_SPDIFRX_ReceiveDataFlow()
(+) Receive control flow of data in blocking mode using HAL_SPDIFRX_ReceiveControlFlow()
*** Interrupt mode for reception operation ***
=========================================
[..]
(+) Receive an amount of data (Data Flow) in non blocking mode using HAL_SPDIFRX_ReceiveDataFlow_IT()
(+) Receive an amount of data (Control Flow) in non blocking mode using HAL_SPDIFRX_ReceiveControlFlow_IT()
(+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback
(+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback
(+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback
*** DMA mode for reception operation ***
========================================
[..]
(+) Receive an amount of data (Data Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveDataFlow_DMA()
(+) Receive an amount of data (Control Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveControlFlow_DMA()
(+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback
(+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback
(+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback
(+) Stop the DMA Transfer using HAL_SPDIFRX_DMAStop()
*** SPDIFRX HAL driver macros list ***
=============================================
[..]
Below the list of most used macros in USART HAL driver.
(+) __HAL_SPDIFRX_IDLE: Disable the specified SPDIFRX peripheral (IDEL State)
(+) __HAL_SPDIFRX_SYNC: Enable the synchronization state of the specified SPDIFRX peripheral (SYNC State)
(+) __HAL_SPDIFRX_RCV: Enable the receive state of the specified SPDIFRX peripheral (RCV State)
(+) __HAL_SPDIFRX_ENABLE_IT : Enable the specified SPDIFRX interrupts
(+) __HAL_SPDIFRX_DISABLE_IT : Disable the specified SPDIFRX interrupts
(+) __HAL_SPDIFRX_GET_FLAG: Check whether the specified SPDIFRX flag is set or not.
[..]
(@) You can refer to the SPDIFRX HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal.h"
/** @addtogroup STM32F7xx_HAL_Driver
* @{
*/
/** @defgroup SPDIFRX SPDIFRX
* @brief SPDIFRX HAL module driver
* @{
*/
#ifdef HAL_SPDIFRX_MODULE_ENABLED
#if defined (SPDIFRX)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define SPDIFRX_TIMEOUT_VALUE 0xFFFF
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup SPDIFRX_Private_Functions
* @{
*/
static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma);
static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma);
static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma);
static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma);
static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif);
static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif);
static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t tickstart);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup SPDIFRX_Exported_Functions SPDIFRX Exported Functions
* @{
*/
/** @defgroup SPDIFRX_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
de-initialize the SPDIFRX peripheral:
(+) User must Implement HAL_SPDIFRX_MspInit() function in which he configures
all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
(+) Call the function HAL_SPDIFRX_Init() to configure the SPDIFRX peripheral with
the selected configuration:
(++) Input Selection (IN0, IN1,...)
(++) Maximum allowed re-tries during synchronization phase
(++) Wait for activity on SPDIF selected input
(++) Channel status selection (from channel A or B)
(++) Data format (LSB, MSB, ...)
(++) Stereo mode
(++) User bits masking (PT,C,U,V,...)
(+) Call the function HAL_SPDIFRX_DeInit() to restore the default configuration
of the selected SPDIFRXx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initializes the SPDIFRX according to the specified parameters
* in the SPDIFRX_InitTypeDef and create the associated handle.
* @param hspdif SPDIFRX handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_Init(SPDIFRX_HandleTypeDef *hspdif)
{
uint32_t tmpreg = 0;
/* Check the SPDIFRX handle allocation */
if(hspdif == NULL)
{
return HAL_ERROR;
}
/* Check the SPDIFRX parameters */
assert_param(IS_STEREO_MODE(hspdif->Init.StereoMode));
assert_param(IS_SPDIFRX_INPUT_SELECT(hspdif->Init.InputSelection));
assert_param(IS_SPDIFRX_MAX_RETRIES(hspdif->Init.Retries));
assert_param(IS_SPDIFRX_WAIT_FOR_ACTIVITY(hspdif->Init.WaitForActivity));
assert_param(IS_SPDIFRX_CHANNEL(hspdif->Init.ChannelSelection));
assert_param(IS_SPDIFRX_DATA_FORMAT(hspdif->Init.DataFormat));
assert_param(IS_PREAMBLE_TYPE_MASK(hspdif->Init.PreambleTypeMask));
assert_param(IS_CHANNEL_STATUS_MASK(hspdif->Init.ChannelStatusMask));
assert_param(IS_VALIDITY_MASK(hspdif->Init.ValidityBitMask));
assert_param(IS_PARITY_ERROR_MASK(hspdif->Init.ParityErrorMask));
if(hspdif->State == HAL_SPDIFRX_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hspdif->Lock = HAL_UNLOCKED;
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
HAL_SPDIFRX_MspInit(hspdif);
}
/* SPDIFRX peripheral state is BUSY*/
hspdif->State = HAL_SPDIFRX_STATE_BUSY;
/* Disable SPDIFRX interface (IDLE State) */
__HAL_SPDIFRX_IDLE(hspdif);
/* Reset the old SPDIFRX CR configuration */
tmpreg = hspdif->Instance->CR;
tmpreg &= ~((uint16_t) SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK |
SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK |
SPDIFRX_CR_CHSEL | SPDIFRX_CR_NBTR | SPDIFRX_CR_WFA | SPDIFRX_CR_INSEL);
/* Sets the new configuration of the SPDIFRX peripheral */
tmpreg |= ((uint16_t) hspdif->Init.StereoMode |
hspdif->Init.InputSelection |
hspdif->Init.Retries |
hspdif->Init.WaitForActivity |
hspdif->Init.ChannelSelection |
hspdif->Init.DataFormat |
hspdif->Init.PreambleTypeMask |
hspdif->Init.ChannelStatusMask |
hspdif->Init.ValidityBitMask |
hspdif->Init.ParityErrorMask);
hspdif->Instance->CR = tmpreg;
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
/* SPDIFRX peripheral state is READY*/
hspdif->State = HAL_SPDIFRX_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the SPDIFRX peripheral
* @param hspdif SPDIFRX handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_DeInit(SPDIFRX_HandleTypeDef *hspdif)
{
/* Check the SPDIFRX handle allocation */
if(hspdif == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPDIFRX_ALL_INSTANCE(hspdif->Instance));
hspdif->State = HAL_SPDIFRX_STATE_BUSY;
/* Disable SPDIFRX interface (IDLE state) */
__HAL_SPDIFRX_IDLE(hspdif);
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
HAL_SPDIFRX_MspDeInit(hspdif);
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
/* SPDIFRX peripheral state is RESET*/
hspdif->State = HAL_SPDIFRX_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
/**
* @brief SPDIFRX MSP Init
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_MspInit(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_MspInit could be implemented in the user file
*/
}
/**
* @brief SPDIFRX MSP DeInit
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_MspDeInit(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_MspDeInit could be implemented in the user file
*/
}
/**
* @brief Sets the SPDIFRX dtat format according to the specified parameters
* in the SPDIFRX_InitTypeDef.
* @param hspdif SPDIFRX handle
* @param sDataFormat SPDIFRX data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_SetDataFormat(SPDIFRX_HandleTypeDef *hspdif, SPDIFRX_SetDataFormatTypeDef sDataFormat)
{
uint32_t tmpreg = 0;
/* Check the SPDIFRX handle allocation */
if(hspdif == NULL)
{
return HAL_ERROR;
}
/* Check the SPDIFRX parameters */
assert_param(IS_STEREO_MODE(sDataFormat.StereoMode));
assert_param(IS_SPDIFRX_DATA_FORMAT(sDataFormat.DataFormat));
assert_param(IS_PREAMBLE_TYPE_MASK(sDataFormat.PreambleTypeMask));
assert_param(IS_CHANNEL_STATUS_MASK(sDataFormat.ChannelStatusMask));
assert_param(IS_VALIDITY_MASK(sDataFormat.ValidityBitMask));
assert_param(IS_PARITY_ERROR_MASK(sDataFormat.ParityErrorMask));
/* Reset the old SPDIFRX CR configuration */
tmpreg = hspdif->Instance->CR;
if(((tmpreg & SPDIFRX_STATE_RCV) == SPDIFRX_STATE_RCV) &&
(((tmpreg & SPDIFRX_CR_DRFMT) != sDataFormat.DataFormat) ||
((tmpreg & SPDIFRX_CR_RXSTEO) != sDataFormat.StereoMode)))
{
return HAL_ERROR;
}
tmpreg &= ~((uint16_t) SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK |
SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK);
/* Sets the new configuration of the SPDIFRX peripheral */
tmpreg |= ((uint16_t) sDataFormat.StereoMode |
sDataFormat.DataFormat |
sDataFormat.PreambleTypeMask |
sDataFormat.ChannelStatusMask |
sDataFormat.ValidityBitMask |
sDataFormat.ParityErrorMask);
hspdif->Instance->CR = tmpreg;
return HAL_OK;
}
/**
* @}
*/
/** @defgroup SPDIFRX_Exported_Functions_Group2 IO operation functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the SPDIFRX data
transfers.
(#) There is two mode of transfer:
(++) Blocking mode : The communication is performed in the polling mode.
The status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode : The communication is performed using Interrupts
or DMA. These functions return the status of the transfer start-up.
The end of the data processing will be indicated through the
dedicated SPDIFRX IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
(#) Blocking mode functions are :
(++) HAL_SPDIFRX_ReceiveDataFlow()
(++) HAL_SPDIFRX_ReceiveControlFlow()
(+@) Do not use blocking mode to receive both control and data flow at the same time.
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_SPDIFRX_ReceiveControlFlow_IT()
(++) HAL_SPDIFRX_ReceiveDataFlow_IT()
(#) No-Blocking mode functions with DMA are :
(++) HAL_SPDIFRX_ReceiveControlFlow_DMA()
(++) HAL_SPDIFRX_ReceiveDataFlow_DMA()
(#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
(++) HAL_SPDIFRX_RxCpltCallback()
(++) HAL_SPDIFRX_ErrorCallback()
@endverbatim
* @{
*/
/**
* @brief Receives an amount of data (Data Flow) in blocking mode.
* @param hspdif pointer to SPDIFRX_HandleTypeDef structure that contains
* the configuration information for SPDIFRX module.
* @param pData Pointer to data buffer
* @param Size Amount of data to be received
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if((pData == NULL ) || (Size == 0U))
{
return HAL_ERROR;
}
if(hspdif->State == HAL_SPDIFRX_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->State = HAL_SPDIFRX_STATE_BUSY;
/* Start synchronisation */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
/* Receive data flow */
while(Size > 0U)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until RXNE flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*pData++) = hspdif->Instance->DR;
Size--;
}
/* SPDIFRX ready */
hspdif->State = HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data (Control Flow) in blocking mode.
* @param hspdif pointer to a SPDIFRX_HandleTypeDef structure that contains
* the configuration information for SPDIFRX module.
* @param pData Pointer to data buffer
* @param Size Amount of data to be received
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if((pData == NULL ) || (Size == 0U))
{
return HAL_ERROR;
}
if(hspdif->State == HAL_SPDIFRX_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->State = HAL_SPDIFRX_STATE_BUSY;
/* Start synchronization */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
/* Receive control flow */
while(Size > 0U)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until CSRNE flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_CSRNE, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*pData++) = hspdif->Instance->CSR;
Size--;
}
/* SPDIFRX ready */
hspdif->State = HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data (Data Flow) in non-blocking mode with Interrupt
* @param hspdif SPDIFRX handle
* @param pData a 32-bit pointer to the Receive data buffer.
* @param Size number of data sample to be received .
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
if((hspdif->State == HAL_SPDIFRX_STATE_READY) || (hspdif->State == HAL_SPDIFRX_STATE_BUSY_CX))
{
if((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->pRxBuffPtr = pData;
hspdif->RxXferSize = Size;
hspdif->RxXferCount = Size;
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
/* Check if a receive process is ongoing or not */
hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX;
/* Enable the SPDIFRX PE Error Interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE);
/* Enable the SPDIFRX OVR Error Interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE);
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
/* Enable the SPDIFRX RXNE interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_RXNE);
if (((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != SPDIFRX_STATE_SYNC) || ((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != 0x00U))
{
/* Start synchronization */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, SPDIFRX_TIMEOUT_VALUE, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data (Control Flow) with Interrupt
* @param hspdif SPDIFRX handle
* @param pData a 32-bit pointer to the Receive data buffer.
* @param Size number of data sample (Control Flow) to be received :
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
if((hspdif->State == HAL_SPDIFRX_STATE_READY) || (hspdif->State == HAL_SPDIFRX_STATE_BUSY_RX))
{
if((pData == NULL ) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->pCsBuffPtr = pData;
hspdif->CsXferSize = Size;
hspdif->CsXferCount = Size;
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
/* Check if a receive process is ongoing or not */
hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX;
/* Enable the SPDIFRX PE Error Interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE);
/* Enable the SPDIFRX OVR Error Interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE);
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
/* Enable the SPDIFRX CSRNE interrupt */
__HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_CSRNE);
if (((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != SPDIFRX_STATE_SYNC) || ((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != 0x00U))
{
/* Start synchronization */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, SPDIFRX_TIMEOUT_VALUE, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data (Data Flow) mode with DMA
* @param hspdif SPDIFRX handle
* @param pData a 32-bit pointer to the Receive data buffer.
* @param Size number of data sample to be received :
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
if((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if((hspdif->State == HAL_SPDIFRX_STATE_READY) || (hspdif->State == HAL_SPDIFRX_STATE_BUSY_CX))
{
hspdif->pRxBuffPtr = pData;
hspdif->RxXferSize = Size;
hspdif->RxXferCount = Size;
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX;
/* Set the SPDIFRX Rx DMA Half transfer complete callback */
hspdif->hdmaDrRx->XferHalfCpltCallback = SPDIFRX_DMARxHalfCplt;
/* Set the SPDIFRX Rx DMA transfer complete callback */
hspdif->hdmaDrRx->XferCpltCallback = SPDIFRX_DMARxCplt;
/* Set the DMA error callback */
hspdif->hdmaDrRx->XferErrorCallback = SPDIFRX_DMAError;
/* Enable the DMA request */
HAL_DMA_Start_IT(hspdif->hdmaDrRx, (uint32_t)&hspdif->Instance->DR, (uint32_t)hspdif->pRxBuffPtr, Size);
/* Enable RXDMAEN bit in SPDIFRX CR register for data flow reception*/
hspdif->Instance->CR |= SPDIFRX_CR_RXDMAEN;
if (((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != SPDIFRX_STATE_SYNC) || ((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != 0x00U))
{
/* Start synchronization */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, SPDIFRX_TIMEOUT_VALUE, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
}
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data (Control Flow) with DMA
* @param hspdif SPDIFRX handle
* @param pData a 32-bit pointer to the Receive data buffer.
* @param Size number of data (Control Flow) sample to be received :
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
if((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if((hspdif->State == HAL_SPDIFRX_STATE_READY) || (hspdif->State == HAL_SPDIFRX_STATE_BUSY_RX))
{
hspdif->pCsBuffPtr = pData;
hspdif->CsXferSize = Size;
hspdif->CsXferCount = Size;
/* Process Locked */
__HAL_LOCK(hspdif);
hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE;
hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX;
/* Set the SPDIFRX Rx DMA Half transfer complete callback */
hspdif->hdmaCsRx->XferHalfCpltCallback = SPDIFRX_DMACxHalfCplt;
/* Set the SPDIFRX Rx DMA transfer complete callback */
hspdif->hdmaCsRx->XferCpltCallback = SPDIFRX_DMACxCplt;
/* Set the DMA error callback */
hspdif->hdmaCsRx->XferErrorCallback = SPDIFRX_DMAError;
/* Enable the DMA request */
HAL_DMA_Start_IT(hspdif->hdmaCsRx, (uint32_t)&hspdif->Instance->CSR, (uint32_t)hspdif->pCsBuffPtr, Size);
/* Enable CBDMAEN bit in SPDIFRX CR register for control flow reception*/
hspdif->Instance->CR |= SPDIFRX_CR_CBDMAEN;
if (((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != SPDIFRX_STATE_SYNC) || ((SPDIFRX->CR & SPDIFRX_CR_SPDIFEN) != 0x00U))
{
/* Start synchronization */
__HAL_SPDIFRX_SYNC(hspdif);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until SYNCD flag is set */
if(SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, SPDIFRX_TIMEOUT_VALUE, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Start reception */
__HAL_SPDIFRX_RCV(hspdif);
}
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief stop the audio stream receive from the Media.
* @param hspdif SPDIFRX handle
* @retval None
*/
HAL_StatusTypeDef HAL_SPDIFRX_DMAStop(SPDIFRX_HandleTypeDef *hspdif)
{
/* Process Locked */
__HAL_LOCK(hspdif);
/* Disable the SPDIFRX DMA requests */
hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN);
hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN);
/* Disable the SPDIFRX DMA channel */
__HAL_DMA_DISABLE(hspdif->hdmaDrRx);
__HAL_DMA_DISABLE(hspdif->hdmaCsRx);
/* Disable SPDIFRX peripheral */
__HAL_SPDIFRX_IDLE(hspdif);
hspdif->State = HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_OK;
}
/**
* @brief This function handles SPDIFRX interrupt request.
* @param hspdif SPDIFRX handle
* @retval HAL status
*/
void HAL_SPDIFRX_IRQHandler(SPDIFRX_HandleTypeDef *hspdif)
{
/* SPDIFRX in mode Data Flow Reception ------------------------------------------------*/
if((__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_RXNE) != RESET) && (__HAL_SPDIFRX_GET_IT_SOURCE(hspdif, SPDIFRX_IT_RXNE) != RESET))
{
__HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_RXNE);
SPDIFRX_ReceiveDataFlow_IT(hspdif);
}
/* SPDIFRX in mode Control Flow Reception ------------------------------------------------*/
if((__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_CSRNE) != RESET) && (__HAL_SPDIFRX_GET_IT_SOURCE(hspdif, SPDIFRX_IT_CSRNE) != RESET))
{
__HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_CSRNE);
SPDIFRX_ReceiveControlFlow_IT(hspdif);
}
/* SPDIFRX Overrun error interrupt occurred ---------------------------------*/
if((__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_OVR) != RESET) && (__HAL_SPDIFRX_GET_IT_SOURCE(hspdif, SPDIFRX_IT_OVRIE) != RESET))
{
__HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_FLAG_OVR);
/* Change the SPDIFRX error code */
hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_OVR;
/* the transfer is not stopped */
HAL_SPDIFRX_ErrorCallback(hspdif);
}
/* SPDIFRX Parity error interrupt occurred ---------------------------------*/
if((__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_PERR) != RESET) && (__HAL_SPDIFRX_GET_IT_SOURCE(hspdif, SPDIFRX_IT_PERRIE) != RESET))
{
__HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_FLAG_PERR);
/* Change the SPDIFRX error code */
hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_PE;
/* the transfer is not stopped */
HAL_SPDIFRX_ErrorCallback(hspdif);
}
}
/**
* @brief Rx Transfer (Data flow) half completed callbacks
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_RxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer (Data flow) completed callbacks
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_RxCpltCallback(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx (Control flow) Transfer half completed callbacks
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_CxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer (Control flow) completed callbacks
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_CxCpltCallback(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief SPDIFRX error callbacks
* @param hspdif SPDIFRX handle
* @retval None
*/
__weak void HAL_SPDIFRX_ErrorCallback(SPDIFRX_HandleTypeDef *hspdif)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hspdif);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPDIFRX_ErrorCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup SPDIFRX_Exported_Functions_Group3 Peripheral State and Errors functions
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State and Errors functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the SPDIFRX state
* @param hspdif SPDIFRX handle
* @retval HAL state
*/
HAL_SPDIFRX_StateTypeDef HAL_SPDIFRX_GetState(SPDIFRX_HandleTypeDef *hspdif)
{
return hspdif->State;
}
/**
* @brief Return the SPDIFRX error code
* @param hspdif SPDIFRX handle
* @retval SPDIFRX Error Code
*/
uint32_t HAL_SPDIFRX_GetError(SPDIFRX_HandleTypeDef *hspdif)
{
return hspdif->ErrorCode;
}
/**
* @}
*/
/**
* @brief DMA SPDIFRX receive process (Data flow) complete callback
* @param hdma DMA handle
* @retval None
*/
static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma)
{
SPDIFRX_HandleTypeDef* hspdif = ( SPDIFRX_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* Disable Rx DMA Request */
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN);
hspdif->RxXferCount = 0;
hspdif->State = HAL_SPDIFRX_STATE_READY;
}
HAL_SPDIFRX_RxCpltCallback(hspdif);
}
/**
* @brief DMA SPDIFRX receive process (Data flow) half complete callback
* @param hdma DMA handle
* @retval None
*/
static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
SPDIFRX_HandleTypeDef* hspdif = (SPDIFRX_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
HAL_SPDIFRX_RxHalfCpltCallback(hspdif);
}
/**
* @brief DMA SPDIFRX receive process (Control flow) complete callback
* @param hdma DMA handle
* @retval None
*/
static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma)
{
SPDIFRX_HandleTypeDef* hspdif = ( SPDIFRX_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* Disable Cb DMA Request */
hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN);
hspdif->CsXferCount = 0;
hspdif->State = HAL_SPDIFRX_STATE_READY;
HAL_SPDIFRX_CxCpltCallback(hspdif);
}
/**
* @brief DMA SPDIFRX receive process (Control flow) half complete callback
* @param hdma DMA handle
* @retval None
*/
static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma)
{
SPDIFRX_HandleTypeDef* hspdif = (SPDIFRX_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
HAL_SPDIFRX_CxHalfCpltCallback(hspdif);
}
/**
* @brief DMA SPDIFRX communication error callback
* @param hdma DMA handle
* @retval None
*/
static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma)
{
SPDIFRX_HandleTypeDef* hspdif = ( SPDIFRX_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* Disable Rx and Cb DMA Request */
hspdif->Instance->CR &= (uint16_t)(~(SPDIFRX_CR_RXDMAEN | SPDIFRX_CR_CBDMAEN));
hspdif->RxXferCount = 0;
hspdif->State= HAL_SPDIFRX_STATE_READY;
/* Set the error code and execute error callback*/
hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_DMA;
HAL_SPDIFRX_ErrorCallback(hspdif);
}
/**
* @brief Receive an amount of data (Data Flow) with Interrupt
* @param hspdif SPDIFRX handle
* @retval None
*/
static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif)
{
/* Receive data */
(*hspdif->pRxBuffPtr++) = hspdif->Instance->DR;
hspdif->RxXferCount--;
if(hspdif->RxXferCount == 0)
{
/* Disable RXNE/PE and OVR interrupts */
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE | SPDIFRX_IT_PERRIE | SPDIFRX_IT_RXNE);
hspdif->State = HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
HAL_SPDIFRX_RxCpltCallback(hspdif);
}
}
/**
* @brief Receive an amount of data (Control Flow) with Interrupt
* @param hspdif SPDIFRX handle
* @retval None
*/
static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif)
{
/* Receive data */
(*hspdif->pCsBuffPtr++) = hspdif->Instance->CSR;
hspdif->CsXferCount--;
if(hspdif->CsXferCount == 0)
{
/* Disable CSRNE interrupt */
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE);
hspdif->State = HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
HAL_SPDIFRX_CxCpltCallback(hspdif);
}
}
/**
* @brief This function handles SPDIFRX Communication Timeout.
* @param hspdif SPDIFRX handle
* @param Flag Flag checked
* @param Status Value of the flag expected
* @param Timeout Duration of the timeout
* @param tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t tickstart)
{
/* Wait until flag is set */
if(Status == RESET)
{
while(__HAL_SPDIFRX_GET_FLAG(hspdif, Flag) == RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE);
hspdif->State= HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_TIMEOUT;
}
}
}
}
else
{
while(__HAL_SPDIFRX_GET_FLAG(hspdif, Flag) != RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE);
__HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE);
hspdif->State= HAL_SPDIFRX_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspdif);
return HAL_TIMEOUT;
}
}
}
}
return HAL_OK;
}
/**
* @}
*/
#endif /* SPDIFRX */
#endif /* HAL_SPDIFRX_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
553410.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 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* Copyright (c) 2018, Joyent, Inc.
*/
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <libintl.h>
#include <locale.h>
#include <sys/stat.h>
#include <sys/corectl.h>
#include <libproc.h>
#include <libscf.h>
#include <libscf_priv.h>
#include <assert.h>
#define E_SUCCESS 0 /* Exit status for success */
#define E_ERROR 1 /* Exit status for error */
#define E_USAGE 2 /* Exit status for usage error */
static const char PATH_CONFIG[] = "/etc/coreadm.conf";
static const char PATH_CONFIG_OLD[] = "/etc/coreadm.conf.old";
#define COREADM_INST_NAME "system/coreadm:default"
#define COREADM_INST_FMRI \
SCF_FMRI_SVC_PREFIX SCF_FMRI_SERVICE_PREFIX COREADM_INST_NAME
#define CONFIG_PARAMS "config_params"
#define GLOBAL_ENABLED "global_enabled"
#define PROCESS_ENABLED "process_enabled"
#define GLOBAL_SETID_ENABLED "global_setid_enabled"
#define PROCESS_SETID_ENABLED "process_setid_enabled"
#define GLOBAL_LOG_ENABLED "global_log_enabled"
#define GLOBAL_PATTERN "global_pattern"
#define GLOBAL_CONTENT "global_content"
#define INIT_PATTERN "init_pattern"
#define INIT_CONTENT "init_content"
static char *command;
static uint64_t options;
static int alloptions;
static char *glob_pattern;
static char gpattern[PATH_MAX];
static core_content_t glob_content = CC_CONTENT_INVALID;
static char *init_pattern;
static char ipattern[PATH_MAX];
static core_content_t init_content = CC_CONTENT_INVALID;
static char *proc_pattern;
static size_t proc_size;
static core_content_t proc_content = CC_CONTENT_INVALID;
static int report_settings(void);
static int do_processes(int, char **);
static int do_modify(boolean_t);
static int do_update(void);
static int do_legacy(void);
static scf_propvec_t prop_gpattern = { GLOBAL_PATTERN, NULL, SCF_TYPE_ASTRING };
static scf_propvec_t prop_gcontent = { GLOBAL_CONTENT, NULL, SCF_TYPE_ASTRING };
static scf_propvec_t prop_ipattern = { INIT_PATTERN, NULL, SCF_TYPE_ASTRING };
static scf_propvec_t prop_icontent = { INIT_CONTENT, NULL, SCF_TYPE_ASTRING };
static scf_propvec_t prop_option[] = {
{ GLOBAL_ENABLED, NULL, SCF_TYPE_BOOLEAN, NULL, CC_GLOBAL_PATH },
{ PROCESS_ENABLED, NULL, SCF_TYPE_BOOLEAN, NULL, CC_PROCESS_PATH },
{ GLOBAL_SETID_ENABLED, NULL, SCF_TYPE_BOOLEAN, NULL, CC_GLOBAL_SETID },
{ PROCESS_SETID_ENABLED, NULL, SCF_TYPE_BOOLEAN, NULL, CC_PROCESS_SETID },
{ GLOBAL_LOG_ENABLED, NULL, SCF_TYPE_BOOLEAN, NULL, CC_GLOBAL_LOG },
{ NULL }
};
#define MAX_PROPS (4 + (sizeof (prop_option) / sizeof (scf_propvec_t)))
static void
usage(void)
{
(void) fprintf(stderr, gettext(
"usage:\n"));
(void) fprintf(stderr, gettext(
" %s [ -g pattern ] [ -i pattern ] [ -G content ] [ -I content ]\n"),
command);
(void) fprintf(stderr, gettext(
" [ -e {global | process | global-setid | proc-setid | log} ]\n"));
(void) fprintf(stderr, gettext(
" [ -d {global | process | global-setid | proc-setid | log} ]\n"));
(void) fprintf(stderr, gettext(
" %s [ -p pattern ] [ -P content ] [ pid ... ]\n"), command);
exit(E_USAGE);
}
static int
perm(void)
{
(void) fprintf(stderr, gettext("%s: insufficient privileges to "
"exercise the -[GIgied] options\n"), command);
return (E_USAGE);
}
static int
parse_content(char *arg, core_content_t *content)
{
if (proc_str2content(arg, content) == 0)
return (0);
(void) fprintf(stderr, gettext("%s: invalid content string '%s'\n"),
command, arg);
return (1);
}
int
main(int argc, char **argv)
{
int flag;
int opt;
int modify;
int update = 0;
int legacy_update = 0;
int error = 0;
int npids;
char **pidlist;
char curpid[11];
char *curpid_ptr = &curpid[0];
(void) setlocale(LC_ALL, "");
(void) textdomain(TEXT_DOMAIN);
/* command name (e.g., "coreadm") */
if ((command = strrchr(argv[0], '/')) != NULL)
command++;
else
command = argv[0];
while ((opt = getopt(argc, argv, "g:G:i:I:p:P:e:d:uU?")) != EOF) {
switch (opt) {
case 'g':
glob_pattern = optarg;
break;
case 'i':
init_pattern = optarg;
break;
case 'p':
proc_pattern = optarg;
proc_size = strlen(proc_pattern) + 1;
break;
case 'G':
error |= parse_content(optarg, &glob_content);
break;
case 'I':
error |= parse_content(optarg, &init_content);
break;
case 'P':
error |= parse_content(optarg, &proc_content);
break;
case 'e':
case 'd':
if (strcmp(optarg, "global") == 0)
flag = CC_GLOBAL_PATH;
else if (strcmp(optarg, "process") == 0)
flag = CC_PROCESS_PATH;
else if (strcmp(optarg, "global-setid") == 0)
flag = CC_GLOBAL_SETID;
else if (strcmp(optarg, "proc-setid") == 0)
flag = CC_PROCESS_SETID;
else if (strcmp(optarg, "log") == 0)
flag = CC_GLOBAL_LOG;
else {
flag = 0;
error = 1;
}
if (opt == 'e')
options |= flag;
else
options &= ~flag;
alloptions |= flag;
break;
case 'U':
update = 1;
break;
case 'u':
legacy_update = 1;
break;
case '?':
default:
error = 1;
break;
}
}
npids = argc - optind;
pidlist = argv + optind;
if (error)
usage();
/*
* If 'modify' is true, we must modify the system settings
* and update the configuration file with the new parameters.
*/
modify = glob_pattern != NULL || glob_content != CC_CONTENT_INVALID ||
init_pattern != NULL || init_content != CC_CONTENT_INVALID ||
alloptions != 0;
if ((update || legacy_update) && (modify || proc_pattern != NULL ||
proc_content != CC_CONTENT_INVALID || npids != 0)) {
(void) fprintf(stderr,
gettext("%s: the -u option must stand alone\n"), command);
usage();
}
if (modify &&
(proc_pattern != NULL || proc_content != CC_CONTENT_INVALID)) {
(void) fprintf(stderr, gettext(
"%s: -[GIgied] and -[Pp] options are mutually exclusive\n"),
command);
usage();
}
if (modify && npids != 0) {
(void) fprintf(stderr, gettext(
"%s: -[GIgied] options cannot have a process-id list\n"),
command);
usage();
}
if ((proc_pattern != NULL || proc_content != CC_CONTENT_INVALID) &&
npids == 0) {
(void) sprintf(curpid, "%u", (uint_t)getppid());
npids = 1;
pidlist = &curpid_ptr;
}
if (legacy_update)
return (do_legacy());
if (update)
return (do_update());
if (modify)
return (do_modify(B_FALSE));
if (npids != 0)
return (do_processes(npids, pidlist));
return (report_settings());
}
static int
report_settings(void)
{
char content_str[PRCONTENTBUFSZ];
if ((options = core_get_options()) == -1) {
perror("core_get_options()");
return (E_ERROR);
}
if (core_get_global_path(gpattern, sizeof (gpattern)) != 0) {
perror("core_get_global_path()");
return (E_ERROR);
}
if (core_get_default_path(ipattern, sizeof (ipattern)) != 0) {
perror("core_get_default_path()");
return (E_ERROR);
}
if (core_get_global_content(&glob_content) != 0) {
perror("core_get_global_content()");
return (E_ERROR);
}
if (core_get_default_content(&init_content) != 0) {
perror("core_get_default_content()");
return (E_ERROR);
}
(void) printf(gettext(" global core file pattern: %s\n"),
gpattern);
(void) proc_content2str(glob_content, content_str,
sizeof (content_str));
(void) printf(gettext(" global core file content: %s\n"),
content_str);
(void) printf(gettext(" init core file pattern: %s\n"),
ipattern);
(void) proc_content2str(init_content, content_str,
sizeof (content_str));
(void) printf(gettext(" init core file content: %s\n"),
content_str);
(void) printf(gettext(" global core dumps: %s\n"),
(options & CC_GLOBAL_PATH)? "enabled" : "disabled");
(void) printf(gettext(" per-process core dumps: %s\n"),
(options & CC_PROCESS_PATH)? "enabled" : "disabled");
(void) printf(gettext(" global setid core dumps: %s\n"),
(options & CC_GLOBAL_SETID)? "enabled" : "disabled");
(void) printf(gettext(" per-process setid core dumps: %s\n"),
(options & CC_PROCESS_SETID)? "enabled" : "disabled");
(void) printf(gettext(" global core dump logging: %s\n"),
(options & CC_GLOBAL_LOG)? "enabled" : "disabled");
return (E_SUCCESS);
}
static int
do_processes(int npids, char **pidlist)
{
char process_path[PATH_MAX];
core_content_t content;
pid_t pid;
char *next;
int rc = E_SUCCESS;
char content_str[PRCONTENTBUFSZ];
if (proc_pattern == NULL && proc_content == CC_CONTENT_INVALID) {
while (npids-- > 0) {
pid = strtol(*pidlist, &next, 10);
if (*next != '\0' || !isdigit(**pidlist)) {
(void) fprintf(stderr,
gettext("%s: invalid process-id\n"),
*pidlist);
rc = E_USAGE;
} else if (core_get_process_path(process_path,
sizeof (process_path), pid) != 0 ||
core_get_process_content(&content, pid) != 0) {
perror(*pidlist);
rc = E_USAGE;
} else {
(void) proc_content2str(content, content_str,
sizeof (content_str));
(void) printf(gettext("%s:\t%s\t%s\n"),
*pidlist, process_path, content_str);
}
pidlist++;
}
} else {
while (npids-- > 0) {
pid = strtol(*pidlist, &next, 10);
if (*next != '\0') {
(void) fprintf(stderr,
gettext("%s: invalid process-id\n"),
*pidlist);
rc = E_USAGE;
} else {
if (proc_pattern != NULL &&
core_set_process_path(proc_pattern,
proc_size, pid) != 0) {
perror(*pidlist);
rc = E_USAGE;
}
if (proc_content != CC_CONTENT_INVALID &&
core_set_process_content(
&proc_content, pid) != 0) {
perror(*pidlist);
rc = E_USAGE;
}
}
pidlist++;
}
}
return (rc);
}
static void
addprop(scf_propvec_t *props, int size, int count, scf_propvec_t *pv, void *ptr)
{
assert(count + 1 < size);
props[count] = *pv;
props[count].pv_ptr = ptr;
}
static boolean_t
is_online(const char *fmri)
{
char *state = smf_get_state(fmri);
boolean_t result = state != NULL &&
strcmp(state, SCF_STATE_STRING_ONLINE) == 0;
free(state);
return (result);
}
/*
* The user has specified the -g, -G, -i, -I, -d, or -e options to
* modify the given configuration parameter. Perform the modification
* in the smf repository and then perform a smf_refresh_instance which
* will cause a coreadm -u to occur which will transfer ALL coreadm
* configuration information from the repository to the kernel.
*/
static int
do_modify(boolean_t method)
{
char gcontentstr[PRCONTENTBUFSZ];
char icontentstr[PRCONTENTBUFSZ];
scf_propvec_t *prop;
scf_propvec_t properties[MAX_PROPS + 1];
int count = 0;
if (!method && !is_online(COREADM_INST_FMRI)) {
(void) fprintf(stderr,
gettext("%s: coreadm service not online\n"), command);
return (E_ERROR);
}
if (glob_pattern != NULL)
addprop(properties, MAX_PROPS, count++, &prop_gpattern,
glob_pattern);
if (glob_content != CC_CONTENT_INVALID) {
(void) proc_content2str(glob_content, gcontentstr,
sizeof (gcontentstr));
addprop(properties, MAX_PROPS, count++, &prop_gcontent,
gcontentstr);
}
if (init_pattern != NULL)
addprop(properties, MAX_PROPS, count++, &prop_ipattern,
init_pattern);
if (init_content != CC_CONTENT_INVALID) {
(void) proc_content2str(init_content, icontentstr,
sizeof (icontentstr));
addprop(properties, MAX_PROPS, count++, &prop_icontent,
icontentstr);
}
for (prop = prop_option; prop->pv_prop != NULL; prop++)
if ((alloptions & prop->pv_aux) != 0)
addprop(properties, MAX_PROPS, count++, prop, &options);
properties[count].pv_prop = NULL;
prop = NULL;
if (scf_write_propvec(COREADM_INST_FMRI, CONFIG_PARAMS, properties,
&prop) == SCF_FAILED) {
if (prop != NULL) {
(void) fprintf(stderr, gettext(
"%s: Unable to write property '%s': %s"), command,
prop->pv_prop, scf_strerror(scf_error()));
} else {
(void) fprintf(stderr, gettext(
"%s: Unable to write configuration: %s\n"),
command, scf_strerror(scf_error()));
}
return (E_ERROR);
}
if (smf_refresh_instance(COREADM_INST_FMRI) != 0) {
(void) fprintf(stderr,
gettext("%s: Unable to refresh %s: %s\n"
"Configuration stored but not made active.\n"),
command, COREADM_INST_FMRI, scf_strerror(scf_error()));
return (E_ERROR);
}
return (E_SUCCESS);
}
static const char *
write_kernel(void)
{
if (core_set_global_path(glob_pattern, strlen(glob_pattern) + 1) != 0)
return ("core_set_global_path()");
if (core_set_global_content(&glob_content) != 0)
return ("core_set_global_content()");
if (core_set_default_path(init_pattern, strlen(init_pattern) + 1) != 0)
return ("core_set_default_path()");
if (core_set_default_content(&init_content) != 0)
return ("core_set_init_content()");
if (core_set_options((int)options) != 0)
return ("core_set_options()");
return (NULL);
}
/*
* BUFSIZE must be large enough to contain the longest path plus some more.
*/
#define BUFSIZE (PATH_MAX + 80)
static int
yes(char *name, char *value, int line)
{
if (strcmp(value, "yes") == 0)
return (1);
if (strcmp(value, "no") == 0)
return (0);
(void) fprintf(stderr, gettext(
"\"%s\", line %d: warning: value must be yes or no: %s=%s\n"),
PATH_CONFIG, line, name, value);
return (0);
}
static int
read_legacy(void)
{
FILE *fp;
int line;
char buf[BUFSIZE];
char name[BUFSIZE], value[BUFSIZE];
int n, len;
/* defaults */
alloptions = CC_OPTIONS;
options = CC_PROCESS_PATH;
gpattern[0] = '\0';
(void) strcpy(ipattern, "core");
glob_content = init_content = CC_CONTENT_DEFAULT;
glob_pattern = gpattern;
init_pattern = ipattern;
if ((fp = fopen(PATH_CONFIG, "r")) == NULL)
return (0);
for (line = 1; fgets(buf, sizeof (buf), fp) != NULL; line++) {
/*
* Skip comment lines and empty lines.
*/
if (buf[0] == '#' || buf[0] == '\n')
continue;
/*
* Look for "name=value", with optional whitespace on either
* side, terminated by a newline, and consuming the whole line.
*/
/* LINTED - unbounded string specifier */
n = sscanf(buf, " %[^=]=%s \n%n", name, value, &len);
if (n >= 1 && name[0] != '\0' &&
(n == 1 || len == strlen(buf))) {
if (n == 1)
value[0] = '\0';
if (strcmp(name, "COREADM_GLOB_PATTERN") == 0) {
(void) strlcpy(gpattern, value,
sizeof (gpattern));
continue;
}
if (strcmp(name, "COREADM_GLOB_CONTENT") == 0) {
(void) proc_str2content(value, &glob_content);
continue;
}
if (strcmp(name, "COREADM_INIT_PATTERN") == 0) {
(void) strlcpy(ipattern, value,
sizeof (ipattern));
continue;
}
if (strcmp(name, "COREADM_INIT_CONTENT") == 0) {
(void) proc_str2content(value, &init_content);
continue;
}
if (strcmp(name, "COREADM_GLOB_ENABLED") == 0) {
if (yes(name, value, line))
options |= CC_GLOBAL_PATH;
continue;
}
if (strcmp(name, "COREADM_PROC_ENABLED") == 0) {
if (yes(name, value, line))
options |= CC_PROCESS_PATH;
else
options &= ~CC_PROCESS_PATH;
continue;
}
if (strcmp(name, "COREADM_GLOB_SETID_ENABLED") == 0) {
if (yes(name, value, line))
options |= CC_GLOBAL_SETID;
continue;
}
if (strcmp(name, "COREADM_PROC_SETID_ENABLED") == 0) {
if (yes(name, value, line))
options |= CC_PROCESS_SETID;
continue;
}
if (strcmp(name, "COREADM_GLOB_LOG_ENABLED") == 0) {
if (yes(name, value, line))
options |= CC_GLOBAL_LOG;
continue;
}
(void) fprintf(stderr, gettext(
"\"%s\", line %d: warning: invalid token: %s\n"),
PATH_CONFIG, line, name);
} else {
(void) fprintf(stderr,
gettext("\"%s\", line %d: syntax error\n"),
PATH_CONFIG, line);
}
}
(void) fclose(fp);
return (1);
}
/*
* Loads and applies the coreadm configuration stored in the default
* coreadm instance. As this option is (only) used from within an SMF
* service method, this function must return an SMF_EXIT_* exit status
* to its caller.
*/
static int
do_update(void)
{
char *gcstr, *icstr;
scf_propvec_t properties[MAX_PROPS + 1];
scf_propvec_t *prop;
int count = 0;
const char *errstr;
if (read_legacy()) {
if ((errstr = write_kernel()) != NULL)
goto error;
if (do_modify(B_TRUE) != 0 ||
rename(PATH_CONFIG, PATH_CONFIG_OLD) != 0) {
(void) fprintf(stderr, gettext(
"%s: failed to import legacy configuration.\n"),
command);
return (SMF_EXIT_ERR_FATAL);
}
return (SMF_EXIT_OK);
}
addprop(properties, MAX_PROPS, count++, &prop_gpattern, &glob_pattern);
addprop(properties, MAX_PROPS, count++, &prop_gcontent, &gcstr);
addprop(properties, MAX_PROPS, count++, &prop_ipattern, &init_pattern);
addprop(properties, MAX_PROPS, count++, &prop_icontent, &icstr);
for (prop = prop_option; prop->pv_prop != NULL; prop++)
addprop(properties, MAX_PROPS, count++, prop, &options);
properties[count].pv_prop = NULL;
alloptions = CC_OPTIONS;
if (scf_read_propvec(COREADM_INST_FMRI, CONFIG_PARAMS, B_TRUE,
properties, &prop) == SCF_FAILED) {
if (prop != NULL) {
(void) fprintf(stderr, gettext(
"%s: configuration property '%s' not found.\n"),
command, prop->pv_prop);
} else {
(void) fprintf(stderr, gettext(
"%s: unable to read configuration: %s\n"),
command, scf_strerror(scf_error()));
}
return (SMF_EXIT_ERR_FATAL);
}
(void) proc_str2content(gcstr, &glob_content);
(void) proc_str2content(icstr, &init_content);
errstr = write_kernel();
scf_clean_propvec(properties);
if (errstr == NULL)
return (SMF_EXIT_OK);
error:
if (errno == EPERM) {
(void) perm();
return (SMF_EXIT_ERR_PERM);
}
perror(errstr);
return (SMF_EXIT_ERR_FATAL);
}
static int do_legacy()
{
const char *errstr;
if (read_legacy() && (errstr = write_kernel()) != NULL) {
if (errno == EPERM)
return (perm());
perror(errstr);
return (E_ERROR);
}
return (E_SUCCESS);
}
|
24460.c | /* @(#)e_lgamma.c 1.3 95/01/18 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "math.h"
#include "math_private.h"
extern int signgam;
long double
lgammal(long double x)
{
return lgammal_r(x,&signgam);
}
|
574356.c | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <soso.h>
int get_process_cpu_usage(uint32_t pid, ThreadInfo* threads, uint32_t count)
{
for (size_t i = 0; i < count; i++)
{
ThreadInfo* info = threads + i;
if (info->process_id == pid)
{
return info->usage_cpu;
}
}
return 0;
}
int main(int argc, char** argv)
{
int seconds = 1;
if (argc > 1)
{
sscanf(argv[1], "%d", &seconds);
}
ProcInfo procs[20];
int proc_count = getprocs(procs, 20, 0);
ThreadInfo threads[20];
int thread_count = getthreads(threads, 20, 0);
printf("Process count: %d\n", proc_count);
printf("PID NAME CPU(%%)\n");
for (size_t i = 0; i < proc_count; i++)
{
ProcInfo* p = procs + i;
uint32_t usage = get_process_cpu_usage(p->process_id, threads, thread_count);
printf("%d %s %d\n", p->process_id, p->name, usage);
}
return 0;
}
|
372428.c | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int con, exp, et, n,i,op1,op2,op;
char numi[20], ci, cf;
printf("From which format you want to convert ? \n");
printf("1. Binary\n");
printf("2. Octal\n");
printf("3. Decimal\n");
printf("4. Hexadecimal\n");
scanf("%d", op1);
printf("To which format you want to convert ? \n");
printf("1. Binary\n");
printf("2. Octal\n");
printf("3. Decimal\n");
printf("4. Hexadecimal\n");
scanf("%d", op2);
op=op2+10*op1;
if(op==11 || op==22 || op==33 || op=44)
printf("It is the same as you entered !");
else
switch(op)
{
case 13 :
printf("Enter a number in Binary : \n");
scanf("%s",numi);
for(i=0; numi[i]!='\0'; ++i);
for(n=0; n<=i-1; ++n)
{
ci=numi[i-n-1];
(ci=="1")? et=1 : et=0;
exp=pow(2,n);
con=con+et*exp;
}
}
|
909195.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__rand_memcpy_52a.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-52a.tmpl.c
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: rand Set data to result of rand(), which could be negative
* GoodSource: Positive integer
* Sink: memcpy
* BadSink : Copy strings using memcpy() with the length of data
* Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
/* bad function declaration */
void CWE194_Unexpected_Sign_Extension__rand_memcpy_52b_bad_sink(short data);
void CWE194_Unexpected_Sign_Extension__rand_memcpy_52_bad()
{
short data;
/* Initialize data */
data = 0;
/* POTENTIAL FLAW: Use a random value that could be less than 0 */
data = (short)RAND32();
CWE194_Unexpected_Sign_Extension__rand_memcpy_52b_bad_sink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declaration */
void CWE194_Unexpected_Sign_Extension__rand_memcpy_52b_goodG2B_sink(short data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
short data;
/* Initialize data */
data = 0;
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
CWE194_Unexpected_Sign_Extension__rand_memcpy_52b_goodG2B_sink(data);
}
void CWE194_Unexpected_Sign_Extension__rand_memcpy_52_good()
{
goodG2B();
}
#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()...");
CWE194_Unexpected_Sign_Extension__rand_memcpy_52_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE194_Unexpected_Sign_Extension__rand_memcpy_52_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
692933.c | /*
* Copyright (C) 2012,2013 Free Software Foundation, Inc.
* Copyright (C) 2013 Nikos Mavrogiannopoulos
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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 program. If not, see <http://www.gnu.org/licenses/>
*
*/
/* This file implements the TLS heartbeat extension.
*/
#include "errors.h"
#include "gnutls_int.h"
#include <dtls.h>
#include <record.h>
#include <ext/heartbeat.h>
#include <extensions.h>
#include <random.h>
#ifdef ENABLE_HEARTBEAT
/**
* gnutls_heartbeat_enable:
* @session: is a #gnutls_session_t type.
* @type: one of the GNUTLS_HB_* flags
*
* If this function is called with the %GNUTLS_HB_PEER_ALLOWED_TO_SEND
* @type, GnuTLS will allow heartbeat messages to be received. Moreover it also
* request the peer to accept heartbeat messages.
*
* If the @type used is %GNUTLS_HB_LOCAL_ALLOWED_TO_SEND, then the peer
* will be asked to accept heartbeat messages but not send ones.
*
* The function gnutls_heartbeat_allowed() can be used to test Whether
* locally generated heartbeat messages can be accepted by the peer.
*
* Since: 3.1.2
**/
void gnutls_heartbeat_enable(gnutls_session_t session, unsigned int type)
{
extension_priv_data_t epriv;
epriv = (void*)(intptr_t)type;
_gnutls_ext_set_session_data(session, GNUTLS_EXTENSION_HEARTBEAT,
epriv);
}
/**
* gnutls_heartbeat_allowed:
* @session: is a #gnutls_session_t type.
* @type: one of %GNUTLS_HB_LOCAL_ALLOWED_TO_SEND and %GNUTLS_HB_PEER_ALLOWED_TO_SEND
*
* This function will check whether heartbeats are allowed
* to be sent or received in this session.
*
* Returns: Non zero if heartbeats are allowed.
*
* Since: 3.1.2
**/
int gnutls_heartbeat_allowed(gnutls_session_t session, unsigned int type)
{
extension_priv_data_t epriv;
if (session->internals.handshake_in_progress != 0)
return 0; /* not allowed */
if (_gnutls_ext_get_session_data
(session, GNUTLS_EXTENSION_HEARTBEAT, &epriv) < 0)
return 0; /* Not enabled */
if (type == GNUTLS_HB_LOCAL_ALLOWED_TO_SEND) {
if (((intptr_t)epriv) & LOCAL_ALLOWED_TO_SEND)
return 1;
} else if (((intptr_t)epriv) & GNUTLS_HB_PEER_ALLOWED_TO_SEND)
return 1;
return 0;
}
#define DEFAULT_PADDING_SIZE 16
/*
* Sends heartbeat data.
*/
static int
heartbeat_send_data(gnutls_session_t session, const void *data,
size_t data_size, uint8_t type)
{
int ret, pos;
uint8_t *response;
response = gnutls_malloc(1 + 2 + data_size + DEFAULT_PADDING_SIZE);
if (response == NULL)
return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
pos = 0;
response[pos++] = type;
_gnutls_write_uint16(data_size, &response[pos]);
pos += 2;
memcpy(&response[pos], data, data_size);
pos += data_size;
ret =
gnutls_rnd(GNUTLS_RND_NONCE, &response[pos],
DEFAULT_PADDING_SIZE);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
pos += DEFAULT_PADDING_SIZE;
ret =
_gnutls_send_int(session, GNUTLS_HEARTBEAT, -1,
EPOCH_WRITE_CURRENT, response, pos,
MBUFFER_FLUSH);
cleanup:
gnutls_free(response);
return ret;
}
/**
* gnutls_heartbeat_ping:
* @session: is a #gnutls_session_t type.
* @data_size: is the length of the ping payload.
* @max_tries: if flags is %GNUTLS_HEARTBEAT_WAIT then this sets the number of retransmissions. Use zero for indefinite (until timeout).
* @flags: if %GNUTLS_HEARTBEAT_WAIT then wait for pong or timeout instead of returning immediately.
*
* This function sends a ping to the peer. If the @flags is set
* to %GNUTLS_HEARTBEAT_WAIT then it waits for a reply from the peer.
*
* Note that it is highly recommended to use this function with the
* flag %GNUTLS_HEARTBEAT_WAIT, or you need to handle retransmissions
* and timeouts manually.
*
* The total TLS data transmitted as part of the ping message are given by
* the following formula: MAX(16, @data_size)+gnutls_record_overhead_size()+3.
*
* Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
*
* Since: 3.1.2
**/
int
gnutls_heartbeat_ping(gnutls_session_t session, size_t data_size,
unsigned int max_tries, unsigned int flags)
{
int ret;
unsigned int retries = 1, diff;
struct timespec now;
if (data_size > MAX_HEARTBEAT_LENGTH)
return
gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
if (gnutls_heartbeat_allowed
(session, GNUTLS_HB_LOCAL_ALLOWED_TO_SEND) == 0)
return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
/* resume previous call if interrupted */
if (session->internals.record_send_buffer.byte_length > 0 &&
session->internals.record_send_buffer.head != NULL &&
session->internals.record_send_buffer.head->type ==
GNUTLS_HEARTBEAT)
return _gnutls_io_write_flush(session);
switch (session->internals.hb_state) {
case SHB_SEND1:
if (data_size > DEFAULT_PADDING_SIZE)
data_size -= DEFAULT_PADDING_SIZE;
else
data_size = 0;
_gnutls_buffer_reset(&session->internals.hb_local_data);
ret =
_gnutls_buffer_resize(&session->internals.
hb_local_data, data_size);
if (ret < 0)
return gnutls_assert_val(ret);
ret =
gnutls_rnd(GNUTLS_RND_NONCE,
session->internals.hb_local_data.data,
data_size);
if (ret < 0)
return gnutls_assert_val(ret);
gettime(&session->internals.hb_ping_start);
session->internals.hb_local_data.length = data_size;
session->internals.hb_state = SHB_SEND2;
/* fallthrough */
case SHB_SEND2:
session->internals.hb_actual_retrans_timeout_ms =
session->internals.hb_retrans_timeout_ms;
retry:
ret =
heartbeat_send_data(session,
session->internals.hb_local_data.
data,
session->internals.hb_local_data.
length, HEARTBEAT_REQUEST);
if (ret < 0)
return gnutls_assert_val(ret);
gettime(&session->internals.hb_ping_sent);
if (!(flags & GNUTLS_HEARTBEAT_WAIT)) {
session->internals.hb_state = SHB_SEND1;
break;
}
session->internals.hb_state = SHB_RECV;
/* fallthrough */
case SHB_RECV:
ret =
_gnutls_recv_int(session, GNUTLS_HEARTBEAT,
NULL, 0, NULL,
session->internals.
hb_actual_retrans_timeout_ms);
if (ret == GNUTLS_E_HEARTBEAT_PONG_RECEIVED) {
session->internals.hb_state = SHB_SEND1;
break;
} else if (ret == GNUTLS_E_TIMEDOUT) {
retries++;
if (max_tries > 0 && retries > max_tries) {
session->internals.hb_state = SHB_SEND1;
return gnutls_assert_val(ret);
}
gettime(&now);
diff =
timespec_sub_ms(&now,
&session->internals.
hb_ping_start);
if (diff > session->internals.hb_total_timeout_ms) {
session->internals.hb_state = SHB_SEND1;
return
gnutls_assert_val(GNUTLS_E_TIMEDOUT);
}
session->internals.hb_actual_retrans_timeout_ms *=
2;
session->internals.hb_actual_retrans_timeout_ms %=
MAX_DTLS_TIMEOUT;
session->internals.hb_state = SHB_SEND2;
goto retry;
} else if (ret < 0) {
session->internals.hb_state = SHB_SEND1;
return gnutls_assert_val(ret);
}
}
return 0;
}
/**
* gnutls_heartbeat_pong:
* @session: is a #gnutls_session_t type.
* @flags: should be zero
*
* This function replies to a ping by sending a pong to the peer.
*
* Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
*
* Since: 3.1.2
**/
int gnutls_heartbeat_pong(gnutls_session_t session, unsigned int flags)
{
int ret;
if (session->internals.record_send_buffer.byte_length > 0 &&
session->internals.record_send_buffer.head != NULL &&
session->internals.record_send_buffer.head->type ==
GNUTLS_HEARTBEAT)
return _gnutls_io_write_flush(session);
if (session->internals.hb_remote_data.length == 0)
return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
ret =
heartbeat_send_data(session,
session->internals.hb_remote_data.data,
session->internals.hb_remote_data.length,
HEARTBEAT_RESPONSE);
_gnutls_buffer_reset(&session->internals.hb_remote_data);
if (ret < 0)
return gnutls_assert_val(ret);
return 0;
}
/*
* Processes a heartbeat message.
*/
int _gnutls_heartbeat_handle(gnutls_session_t session, mbuffer_st * bufel)
{
int ret;
unsigned type;
unsigned pos;
uint8_t *msg = _mbuffer_get_udata_ptr(bufel);
size_t hb_len, len = _mbuffer_get_udata_size(bufel);
if (gnutls_heartbeat_allowed
(session, GNUTLS_HB_PEER_ALLOWED_TO_SEND) == 0)
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
if (len < 3 + DEFAULT_PADDING_SIZE)
return
gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
pos = 0;
type = msg[pos++];
hb_len = _gnutls_read_uint16(&msg[pos]);
if (hb_len > len - 3 - DEFAULT_PADDING_SIZE)
return
gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
pos += 2;
switch (type) {
case HEARTBEAT_REQUEST:
_gnutls_buffer_reset(&session->internals.hb_remote_data);
ret =
_gnutls_buffer_resize(&session->internals.
hb_remote_data, hb_len);
if (ret < 0)
return gnutls_assert_val(ret);
if (hb_len > 0)
memcpy(session->internals.hb_remote_data.data,
&msg[pos], hb_len);
session->internals.hb_remote_data.length = hb_len;
return gnutls_assert_val(GNUTLS_E_HEARTBEAT_PING_RECEIVED);
case HEARTBEAT_RESPONSE:
if (hb_len != session->internals.hb_local_data.length)
return
gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
if (hb_len > 0 &&
memcmp(&msg[pos],
session->internals.hb_local_data.data,
hb_len) != 0) {
if (IS_DTLS(session))
return gnutls_assert_val(GNUTLS_E_AGAIN); /* ignore it */
else
return
gnutls_assert_val
(GNUTLS_E_UNEXPECTED_PACKET);
}
_gnutls_buffer_reset(&session->internals.hb_local_data);
return gnutls_assert_val(GNUTLS_E_HEARTBEAT_PONG_RECEIVED);
default:
_gnutls_record_log
("REC[%p]: HB: received unknown type %u\n", session,
type);
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
}
}
/**
* gnutls_heartbeat_get_timeout:
* @session: is a #gnutls_session_t type.
*
* This function will return the milliseconds remaining
* for a retransmission of the previously sent ping
* message. This function is useful when ping is used in
* non-blocking mode, to estimate when to call gnutls_heartbeat_ping()
* if no packets have been received.
*
* Returns: the remaining time in milliseconds.
*
* Since: 3.1.2
**/
unsigned int gnutls_heartbeat_get_timeout(gnutls_session_t session)
{
struct timespec now;
unsigned int diff;
gettime(&now);
diff = timespec_sub_ms(&now, &session->internals.hb_ping_sent);
if (diff >= session->internals.hb_actual_retrans_timeout_ms)
return 0;
else
return session->internals.hb_actual_retrans_timeout_ms -
diff;
}
/**
* gnutls_heartbeat_set_timeouts:
* @session: is a #gnutls_session_t type.
* @retrans_timeout: The time at which a retransmission will occur in milliseconds
* @total_timeout: The time at which the connection will be aborted, in milliseconds.
*
* This function will override the timeouts for the DTLS heartbeat
* protocol. The retransmission timeout is the time after which a
* message from the peer is not received, the previous request will
* be retransmitted. The total timeout is the time after which the
* handshake will be aborted with %GNUTLS_E_TIMEDOUT.
*
* Since: 3.1.2
**/
void gnutls_heartbeat_set_timeouts(gnutls_session_t session,
unsigned int retrans_timeout,
unsigned int total_timeout)
{
session->internals.hb_retrans_timeout_ms = retrans_timeout;
session->internals.hb_total_timeout_ms = total_timeout;
}
static int
_gnutls_heartbeat_recv_params(gnutls_session_t session,
const uint8_t * data, size_t _data_size)
{
unsigned policy;
extension_priv_data_t epriv;
if (_gnutls_ext_get_session_data
(session, GNUTLS_EXTENSION_HEARTBEAT, &epriv) < 0) {
if (session->security_parameters.entity == GNUTLS_CLIENT)
return
gnutls_assert_val
(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER);
return 0; /* Not enabled */
}
if (_data_size == 0)
return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
policy = (intptr_t)epriv;
if (data[0] == 1)
policy |= LOCAL_ALLOWED_TO_SEND;
else if (data[0] == 2)
policy |= LOCAL_NOT_ALLOWED_TO_SEND;
else
return
gnutls_assert_val(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER);
epriv = (void*)(intptr_t)policy;
_gnutls_ext_set_session_data(session, GNUTLS_EXTENSION_HEARTBEAT,
epriv);
return 0;
}
static int
_gnutls_heartbeat_send_params(gnutls_session_t session,
gnutls_buffer_st * extdata)
{
extension_priv_data_t epriv;
uint8_t p;
if (_gnutls_ext_get_session_data
(session, GNUTLS_EXTENSION_HEARTBEAT, &epriv) < 0)
return 0; /* nothing to send - not enabled */
if (((intptr_t)epriv) & GNUTLS_HB_PEER_ALLOWED_TO_SEND)
p = 1;
else /*if (epriv.num & GNUTLS_HB_PEER_NOT_ALLOWED_TO_SEND) */
p = 2;
if (_gnutls_buffer_append_data(extdata, &p, 1) < 0)
return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
return 1;
}
static int
_gnutls_heartbeat_pack(extension_priv_data_t epriv, gnutls_buffer_st * ps)
{
int ret;
BUFFER_APPEND_NUM(ps, (intptr_t)epriv);
return 0;
}
static int
_gnutls_heartbeat_unpack(gnutls_buffer_st * ps,
extension_priv_data_t * _priv)
{
extension_priv_data_t epriv;
int ret;
BUFFER_POP_CAST_NUM(ps, epriv);
*_priv = epriv;
ret = 0;
error:
return ret;
}
const extension_entry_st ext_mod_heartbeat = {
.name = "Heartbeat",
.type = GNUTLS_EXTENSION_HEARTBEAT,
.parse_type = GNUTLS_EXT_TLS,
.recv_func = _gnutls_heartbeat_recv_params,
.send_func = _gnutls_heartbeat_send_params,
.pack_func = _gnutls_heartbeat_pack,
.unpack_func = _gnutls_heartbeat_unpack,
.deinit_func = NULL
};
#else
void gnutls_heartbeat_enable(gnutls_session_t session, unsigned int type)
{
}
int gnutls_heartbeat_allowed(gnutls_session_t session, unsigned int type)
{
return 0;
}
int
gnutls_heartbeat_ping(gnutls_session_t session, size_t data_size,
unsigned int max_tries, unsigned int flags)
{
return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
}
int gnutls_heartbeat_pong(gnutls_session_t session, unsigned int flags)
{
return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
}
unsigned int gnutls_heartbeat_get_timeout(gnutls_session_t session)
{
return 0;
}
void gnutls_heartbeat_set_timeouts(gnutls_session_t session,
unsigned int retrans_timeout,
unsigned int total_timeout)
{
return;
}
#endif
|
794950.c | /*******************************************************************************
* File Name: ADC_1.c
* Version 3.10
*
* Description:
* This file provides the source code to the API for the Successive
* approximation ADC Component.
*
* Note:
*
********************************************************************************
* Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#include "CyLib.h"
#include "ADC_1.h"
#if(ADC_1_DEFAULT_INTERNAL_CLK)
#include "ADC_1_theACLK.h"
#endif /* End ADC_1_DEFAULT_INTERNAL_CLK */
/***************************************
* Forward function references
***************************************/
static void ADC_1_CalcGain(uint8 resolution);
/***************************************
* Global data allocation
***************************************/
uint8 ADC_1_initVar = 0u;
volatile int16 ADC_1_offset;
volatile int16 ADC_1_countsPerVolt; /* Obsolete Gain compensation */
volatile int32 ADC_1_countsPer10Volt; /* Gain compensation */
volatile int16 ADC_1_shift;
/*******************************************************************************
* Function Name: ADC_1_Start
********************************************************************************
*
* Summary:
* This is the preferred method to begin component operation.
* ADC_1_Start() sets the initVar variable, calls the
* ADC_1_Init() function, and then calls the
* ADC_1_Enable() function.
*
* Parameters:
* None.
*
* Return:
* None.
*
* Global variables:
* The ADC_1_initVar variable is used to indicate when/if initial
* configuration of this component has happened. The variable is initialized to
* zero and set to 1 the first time ADC_Start() is called. This allows for
* component Re-Start without re-initialization in all subsequent calls to the
* ADC_1_Start() routine.
* If re-initialization of the component is required the variable should be set
* to zero before call of ADC_1_Start() routine, or the user may call
* ADC_1_Init() and ADC_1_Enable() as done in the
* ADC_1_Start() routine.
*
* Side Effect:
* If the initVar variable is already set, this function only calls the
* ADC_1_Enable() function.
*
*******************************************************************************/
void ADC_1_Start(void)
{
/* If not Initialized then initialize all required hardware and software */
if(ADC_1_initVar == 0u)
{
ADC_1_Init();
ADC_1_initVar = 1u;
}
ADC_1_Enable();
}
/*******************************************************************************
* Function Name: ADC_1_Init
********************************************************************************
*
* Summary:
* Initialize component's parameters to the parameters set by user in the
* customizer of the component placed onto schematic. Usually called in
* ADC_1_Start().
*
* Parameters:
* None.
*
* Return:
* None.
*
* Global variables:
* The ADC_1_offset variable is initialized to 0.
*
*******************************************************************************/
void ADC_1_Init(void)
{
/* This is only valid if there is an internal clock */
#if(ADC_1_DEFAULT_INTERNAL_CLK)
ADC_1_theACLK_SetMode(CYCLK_DUTY);
#endif /* End ADC_1_DEFAULT_INTERNAL_CLK */
#if(ADC_1_IRQ_REMOVE == 0u)
/* Start and set interrupt vector */
CyIntSetPriority(ADC_1_INTC_NUMBER, ADC_1_INTC_PRIOR_NUMBER);
(void)CyIntSetVector(ADC_1_INTC_NUMBER, &ADC_1_ISR);
#endif /* End ADC_1_IRQ_REMOVE */
/* Enable IRQ mode*/
ADC_1_SAR_CSR1_REG |= ADC_1_SAR_IRQ_MASK_EN | ADC_1_SAR_IRQ_MODE_EDGE;
/*Set SAR ADC resolution ADC */
ADC_1_SetResolution(ADC_1_DEFAULT_RESOLUTION);
ADC_1_offset = 0;
}
/*******************************************************************************
* Function Name: ADC_1_Enable
********************************************************************************
*
* Summary:
* Enables the reference, clock and power for SAR ADC.
*
* Parameters:
* None.
*
* Return:
* None.
*
*******************************************************************************/
void ADC_1_Enable(void)
{
uint8 tmpReg;
uint8 enableInterrupts;
enableInterrupts = CyEnterCriticalSection();
/* Enable the SAR ADC block in Active Power Mode */
ADC_1_PWRMGR_SAR_REG |= ADC_1_ACT_PWR_SAR_EN;
/* Enable the SAR ADC in Standby Power Mode*/
ADC_1_STBY_PWRMGR_SAR_REG |= ADC_1_STBY_PWR_SAR_EN;
/* This is only valid if there is an internal clock */
#if(ADC_1_DEFAULT_INTERNAL_CLK)
ADC_1_PWRMGR_CLK_REG |= ADC_1_ACT_PWR_CLK_EN;
ADC_1_STBY_PWRMGR_CLK_REG |= ADC_1_STBY_PWR_CLK_EN;
#endif /* End ADC_1_DEFAULT_INTERNAL_CLK */
/* Enable VCM buffer and Enable Int Ref Amp */
tmpReg = ADC_1_SAR_CSR3_REG;
tmpReg |= ADC_1_SAR_EN_BUF_VCM_EN;
/* PD_BUF_VREF is OFF in External reference or Vdda reference mode */
#if((ADC_1_DEFAULT_REFERENCE == ADC_1__EXT_REF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VNEG_VDDA_DIFF))
tmpReg &= (uint8)~ADC_1_SAR_EN_BUF_VREF_EN;
#else /* In INTREF or INTREF Bypassed this buffer is ON */
tmpReg |= ADC_1_SAR_EN_BUF_VREF_EN;
#endif /* ADC_1_DEFAULT_REFERENCE == ADC_1__EXT_REF */
ADC_1_SAR_CSR3_REG = tmpReg;
/* Set reference for ADC */
#if(ADC_1_DEFAULT_RANGE == ADC_1__VNEG_VDDA_DIFF)
#if(ADC_1_DEFAULT_REFERENCE == ADC_1__EXT_REF)
ADC_1_SAR_CSR6_REG = ADC_1_INT_BYPASS_EXT_VREF; /* S2 */
#else /* Internal Vdda reference or obsolete bypass mode */
ADC_1_SAR_CSR6_REG = ADC_1_VDDA_VREF; /* S7 */
#endif /* ADC_1_DEFAULT_REFERENCE == ADC_1__EXT_REF */
#else /* Reference goes through internal buffer */
#if(ADC_1_DEFAULT_REFERENCE == ADC_1__INT_REF_NOT_BYPASSED)
ADC_1_SAR_CSR6_REG = ADC_1_INT_VREF; /* S3 + S4 */
#else /* INTREF Bypassed of External */
ADC_1_SAR_CSR6_REG = ADC_1_INT_BYPASS_EXT_VREF; /* S2 */
#endif /* ADC_1_DEFAULT_REFERENCE == ADC_1__INT_REF_NOT_BYPASSED */
#endif /* VNEG_VDDA_DIFF */
/* Low non-overlap delay for sampling clock signals (for 1MSPS) */
#if(ADC_1_HIGH_POWER_PULSE == 0u) /* MinPulseWidth <= 50 ns */
ADC_1_SAR_CSR5_REG &= (uint8)~ADC_1_SAR_DLY_INC;
#else /* Set High non-overlap delay for sampling clock signals (for <500KSPS)*/
ADC_1_SAR_CSR5_REG |= ADC_1_SAR_DLY_INC;
#endif /* ADC_1_HIGH_POWER_PULSE == 0u */
/* Increase comparator latch enable delay by 20%,
* Increase comparator bias current by 30% without impacting delaysDelay
* Default for 1MSPS)
*/
#if(ADC_1_HIGH_POWER_PULSE == 0u) /* MinPulseWidth <= 50 ns */
ADC_1_SAR_CSR5_REG |= ADC_1_SAR_SEL_CSEL_DFT_CHAR;
#else /* for <500ksps */
ADC_1_SAR_CSR5_REG &= (uint8)~ADC_1_SAR_SEL_CSEL_DFT_CHAR;
#endif /* ADC_1_HIGH_POWER_PULSE == 0u */
/* Set default power and other configurations for control register 0 in multiple lines */
ADC_1_SAR_CSR0_REG = (uint8)((uint8)ADC_1_DEFAULT_POWER << ADC_1_SAR_POWER_SHIFT)
/* SAR_HIZ_CLEAR: Should not be used for LP */
#if ((CY_PSOC5LP) || (ADC_1_DEFAULT_REFERENCE != ADC_1__EXT_REF))
| ADC_1_SAR_HIZ_CLEAR
#endif /* SAR_HIZ_CLEAR */
/*Set Convertion mode */
#if(ADC_1_DEFAULT_CONV_MODE != ADC_1__FREE_RUNNING) /* If triggered mode */
| ADC_1_SAR_MX_SOF_UDB /* source: UDB */
| ADC_1_SAR_SOF_MODE_EDGE /* Set edge-sensitive sof source */
#endif /* ADC_1_DEFAULT_CONV_MODE */
; /* end of multiple line initialization */
ADC_1_SAR_TR0_REG = ADC_1_SAR_CAP_TRIM_2;
/* Enable clock for SAR ADC*/
ADC_1_SAR_CLK_REG |= ADC_1_SAR_MX_CLK_EN;
CyDelayUs(10u); /* The block is ready to use 10 us after the enable signal is set high. */
#if(ADC_1_IRQ_REMOVE == 0u)
/* Clear a pending interrupt */
CyIntClearPending(ADC_1_INTC_NUMBER);
#endif /* End ADC_1_IRQ_REMOVE */
CyExitCriticalSection(enableInterrupts);
}
/*******************************************************************************
* Function Name: ADC_1_Stop
********************************************************************************
*
* Summary:
* Stops ADC conversions and puts the ADC into its lowest power mode.
*
* Parameters:
* None.
*
* Return:
* None.
*
*******************************************************************************/
void ADC_1_Stop(void)
{
uint8 enableInterrupts;
enableInterrupts = CyEnterCriticalSection();
/* Stop all conversions */
ADC_1_SAR_CSR0_REG &= (uint8)~ADC_1_SAR_SOF_START_CONV;
/* Disable the SAR ADC block in Active Power Mode */
ADC_1_PWRMGR_SAR_REG &= (uint8)~ADC_1_ACT_PWR_SAR_EN;
/* Disable the SAR ADC in Standby Power Mode */
ADC_1_STBY_PWRMGR_SAR_REG &= (uint8)~ADC_1_STBY_PWR_SAR_EN;
/* This is only valid if there is an internal clock */
#if(ADC_1_DEFAULT_INTERNAL_CLK)
ADC_1_PWRMGR_CLK_REG &= (uint8)~ADC_1_ACT_PWR_CLK_EN;
ADC_1_STBY_PWRMGR_CLK_REG &= (uint8)~ADC_1_STBY_PWR_CLK_EN;
#endif /* End ADC_1_DEFAULT_INTERNAL_CLK */
CyExitCriticalSection(enableInterrupts);
}
/*******************************************************************************
* Function Name: ADC_1_SetPower
********************************************************************************
*
* Summary:
* Sets the operational power of the ADC. You should use the higher power
* settings with faster clock speeds.
*
* Parameters:
* power: Power setting for ADC
* 0 -> Normal
* 1 -> Medium power
* 2 -> 1.25 power
* 3 -> Minimum power.
*
* Return:
* None.
*
*******************************************************************************/
void ADC_1_SetPower(uint8 power)
{
uint8 tmpReg;
/* mask off invalid power settings */
power &= ADC_1_SAR_API_POWER_MASK;
/* Set Power parameter */
tmpReg = ADC_1_SAR_CSR0_REG & (uint8)~ADC_1_SAR_POWER_MASK;
tmpReg |= (uint8)(power << ADC_1_SAR_POWER_SHIFT);
ADC_1_SAR_CSR0_REG = tmpReg;
}
/*******************************************************************************
* Function Name: ADC_1_SetResolution
********************************************************************************
*
* Summary:
* Sets the Relution of the SAR.
*
* Parameters:
* resolution:
* 12 -> RES12
* 10 -> RES10
* 8 -> RES8
*
* Return:
* None.
*
* Side Effects:
* The ADC resolution cannot be changed during a conversion cycle. The
* recommended best practice is to stop conversions with
* ADC_StopConvert(), change the resolution, then restart the
* conversions with ADC_StartConvert().
* If you decide not to stop conversions before calling this API, you
* should use ADC_IsEndConversion() to wait until conversion is complete
* before changing the resolution.
* If you call ADC_SetResolution() during a conversion, the resolution will
* not be changed until the current conversion is complete. Data will not be
* available in the new resolution for another 6 + "New Resolution(in bits)"
* clock cycles.
* You may need add a delay of this number of clock cycles after
* ADC_SetResolution() is called before data is valid again.
* Affects ADC_CountsTo_Volts(), ADC_CountsTo_mVolts(), and
* ADC_CountsTo_uVolts() by calculating the correct conversion between ADC
* counts and the applied input voltage. Calculation depends on resolution,
* input range, and voltage reference.
*
*******************************************************************************/
void ADC_1_SetResolution(uint8 resolution)
{
uint8 tmpReg;
/* Set SAR ADC resolution and sample width: 18 conversion cycles at 12bits + 1 gap */
switch (resolution)
{
case (uint8)ADC_1__BITS_12:
tmpReg = ADC_1_SAR_RESOLUTION_12BIT | ADC_1_SAR_SAMPLE_WIDTH;
break;
case (uint8)ADC_1__BITS_10:
tmpReg = ADC_1_SAR_RESOLUTION_10BIT | ADC_1_SAR_SAMPLE_WIDTH;
break;
case (uint8)ADC_1__BITS_8:
tmpReg = ADC_1_SAR_RESOLUTION_8BIT | ADC_1_SAR_SAMPLE_WIDTH;
break;
default:
tmpReg = ADC_1_SAR_RESOLUTION_12BIT | ADC_1_SAR_SAMPLE_WIDTH;
/* Halt CPU in debug mode if resolution is out of valid range */
CYASSERT(0u != 0u);
break;
}
ADC_1_SAR_CSR2_REG = tmpReg;
/* Calculate gain for convert counts to volts */
ADC_1_CalcGain(resolution);
}
#if(ADC_1_DEFAULT_CONV_MODE != ADC_1__HARDWARE_TRIGGER)
/*******************************************************************************
* Function Name: ADC_1_StartConvert
********************************************************************************
*
* Summary:
* Forces the ADC to initiate a conversion. In free-running mode, the ADC runs
* continuously. In software trigger mode, the function also acts as a software
* version of the SOC and every conversion must be triggered by
* ADC_1_StartConvert(). This function is not available when the
* Hardware Trigger sample mode is selected.
*
* Parameters:
* None.
*
* Return:
* None.
*
* Theory:
* Forces the ADC to initiate a conversion. In Free Running mode, the ADC will
* run continuously. In a software trigger mode the function also acts as a
* software version of the SOC. Here every conversion has to be triggered by
* the routine. This writes into the SOC bit in SAR_CTRL reg.
*
* Side Effects:
* In a software trigger mode the function switches source for SOF from the
* external pin to the internal SOF generation. Application should not call
* StartConvert if external source used for SOF.
*
*******************************************************************************/
void ADC_1_StartConvert(void)
{
#if(ADC_1_DEFAULT_CONV_MODE != ADC_1__FREE_RUNNING) /* If software triggered mode */
ADC_1_SAR_CSR0_REG &= (uint8)~ADC_1_SAR_MX_SOF_UDB; /* source: SOF bit */
#endif /* End ADC_1_DEFAULT_CONV_MODE */
/* Start the conversion */
ADC_1_SAR_CSR0_REG |= ADC_1_SAR_SOF_START_CONV;
}
/*******************************************************************************
* Function Name: ADC_1_StopConvert
********************************************************************************
*
* Summary:
* Forces the ADC to stop conversions. If a conversion is currently executing,
* that conversion will complete, but no further conversions will occur. This
* function is not available when the Hardware Trigger sample mode is selected.
*
* Parameters:
* None.
*
* Return:
* None.
*
* Theory:
* Stops ADC conversion in Free Running mode.
*
* Side Effects:
* In Software Trigger sample mode, this function sets a software version of the
* SOC to low level and switches the SOC source to hardware SOC input.
*
*******************************************************************************/
void ADC_1_StopConvert(void)
{
/* Stop all conversions */
ADC_1_SAR_CSR0_REG &= (uint8)~ADC_1_SAR_SOF_START_CONV;
#if(ADC_1_DEFAULT_CONV_MODE != ADC_1__FREE_RUNNING) /* If software triggered mode */
/* Return source to UDB for hardware SOF signal */
ADC_1_SAR_CSR0_REG |= ADC_1_SAR_MX_SOF_UDB; /* source: UDB */
#endif /* End ADC_1_DEFAULT_CONV_MODE */
}
#endif /* End ADC_1_DEFAULT_CONV_MODE != ADC_1__HARDWARE_TRIGGER */
/*******************************************************************************
* Function Name: ADC_1_IsEndConversion
********************************************************************************
*
* Summary:
* Immediately returns the status of the conversion or does not return
* (blocking) until the conversion completes, depending on the retMode
* parameter.
*
* Parameters:
* retMode: Check conversion return mode.
* ADC_1_RETURN_STATUS: Immediately returns the status. If the
* value returned is zero, the conversion is not complete, and this function
* should be retried until a nonzero result is returned.
* ADC_1_WAIT_FOR_RESULT: Does not return a result until the ADC
* conversion is complete.
*
* Return:
* (uint8) 0 => The ADC is still calculating the last result.
* 1 => The last conversion is complete.
*
* Side Effects:
* This function reads the end of conversion status, which is cleared on read.
*
*******************************************************************************/
uint8 ADC_1_IsEndConversion(uint8 retMode)
{
uint8 status;
do
{
status = ADC_1_SAR_CSR1_REG & ADC_1_SAR_EOF_1;
} while ((status != ADC_1_SAR_EOF_1) && (retMode == ADC_1_WAIT_FOR_RESULT));
/* If convertion complete, wait until EOF bit released */
if(status == ADC_1_SAR_EOF_1)
{
/* wait one ADC clock to let the EOC status bit release */
CyDelayUs(1u);
/* Do the unconditional read operation of the CSR1 register to make sure the EOC bit has been cleared */
CY_GET_REG8(ADC_1_SAR_CSR1_PTR);
}
return(status);
}
/*******************************************************************************
* Function Name: ADC_1_GetResult8
********************************************************************************
*
* Summary:
* Returns the result of an 8-bit conversion. If the resolution is set greater
* than 8 bits, the function returns the LSB of the result.
* ADC_1_IsEndConversion() should be called to verify that the data
* sample is ready.
*
* Parameters:
* None.
*
* Return:
* The LSB of the last ADC conversion.
*
* Global Variables:
* ADC_1_shift - used to convert the ADC counts to the 2s
* compliment form.
*
* Side Effects:
* Converts the ADC counts to the 2s complement form.
*
*******************************************************************************/
int8 ADC_1_GetResult8( void )
{
return( (int8)ADC_1_SAR_WRK0_REG - (int8)ADC_1_shift);
}
/*******************************************************************************
* Function Name: ADC_1_GetResult16
********************************************************************************
*
* Summary:
* Returns a 16-bit result for a conversion with a result that has a resolution
* of 8 to 12 bits.
* ADC_1_IsEndConversion() should be called to verify that the data
* sample is ready
*
* Parameters:
* None.
*
* Return:
* The 16-bit result of the last ADC conversion
*
* Global Variables:
* ADC_1_shift - used to convert the ADC counts to the 2s
* compliment form.
*
* Side Effects:
* Converts the ADC counts to the 2s complement form.
*
*******************************************************************************/
int16 ADC_1_GetResult16( void )
{
uint16 res;
res = CY_GET_REG16(ADC_1_SAR_WRK_PTR);
return( (int16)res - ADC_1_shift );
}
/*******************************************************************************
* Function Name: ADC_1_SetOffset
********************************************************************************
*
* Summary:
* Sets the ADC offset, which is used by ADC_1_CountsTo_Volts(),
* ADC_1_CountsTo_mVolts(), and ADC_1_CountsTo_uVolts()
* to subtract the offset from the given reading before calculating the voltage
* conversion.
*
* Parameters:
* int16: This value is measured when the inputs are shorted or connected to
the same input voltage.
*
* Return:
* None.
*
* Global Variables:
* The ADC_1_offset variable modified. This variable is used for
* offset calibration purpose.
* Affects the ADC_1_CountsTo_Volts,
* ADC_1_CountsTo_mVolts, ADC_1_CountsTo_uVolts functions
* by subtracting the given offset.
*
*******************************************************************************/
void ADC_1_SetOffset(int16 offset)
{
ADC_1_offset = offset;
}
/*******************************************************************************
* Function Name: ADC_1_CalcGain
********************************************************************************
*
* Summary:
* This function calculates the ADC gain in counts per 10 volt.
*
* Parameters:
* uint8: resolution
*
* Return:
* None.
*
* Global Variables:
* ADC_1_shift variable initialized. This variable is used to
* convert the ADC counts to the 2s compliment form.
* ADC_1_countsPer10Volt variable initialized. This variable is used
* for gain calibration purpose.
*
*******************************************************************************/
static void ADC_1_CalcGain( uint8 resolution )
{
int32 counts;
#if(!((ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC)) )
uint16 diff_zero;
#endif /* End ADC_1_DEFAULT_RANGE */
switch (resolution)
{
case (uint8)ADC_1__BITS_12:
counts = (int32)ADC_1_SAR_WRK_MAX_12BIT;
#if(!((ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC)) )
diff_zero = ADC_1_SAR_DIFF_SHIFT;
#endif /* End ADC_1_DEFAULT_RANGE */
break;
case (uint8)ADC_1__BITS_10:
counts = (int32)ADC_1_SAR_WRK_MAX_10BIT;
#if(!((ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC)) )
diff_zero = ADC_1_SAR_DIFF_SHIFT >> 2u;
#endif /* End ADC_1_DEFAULT_RANGE */
break;
case (uint8)ADC_1__BITS_8:
counts = (int32)ADC_1_SAR_WRK_MAX_8BIT;
#if(!((ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC)) )
diff_zero = ADC_1_SAR_DIFF_SHIFT >> 4u;
#endif /* End ADC_1_DEFAULT_RANGE */
break;
default: /* Halt CPU in debug mode if resolution is out of valid range */
counts = 0;
#if(!((ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC)) )
diff_zero = 0u;
#endif /* End ADC_1_DEFAULT_RANGE */
CYASSERT(0u != 0u);
break;
}
ADC_1_countsPerVolt = 0; /* Clear obsolete variable */
/* Calculate gain in counts per 10 volts with rounding */
ADC_1_countsPer10Volt = (((counts * ADC_1_10MV_COUNTS) +
ADC_1_DEFAULT_REF_VOLTAGE_MV) / (ADC_1_DEFAULT_REF_VOLTAGE_MV * 2));
#if( (ADC_1_DEFAULT_RANGE == ADC_1__VSS_TO_VREF) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDDA) || \
(ADC_1_DEFAULT_RANGE == ADC_1__VSSA_TO_VDAC) )
ADC_1_shift = 0;
#else
ADC_1_shift = diff_zero;
#endif /* End ADC_1_DEFAULT_RANGE */
}
/*******************************************************************************
* Function Name: ADC_1_SetGain
********************************************************************************
*
* Summary:
* Sets the ADC gain in counts per volt for the voltage conversion functions
* that follow. This value is set by default by the reference and input range
* settings. It should only be used to further calibrate the ADC with a known
* input or if the ADC is using an external reference.
*
* Parameters:
* int16 adcGain counts per volt
*
* Return:
* None.
*
* Global Variables:
* ADC_1_countsPer10Volt variable modified. This variable is used
* for gain calibration purpose.
*
*******************************************************************************/
void ADC_1_SetGain(int16 adcGain)
{
ADC_1_countsPer10Volt = (int32)adcGain * 10;
}
/*******************************************************************************
* Function Name: ADC_1_SetScaledGain
********************************************************************************
*
* Summary:
* Sets the ADC gain in counts per 10 volt for the voltage conversion functions
* that follow. This value is set by default by the reference and input range
* settings. It should only be used to further calibrate the ADC with a known
* input or if the ADC is using an external reference.
*
* Parameters:
* int32 adcGain counts per 10 volt
*
* Return:
* None.
*
* Global Variables:
* ADC_1_countsPer10Volt variable modified. This variable is used
* for gain calibration purpose.
*
*******************************************************************************/
void ADC_1_SetScaledGain(int32 adcGain)
{
ADC_1_countsPer10Volt = adcGain;
}
/*******************************************************************************
* Function Name: ADC_1_CountsTo_mVolts
********************************************************************************
*
* Summary:
* Converts the ADC output to millivolts as a 16-bit integer.
*
* Parameters:
* int16 adcCounts: Result from the ADC conversion
*
* Return:
* int16 Result in mVolts
*
* Global Variables:
* ADC_1_offset variable used.
* ADC_1_countsPer10Volt variable used.
*
*******************************************************************************/
int16 ADC_1_CountsTo_mVolts(int16 adcCounts)
{
int16 mVolts;
int32 countsPer10Volt;
if(ADC_1_countsPerVolt != 0)
{ /* Support obsolete method */
countsPer10Volt = (int32)ADC_1_countsPerVolt * 10;
}
else
{
countsPer10Volt = ADC_1_countsPer10Volt;
}
/* Subtract ADC offset */
adcCounts -= ADC_1_offset;
/* Convert to millivolts with rounding */
mVolts = (int16)( (( (int32)adcCounts * ADC_1_10MV_COUNTS ) + ( (adcCounts > 0) ?
(countsPer10Volt / 2) : (-(countsPer10Volt / 2)) )) / countsPer10Volt);
return( mVolts );
}
/*******************************************************************************
* Function Name: ADC_1_CountsTo_uVolts
********************************************************************************
*
* Summary:
* Converts the ADC output to microvolts as a 32-bit integer.
*
* Parameters:
* int16 adcCounts: Result from the ADC conversion
*
* Return:
* int32 Result in micro Volts
*
* Global Variables:
* ADC_1_offset variable used.
* ADC_1_countsPer10Volt used to convert ADC counts to uVolts.
*
*******************************************************************************/
int32 ADC_1_CountsTo_uVolts(int16 adcCounts)
{
int64 uVolts;
int32 countsPer10Volt;
if(ADC_1_countsPerVolt != 0)
{ /* Support obsolete method */
countsPer10Volt = (int32)ADC_1_countsPerVolt * 10;
}
else
{
countsPer10Volt = ADC_1_countsPer10Volt;
}
/* Subtract ADC offset */
adcCounts -= ADC_1_offset;
/* To convert adcCounts to microVolts it is required to be multiplied
* on 10 million and later divide on gain in counts per 10V.
*/
uVolts = (( (int64)adcCounts * ADC_1_10UV_COUNTS ) / countsPer10Volt);
return((int32) uVolts );
}
/*******************************************************************************
* Function Name: ADC_1_CountsTo_Volts
********************************************************************************
*
* Summary:
* Converts the ADC output to volts as a floating-point number.
*
* Parameters:
* int16 adcCounts: Result from the ADC conversion
*
* Return:
* float Result in Volts
*
* Global Variables:
* ADC_1_offset variable used.
* ADC_1_countsPer10Volt used to convert ADC counts to Volts.
*
*******************************************************************************/
float32 ADC_1_CountsTo_Volts(int16 adcCounts)
{
float32 volts;
int32 countsPer10Volt;
if(ADC_1_countsPerVolt != 0)
{ /* Support obsolete method */
countsPer10Volt = (int32)ADC_1_countsPerVolt * 10;
}
else
{
countsPer10Volt = ADC_1_countsPer10Volt;
}
/* Subtract ADC offset */
adcCounts -= ADC_1_offset;
volts = ((float32)adcCounts * ADC_1_10V_COUNTS) / (float32)countsPer10Volt;
return( volts );
}
/* [] END OF FILE */
|
295285.c | /* Round to long int long double floating-point values.
IBM extended format long double version.
Copyright (C) 2006-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <math.h>
#include <fenv.h>
#include <math_ldbl_opt.h>
#include <float.h>
#include <ieee754.h>
long
__lrintl (long double x)
{
double xh, xl;
long res, hi, lo;
int save_round;
ldbl_unpack (x, &xh, &xl);
/* Limit the range of values handled by the conversion to long.
We do this because we aren't sure whether that conversion properly
raises FE_INVALID. */
if (
#if __LONG_MAX__ == 2147483647
__builtin_expect
((__builtin_fabs (xh) <= (double) __LONG_MAX__ + 2), 1)
#else
__builtin_expect
((__builtin_fabs (xh) <= -(double) (-__LONG_MAX__ - 1)), 1)
#endif
#if !defined (FE_INVALID)
|| 1
#endif
)
{
save_round = fegetround ();
#if __LONG_MAX__ == 2147483647
long long llhi = (long long) xh;
if (llhi != (long) llhi)
hi = llhi < 0 ? -__LONG_MAX__ - 1 : __LONG_MAX__;
else
hi = llhi;
xh -= hi;
#else
if (__glibc_unlikely ((xh == -(double) (-__LONG_MAX__ - 1))))
{
/* When XH is 9223372036854775808.0, converting to long long will
overflow, resulting in an invalid operation. However, XL might
be negative and of sufficient magnitude that the overall long
double is in fact in range. Avoid raising an exception. In any
case we need to convert this value specially, because
the converted value is not exactly represented as a double
thus subtracting HI from XH suffers rounding error. */
hi = __LONG_MAX__;
xh = 1.0;
}
else
{
hi = (long) xh;
xh -= hi;
}
#endif
ldbl_canonicalize (&xh, &xl);
lo = (long) xh;
/* Peg at max/min values, assuming that the above conversions do so.
Strictly speaking, we can return anything for values that overflow,
but this is more useful. */
res = hi + lo;
/* This is just sign(hi) == sign(lo) && sign(res) != sign(hi). */
if (__glibc_unlikely (((~(hi ^ lo) & (res ^ hi)) < 0)))
goto overflow;
xh -= lo;
ldbl_canonicalize (&xh, &xl);
hi = res;
switch (save_round)
{
case FE_TONEAREST:
if (fabs (xh) < 0.5
|| (fabs (xh) == 0.5
&& ((xh > 0.0 && xl < 0.0)
|| (xh < 0.0 && xl > 0.0)
|| (xl == 0.0 && (res & 1) == 0))))
return res;
if (xh < 0.0)
res -= 1;
else
res += 1;
break;
case FE_TOWARDZERO:
if (res > 0 && (xh < 0.0 || (xh == 0.0 && xl < 0.0)))
res -= 1;
else if (res < 0 && (xh > 0.0 || (xh == 0.0 && xl > 0.0)))
res += 1;
return res;
break;
case FE_UPWARD:
if (xh > 0.0 || (xh == 0.0 && xl > 0.0))
res += 1;
break;
case FE_DOWNWARD:
if (xh < 0.0 || (xh == 0.0 && xl < 0.0))
res -= 1;
break;
}
if (__glibc_unlikely (((~(hi ^ (res - hi)) & (res ^ hi)) < 0)))
goto overflow;
return res;
}
else
{
if (xh > 0.0)
hi = __LONG_MAX__;
else if (xh < 0.0)
hi = -__LONG_MAX__ - 1;
else
/* Nan */
hi = 0;
}
overflow:
#ifdef FE_INVALID
feraiseexcept (FE_INVALID);
#endif
return hi;
}
long_double_symbol (libm, __lrintl, lrintl);
|
615621.c |
//Copyright 2021 Stratify Labs, See LICENSE.md for details
#include <sos/events.h>
#include <sos/debug.h>
#include <sos/led.h>
#include <cortexm/cortexm.h>
#include "os_config.h"
void os_event_handler(int event, void *args) {
switch (event) {
case SOS_EVENT_ROOT_FATAL:
// start the bootloader on a fatal event
// mcu_core_invokebootloader(0, 0);
if (args != 0) {
sos_debug_printf("Fatal Error %s\n", (const char *)args);
} else {
sos_debug_printf("Fatal Error unknown\n");
}
cortexm_reset(NULL);
break;
case SOS_EVENT_START_LINK:
sos_led_startup();
break;
}
}
|
Subsets and Splits