blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
721
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 5
91
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 321
values | visit_date
timestamp[ns]date 2016-08-12 09:31:09
2023-09-06 10:45:07
| revision_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| github_id
int64 426
681M
| star_events_count
int64 101
243k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[ns]date 2012-06-28 18:51:49
2023-09-14 21:59:16
⌀ | gha_created_at
timestamp[ns]date 2008-02-11 22:55:26
2023-08-10 11:14:58
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 26
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 6
10.2M
| extension
stringclasses 115
values | filename
stringlengths 3
113
| content
stringlengths 6
10.2M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aedf39280c06271c3c1c08fed4a580a5fd16f99d
|
02f7ffd2c3537fe4f8ad2ff8511e8281d42f3237
|
/junixsocket-native/src/main/c/exceptions.h
|
33e679c5fb6a913242bd429043791946e299c516
|
[
"Apache-2.0"
] |
permissive
|
kohlschutter/junixsocket
|
64f07c7930c444bd55a98fb417fe9b5ee08fdb5e
|
c2197af9c42b136b77d655c7c2a4cfb4dd38f33e
|
refs/heads/main
| 2023-08-31T07:22:01.028849
| 2023-08-28T10:36:33
| 2023-08-28T10:36:33
| 27,064,201
| 426
| 119
|
Apache-2.0
| 2023-06-04T11:56:03
| 2014-11-24T06:41:49
|
Java
|
UTF-8
|
C
| false
| false
| 1,599
|
h
|
exceptions.h
|
/*
* junixsocket
*
* Copyright 2009-2021 Christian Kohlschütter
*
* 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.
*/
#ifndef exceptions_h
#define exceptions_h
#include "config.h"
typedef enum {
kExceptionSocketException = 0,
kExceptionSocketTimeoutException,
kExceptionIndexOutOfBoundsException,
kExceptionIllegalStateException,
kExceptionNullPointerException,
kExceptionNoRouteToHostException,
kExceptionClosedChannelException,
kExceptionInvalidArgumentSocketException,
kExceptionAddressUnavailableSocketException,
kExceptionOperationNotSupportedSocketException,
kExceptionNoSuchDeviceSocketException,
kExceptionMaxExcl
} ExceptionType;
void init_exceptions(JNIEnv *env);
void destroy_exceptions(JNIEnv *env);
CK_IGNORE_RESERVED_IDENTIFIER_BEGIN
void _throwException(JNIEnv* env, ExceptionType exceptionType, char* message);
void _throwErrnumException(JNIEnv* env, int errnum, jobject fdToClose);
void _throwSockoptErrnumException(JNIEnv* env, int errnum, jobject fd);
CK_IGNORE_RESERVED_IDENTIFIER_END
#endif /* exceptions_h */
|
0b2aa6e5a631cd432669725f894ebb81f8bdfba4
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/ffmpeg/libavcodec/mpeg4_unpack_bframes_bsf.c
|
3a3aad795f4f0e21dbd6ca29dfb64d254aaff79f
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"IJG",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 5,613
|
c
|
mpeg4_unpack_bframes_bsf.c
|
/*
* Bitstream filter for unpacking DivX-style packed B-frames in MPEG-4 (divx_packed)
* Copyright (c) 2015 Andreas Cadhalpun <Andreas.Cadhalpun@googlemail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "bsf.h"
#include "bsf_internal.h"
#include "mpeg4videodefs.h"
#include "startcode.h"
typedef struct UnpackBFramesBSFContext {
AVBufferRef *b_frame_ref;
} UnpackBFramesBSFContext;
/* determine the position of the packed marker in the userdata,
* the number of VOPs and the position of the second VOP */
static void scan_buffer(const uint8_t *buf, int buf_size,
int *pos_p, int *nb_vop, int *pos_vop2) {
uint32_t startcode;
const uint8_t *end = buf + buf_size, *pos = buf;
while (pos < end) {
startcode = -1;
pos = avpriv_find_start_code(pos, end, &startcode);
if (startcode == USER_DATA_STARTCODE && pos_p) {
/* check if the (DivX) userdata string ends with 'p' (packed) */
for (int i = 0; i < 255 && pos + i + 1 < end; i++) {
if (pos[i] == 'p' && pos[i + 1] == '\0') {
*pos_p = pos + i - buf;
break;
}
}
} else if (startcode == VOP_STARTCODE && nb_vop) {
*nb_vop += 1;
if (*nb_vop == 2 && pos_vop2) {
*pos_vop2 = pos - buf - 4; /* subtract 4 bytes startcode */
}
}
}
}
static int mpeg4_unpack_bframes_filter(AVBSFContext *ctx, AVPacket *pkt)
{
UnpackBFramesBSFContext *s = ctx->priv_data;
int pos_p = -1, nb_vop = 0, pos_vop2 = -1, ret = 0;
ret = ff_bsf_get_packet_ref(ctx, pkt);
if (ret < 0)
return ret;
scan_buffer(pkt->data, pkt->size, &pos_p, &nb_vop, &pos_vop2);
av_log(ctx, AV_LOG_DEBUG, "Found %d VOP startcode(s) in this packet.\n", nb_vop);
if (pos_vop2 >= 0) {
if (s->b_frame_ref) {
av_log(ctx, AV_LOG_WARNING,
"Missing one N-VOP packet, discarding one B-frame.\n");
av_buffer_unref(&s->b_frame_ref);
}
/* store a reference to the packed B-frame's data in the BSFContext */
s->b_frame_ref = av_buffer_ref(pkt->buf);
if (!s->b_frame_ref) {
ret = AVERROR(ENOMEM);
goto fail;
}
s->b_frame_ref->data = pkt->data + pos_vop2;
s->b_frame_ref->size = pkt->size - pos_vop2;
}
if (nb_vop > 2) {
av_log(ctx, AV_LOG_WARNING,
"Found %d VOP headers in one packet, only unpacking one.\n", nb_vop);
}
if (nb_vop == 1 && s->b_frame_ref) {
AVBufferRef *tmp = pkt->buf;
/* make tmp accurately reflect the packet's data */
tmp->data = pkt->data;
tmp->size = pkt->size;
/* replace data in packet with stored data */
pkt->buf = s->b_frame_ref;
pkt->data = s->b_frame_ref->data;
pkt->size = s->b_frame_ref->size;
/* store reference to data into BSFContext */
s->b_frame_ref = tmp;
if (s->b_frame_ref->size <= MAX_NVOP_SIZE) {
/* N-VOP - discard stored data */
av_log(ctx, AV_LOG_DEBUG, "Skipping N-VOP.\n");
av_buffer_unref(&s->b_frame_ref);
}
} else if (nb_vop >= 2) {
/* use first frame of the packet */
pkt->size = pos_vop2;
} else if (pos_p >= 0) {
ret = av_packet_make_writable(pkt);
if (ret < 0)
goto fail;
av_log(ctx, AV_LOG_DEBUG, "Updating DivX userdata (remove trailing 'p').\n");
/* remove 'p' (packed) from the end of the (DivX) userdata string */
pkt->data[pos_p] = '\0';
} else {
/* use packet as is */
}
fail:
if (ret < 0)
av_packet_unref(pkt);
return ret;
}
static int mpeg4_unpack_bframes_init(AVBSFContext *ctx)
{
if (ctx->par_in->extradata) {
int pos_p_ext = -1;
scan_buffer(ctx->par_in->extradata, ctx->par_in->extradata_size, &pos_p_ext, NULL, NULL);
if (pos_p_ext >= 0) {
av_log(ctx, AV_LOG_DEBUG,
"Updating DivX userdata (remove trailing 'p') in extradata.\n");
ctx->par_out->extradata[pos_p_ext] = '\0';
}
}
return 0;
}
static void mpeg4_unpack_bframes_close_flush(AVBSFContext *bsfc)
{
UnpackBFramesBSFContext *ctx = bsfc->priv_data;
av_buffer_unref(&ctx->b_frame_ref);
}
static const enum AVCodecID codec_ids[] = {
AV_CODEC_ID_MPEG4, AV_CODEC_ID_NONE,
};
const FFBitStreamFilter ff_mpeg4_unpack_bframes_bsf = {
.p.name = "mpeg4_unpack_bframes",
.p.codec_ids = codec_ids,
.priv_data_size = sizeof(UnpackBFramesBSFContext),
.init = mpeg4_unpack_bframes_init,
.filter = mpeg4_unpack_bframes_filter,
.flush = mpeg4_unpack_bframes_close_flush,
.close = mpeg4_unpack_bframes_close_flush,
};
|
f9be3649d5bb64254db37a927a59fc6cabe13bd1
|
676acab8ff535019faff7da3afb8eecc3fa127f5
|
/target/coolfly/chuanyun_f2s/libraries/artosyn/ar1002_lib/Driver/HAL/Src/hal_timer.c
|
dbfda6cc102e5a3fc9d38c8d3d9b4d9428114ecd
|
[
"Apache-2.0"
] |
permissive
|
Firmament-Autopilot/FMT-Firmware
|
f8c324577245bd7e91af436954b4ce9421acbb41
|
0212fe89820376bfbedaded519552f6b011a7b8a
|
refs/heads/master
| 2023-09-01T11:37:46.194145
| 2023-08-29T06:33:10
| 2023-08-29T06:33:10
| 402,557,689
| 351
| 143
|
Apache-2.0
| 2023-09-12T05:28:39
| 2021-09-02T20:42:56
|
C
|
UTF-8
|
C
| false
| false
| 5,065
|
c
|
hal_timer.c
|
/*****************************************************************************
Copyright: 2016-2020, Artosyn. Co., Ltd.
File name: hal_timer.c
Description: this module contains the helper fucntions necessary to control the general
purpose timer block
Author: Artosy Software Team
Version: 0.0.1
Date: 2016/12/19
History:
0.0.1 2016/12/19 The initial version of hal_timer.c
*****************************************************************************/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "interrupt.h"
#include "hal_ret_type.h"
#include "timer.h"
#include "hal_timer.h"
#include "debuglog.h"
#include "driver_mutex.h"
#include "driver_module_init.h"
void TIMER_ClearNvic(uint32_t e_vectorNum);
/**
* @brief register timer
* @param e_timerNum: timer number, the right number should be 0-23.
u32_timeus: timer load count
*fun_callBack: interrput callback
* @retval HAL_OK means the registeration tiemr is well done.
* HAL_TIMER_ERR_UNKNOWN means the timer number error.
* @note none
*/
HAL_RET_T HAL_TIMER_RegisterTimer(ENUM_HAL_TIMER_NUM e_timerNum, uint32_t u32_timeus, void *fun_callBack)
{
if (e_timerNum > HAL_TIMER_NUM23)
{
return HAL_TIMER_ERR_UNKNOWN;
}
if ( -1 == COMMON_driverMutexGet(MUTEX_TIMER, e_timerNum) )
{
DLOG_Error("fail, channel = %d", e_timerNum);
return HAL_OCCUPIED;
}
COMMON_driverMutexSet(MUTEX_TIMER, (uint32_t)e_timerNum);
COMMON_driverInitSet(INITED_TIMER, (uint32_t)e_timerNum);
init_timer_st st_timer;
memset(&st_timer,0,sizeof(init_timer_st));
st_timer.base_time_group = e_timerNum/8;
st_timer.time_num = e_timerNum%8;
st_timer.ctrl |= TIME_ENABLE | USER_DEFINED;
TIM_RegisterTimer(st_timer,u32_timeus);
reg_IrqHandle(TIMER_INTR00_VECTOR_NUM + e_timerNum, fun_callBack, TIMER_ClearNvic);
NVIC_SetPriority(TIMER_INTR00_VECTOR_NUM + e_timerNum, NVIC_EncodePriority(NVIC_PRIORITYGROUP_5,INTR_NVIC_PRIORITY_TIMER_DEFAULT,0));
NVIC_EnableIRQ(TIMER_INTR00_VECTOR_NUM + e_timerNum);
TIM_StartTimer(st_timer);
return HAL_OK;
}
/**
* @brief stop timer
* @param e_timerNum: timer number, the right number should be 0-23.
* @retval HAL_OK means the stop tiemr success.
* HAL_TIMER_ERR_UNKNOWN means the timer number error.
* @note none
*/
HAL_RET_T HAL_TIMER_Stop(ENUM_HAL_TIMER_NUM e_timerNum)
{
if (e_timerNum > HAL_TIMER_NUM23)
{
return HAL_TIMER_ERR_UNKNOWN;
}
if ( -1 == COMMON_driverInitGet(INITED_TIMER, e_timerNum) )
{
DLOG_Error("fail, timer = %d", e_timerNum);
return HAL_NOT_INITED;
}
init_timer_st st_timer;
memset(&st_timer,0,sizeof(init_timer_st));
st_timer.base_time_group = e_timerNum/8;
st_timer.time_num = e_timerNum%8;
st_timer.ctrl |= TIME_ENABLE | USER_DEFINED;
NVIC_DisableIRQ(TIMER_INTR00_VECTOR_NUM + e_timerNum);
NVIC_ClearPendingIRQ(TIMER_INTR00_VECTOR_NUM + e_timerNum);
TIM_StopTimer(st_timer);
return HAL_OK;
}
/**
* @brief start timer
* @param e_timerNum: timer number, the right number should be 0-23.
* @retval HAL_OK means the start tiemr success.
* HAL_TIMER_ERR_UNKNOWN means the timer number error.
* @note none
*/
HAL_RET_T HAL_TIMER_Start(ENUM_HAL_TIMER_NUM e_timerNum)
{
if (e_timerNum > HAL_TIMER_NUM23)
{
return HAL_TIMER_ERR_UNKNOWN;
}
if ( -1 == COMMON_driverInitGet(INITED_TIMER, e_timerNum) )
{
DLOG_Error("fail, timer = %d", e_timerNum);
return HAL_NOT_INITED;
}
init_timer_st st_timer;
memset(&st_timer,0,sizeof(init_timer_st));
st_timer.base_time_group = e_timerNum/8;
st_timer.time_num = e_timerNum%8;
st_timer.ctrl |= TIME_ENABLE | USER_DEFINED;
NVIC_SetPriority(TIMER_INTR00_VECTOR_NUM + e_timerNum, NVIC_EncodePriority(NVIC_PRIORITYGROUP_5,INTR_NVIC_PRIORITY_TIMER_DEFAULT,0));
NVIC_EnableIRQ(TIMER_INTR00_VECTOR_NUM + e_timerNum);
TIM_StartTimer(st_timer);
return HAL_OK;
}
/**
* @brief clear timer interrupt
* @param e_timerNum: timer number, the right number should be 0-23.
* @retval HAL_OK means the clear tiemr interrupt success.
* HAL_TIMER_ERR_UNKNOWN means the timer number error.
* @note none
*/
void TIMER_ClearNvic(uint32_t e_vectorNum)
{
if ((e_vectorNum > TIMER_INTR27_VECTOR_NUM) || (e_vectorNum < TIMER_INTR00_VECTOR_NUM) )
{
return ;
}
uint8_t u8_timerNum = e_vectorNum - TIMER_INTR00_VECTOR_NUM;
init_timer_st st_timer;
memset(&st_timer,0,sizeof(init_timer_st));
st_timer.base_time_group = u8_timerNum/8;
st_timer.time_num = u8_timerNum%8;
st_timer.ctrl |= TIME_ENABLE | USER_DEFINED;
TIM_ClearNvic(st_timer);
}
|
cfccef5950b5d1f61a30532de055ebc377e7fc87
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/src/ksp/pc/impls/fieldsplit/fieldsplit.c
|
713ae1940e1669dc527380aa6a802801f27a4285
|
[
"BSD-2-Clause"
] |
permissive
|
petsc/petsc
|
3b1a04fea71858e0292f9fd4d04ea11618c50969
|
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
|
refs/heads/main
| 2023-08-17T20:51:16.507070
| 2023-08-17T16:08:06
| 2023-08-17T16:08:06
| 8,691,401
| 341
| 169
|
NOASSERTION
| 2023-03-29T11:02:58
| 2013-03-10T20:55:21
|
C
|
UTF-8
|
C
| false
| false
| 154,678
|
c
|
fieldsplit.c
|
#include <petsc/private/pcimpl.h> /*I "petscpc.h" I*/
#include <petsc/private/kspimpl.h> /* This is needed to provide the appropriate PETSC_EXTERN for KSP_Solve_FS ....*/
#include <petscdm.h>
const char *const PCFieldSplitSchurPreTypes[] = {"SELF", "SELFP", "A11", "USER", "FULL", "PCFieldSplitSchurPreType", "PC_FIELDSPLIT_SCHUR_PRE_", NULL};
const char *const PCFieldSplitSchurFactTypes[] = {"DIAG", "LOWER", "UPPER", "FULL", "PCFieldSplitSchurFactType", "PC_FIELDSPLIT_SCHUR_FACT_", NULL};
PetscLogEvent KSP_Solve_FS_0, KSP_Solve_FS_1, KSP_Solve_FS_S, KSP_Solve_FS_U, KSP_Solve_FS_L, KSP_Solve_FS_2, KSP_Solve_FS_3, KSP_Solve_FS_4;
typedef struct _PC_FieldSplitLink *PC_FieldSplitLink;
struct _PC_FieldSplitLink {
KSP ksp;
Vec x, y, z;
char *splitname;
PetscInt nfields;
PetscInt *fields, *fields_col;
VecScatter sctx;
IS is, is_col;
PC_FieldSplitLink next, previous;
PetscLogEvent event;
/* Used only when setting coordinates with PCSetCoordinates */
PetscInt dim;
PetscInt ndofs;
PetscReal *coords;
};
typedef struct {
PCCompositeType type;
PetscBool defaultsplit; /* Flag for a system with a set of 'k' scalar fields with the same layout (and bs = k) */
PetscBool splitdefined; /* Flag is set after the splits have been defined, to prevent more splits from being added */
PetscInt bs; /* Block size for IS and Mat structures */
PetscInt nsplits; /* Number of field divisions defined */
Vec *x, *y, w1, w2;
Mat *mat; /* The diagonal block for each split */
Mat *pmat; /* The preconditioning diagonal block for each split */
Mat *Afield; /* The rows of the matrix associated with each split */
PetscBool issetup;
/* Only used when Schur complement preconditioning is used */
Mat B; /* The (0,1) block */
Mat C; /* The (1,0) block */
Mat schur; /* The Schur complement S = A11 - A10 A00^{-1} A01, the KSP here, kspinner, is H_1 in [El08] */
Mat schurp; /* Assembled approximation to S built by MatSchurComplement to be used as a preconditioning matrix when solving with S */
Mat schur_user; /* User-provided preconditioning matrix for the Schur complement */
PCFieldSplitSchurPreType schurpre; /* Determines which preconditioning matrix is used for the Schur complement */
PCFieldSplitSchurFactType schurfactorization;
KSP kspschur; /* The solver for S */
KSP kspupper; /* The solver for A in the upper diagonal part of the factorization (H_2 in [El08]) */
PetscScalar schurscale; /* Scaling factor for the Schur complement solution with DIAG factorization */
/* Only used when Golub-Kahan bidiagonalization preconditioning is used */
Mat H; /* The modified matrix H = A00 + nu*A01*A01' */
PetscReal gkbtol; /* Stopping tolerance for lower bound estimate */
PetscInt gkbdelay; /* The delay window for the stopping criterion */
PetscReal gkbnu; /* Parameter for augmented Lagrangian H = A + nu*A01*A01' */
PetscInt gkbmaxit; /* Maximum number of iterations for outer loop */
PetscBool gkbmonitor; /* Monitor for gkb iterations and the lower bound error */
PetscViewer gkbviewer; /* Viewer context for gkbmonitor */
Vec u, v, d, Hu; /* Work vectors for the GKB algorithm */
PetscScalar *vecz; /* Contains intermediate values, eg for lower bound */
PC_FieldSplitLink head;
PetscBool isrestrict; /* indicates PCFieldSplitRestrictIS() has been last called on this object, hack */
PetscBool suboptionsset; /* Indicates that the KSPSetFromOptions() has been called on the sub-KSPs */
PetscBool dm_splits; /* Whether to use DMCreateFieldDecomposition() whenever possible */
PetscBool diag_use_amat; /* Whether to extract diagonal matrix blocks from Amat, rather than Pmat (weaker than -pc_use_amat) */
PetscBool offdiag_use_amat; /* Whether to extract off-diagonal matrix blocks from Amat, rather than Pmat (weaker than -pc_use_amat) */
PetscBool detect; /* Whether to form 2-way split by finding zero diagonal entries */
PetscBool coordinates_set; /* Whether PCSetCoordinates has been called */
} PC_FieldSplit;
/*
Note:
there is no particular reason that pmat, x, and y are stored as arrays in PC_FieldSplit instead of
inside PC_FieldSplitLink, just historical. If you want to be able to add new fields after already using the
PC you could change this.
*/
/* This helper is so that setting a user-provided preconditioning matrix is orthogonal to choosing to use it. This way the
* application-provided FormJacobian can provide this matrix without interfering with the user's (command-line) choices. */
static Mat FieldSplitSchurPre(PC_FieldSplit *jac)
{
switch (jac->schurpre) {
case PC_FIELDSPLIT_SCHUR_PRE_SELF:
return jac->schur;
case PC_FIELDSPLIT_SCHUR_PRE_SELFP:
return jac->schurp;
case PC_FIELDSPLIT_SCHUR_PRE_A11:
return jac->pmat[1];
case PC_FIELDSPLIT_SCHUR_PRE_FULL: /* We calculate this and store it in schur_user */
case PC_FIELDSPLIT_SCHUR_PRE_USER: /* Use a user-provided matrix if it is given, otherwise diagonal block */
default:
return jac->schur_user ? jac->schur_user : jac->pmat[1];
}
}
#include <petscdraw.h>
static PetscErrorCode PCView_FieldSplit(PC pc, PetscViewer viewer)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool iascii, isdraw;
PetscInt i, j;
PC_FieldSplitLink ilink = jac->head;
PetscFunctionBegin;
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
if (iascii) {
if (jac->bs > 0) {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with %s composition: total splits = %" PetscInt_FMT ", blocksize = %" PetscInt_FMT "\n", PCCompositeTypes[jac->type], jac->nsplits, jac->bs));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with %s composition: total splits = %" PetscInt_FMT "\n", PCCompositeTypes[jac->type], jac->nsplits));
}
if (pc->useAmat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for blocks\n"));
if (jac->diag_use_amat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for diagonal blocks\n"));
if (jac->offdiag_use_amat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for off-diagonal blocks\n"));
PetscCall(PetscViewerASCIIPrintf(viewer, " Solver info for each split is in the following KSP objects:\n"));
for (i = 0; i < jac->nsplits; i++) {
if (ilink->fields) {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number %" PetscInt_FMT " Fields ", i));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
for (j = 0; j < ilink->nfields; j++) {
if (j > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ","));
PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, ilink->fields[j]));
}
PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number %" PetscInt_FMT " Defined by IS\n", i));
}
PetscCall(KSPView(ilink->ksp, viewer));
ilink = ilink->next;
}
}
if (isdraw) {
PetscDraw draw;
PetscReal x, y, w, wd;
PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
w = 2 * PetscMin(1.0 - x, x);
wd = w / (jac->nsplits + 1);
x = x - wd * (jac->nsplits - 1) / 2.0;
for (i = 0; i < jac->nsplits; i++) {
PetscCall(PetscDrawPushCurrentPoint(draw, x, y));
PetscCall(KSPView(ilink->ksp, viewer));
PetscCall(PetscDrawPopCurrentPoint(draw));
x += wd;
ilink = ilink->next;
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCView_FieldSplit_Schur(PC pc, PetscViewer viewer)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool iascii, isdraw;
PetscInt i, j;
PC_FieldSplitLink ilink = jac->head;
MatSchurComplementAinvType atype;
PetscFunctionBegin;
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
if (iascii) {
if (jac->bs > 0) {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with Schur preconditioner, blocksize = %" PetscInt_FMT ", factorization %s\n", jac->bs, PCFieldSplitSchurFactTypes[jac->schurfactorization]));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with Schur preconditioner, factorization %s\n", PCFieldSplitSchurFactTypes[jac->schurfactorization]));
}
if (pc->useAmat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for blocks\n"));
switch (jac->schurpre) {
case PC_FIELDSPLIT_SCHUR_PRE_SELF:
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from S itself\n"));
break;
case PC_FIELDSPLIT_SCHUR_PRE_SELFP:
if (jac->schur) {
PetscCall(MatSchurComplementGetAinvType(jac->schur, &atype));
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from Sp, an assembled approximation to S, which uses A00's %sinverse\n", atype == MAT_SCHUR_COMPLEMENT_AINV_DIAG ? "diagonal's " : (atype == MAT_SCHUR_COMPLEMENT_AINV_BLOCK_DIAG ? "block diagonal's " : (atype == MAT_SCHUR_COMPLEMENT_AINV_FULL ? "full " : "lumped diagonal's "))));
}
break;
case PC_FIELDSPLIT_SCHUR_PRE_A11:
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from A11\n"));
break;
case PC_FIELDSPLIT_SCHUR_PRE_FULL:
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from the exact Schur complement\n"));
break;
case PC_FIELDSPLIT_SCHUR_PRE_USER:
if (jac->schur_user) {
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from user provided matrix\n"));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioner for the Schur complement formed from A11\n"));
}
break;
default:
SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Invalid Schur preconditioning type: %d", jac->schurpre);
}
PetscCall(PetscViewerASCIIPrintf(viewer, " Split info:\n"));
PetscCall(PetscViewerASCIIPushTab(viewer));
for (i = 0; i < jac->nsplits; i++) {
if (ilink->fields) {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number %" PetscInt_FMT " Fields ", i));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
for (j = 0; j < ilink->nfields; j++) {
if (j > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ","));
PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, ilink->fields[j]));
}
PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number %" PetscInt_FMT " Defined by IS\n", i));
}
ilink = ilink->next;
}
PetscCall(PetscViewerASCIIPrintf(viewer, "KSP solver for A00 block\n"));
PetscCall(PetscViewerASCIIPushTab(viewer));
if (jac->head) {
PetscCall(KSPView(jac->head->ksp, viewer));
} else PetscCall(PetscViewerASCIIPrintf(viewer, " not yet available\n"));
PetscCall(PetscViewerASCIIPopTab(viewer));
if (jac->head && jac->kspupper != jac->head->ksp) {
PetscCall(PetscViewerASCIIPrintf(viewer, "KSP solver for upper A00 in upper triangular factor \n"));
PetscCall(PetscViewerASCIIPushTab(viewer));
if (jac->kspupper) PetscCall(KSPView(jac->kspupper, viewer));
else PetscCall(PetscViewerASCIIPrintf(viewer, " not yet available\n"));
PetscCall(PetscViewerASCIIPopTab(viewer));
}
PetscCall(PetscViewerASCIIPrintf(viewer, "KSP solver for S = A11 - A10 inv(A00) A01 \n"));
PetscCall(PetscViewerASCIIPushTab(viewer));
if (jac->kspschur) {
PetscCall(KSPView(jac->kspschur, viewer));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, " not yet available\n"));
}
PetscCall(PetscViewerASCIIPopTab(viewer));
PetscCall(PetscViewerASCIIPopTab(viewer));
} else if (isdraw && jac->head) {
PetscDraw draw;
PetscReal x, y, w, wd, h;
PetscInt cnt = 2;
char str[32];
PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
if (jac->kspupper != jac->head->ksp) cnt++;
w = 2 * PetscMin(1.0 - x, x);
wd = w / (cnt + 1);
PetscCall(PetscSNPrintf(str, 32, "Schur fact. %s", PCFieldSplitSchurFactTypes[jac->schurfactorization]));
PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_RED, PETSC_DRAW_BLACK, str, NULL, &h));
y -= h;
if (jac->schurpre == PC_FIELDSPLIT_SCHUR_PRE_USER && !jac->schur_user) {
PetscCall(PetscSNPrintf(str, 32, "Prec. for Schur from %s", PCFieldSplitSchurPreTypes[PC_FIELDSPLIT_SCHUR_PRE_A11]));
} else {
PetscCall(PetscSNPrintf(str, 32, "Prec. for Schur from %s", PCFieldSplitSchurPreTypes[jac->schurpre]));
}
PetscCall(PetscDrawStringBoxed(draw, x + wd * (cnt - 1) / 2.0, y, PETSC_DRAW_RED, PETSC_DRAW_BLACK, str, NULL, &h));
y -= h;
x = x - wd * (cnt - 1) / 2.0;
PetscCall(PetscDrawPushCurrentPoint(draw, x, y));
PetscCall(KSPView(jac->head->ksp, viewer));
PetscCall(PetscDrawPopCurrentPoint(draw));
if (jac->kspupper != jac->head->ksp) {
x += wd;
PetscCall(PetscDrawPushCurrentPoint(draw, x, y));
PetscCall(KSPView(jac->kspupper, viewer));
PetscCall(PetscDrawPopCurrentPoint(draw));
}
x += wd;
PetscCall(PetscDrawPushCurrentPoint(draw, x, y));
PetscCall(KSPView(jac->kspschur, viewer));
PetscCall(PetscDrawPopCurrentPoint(draw));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCView_FieldSplit_GKB(PC pc, PetscViewer viewer)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool iascii, isdraw;
PetscInt i, j;
PC_FieldSplitLink ilink = jac->head;
PetscFunctionBegin;
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
if (iascii) {
if (jac->bs > 0) {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with %s composition: total splits = %" PetscInt_FMT ", blocksize = %" PetscInt_FMT "\n", PCCompositeTypes[jac->type], jac->nsplits, jac->bs));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, " FieldSplit with %s composition: total splits = %" PetscInt_FMT "\n", PCCompositeTypes[jac->type], jac->nsplits));
}
if (pc->useAmat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for blocks\n"));
if (jac->diag_use_amat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for diagonal blocks\n"));
if (jac->offdiag_use_amat) PetscCall(PetscViewerASCIIPrintf(viewer, " using Amat (not Pmat) as operator for off-diagonal blocks\n"));
PetscCall(PetscViewerASCIIPrintf(viewer, " Stopping tolerance=%.1e, delay in error estimate=%" PetscInt_FMT ", maximum iterations=%" PetscInt_FMT "\n", (double)jac->gkbtol, jac->gkbdelay, jac->gkbmaxit));
PetscCall(PetscViewerASCIIPrintf(viewer, " Solver info for H = A00 + nu*A01*A01' matrix:\n"));
PetscCall(PetscViewerASCIIPushTab(viewer));
if (ilink->fields) {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number 0 Fields "));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
for (j = 0; j < ilink->nfields; j++) {
if (j > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ","));
PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, ilink->fields[j]));
}
PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
} else {
PetscCall(PetscViewerASCIIPrintf(viewer, "Split number 0 Defined by IS\n"));
}
PetscCall(KSPView(ilink->ksp, viewer));
PetscCall(PetscViewerASCIIPopTab(viewer));
}
if (isdraw) {
PetscDraw draw;
PetscReal x, y, w, wd;
PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
w = 2 * PetscMin(1.0 - x, x);
wd = w / (jac->nsplits + 1);
x = x - wd * (jac->nsplits - 1) / 2.0;
for (i = 0; i < jac->nsplits; i++) {
PetscCall(PetscDrawPushCurrentPoint(draw, x, y));
PetscCall(KSPView(ilink->ksp, viewer));
PetscCall(PetscDrawPopCurrentPoint(draw));
x += wd;
ilink = ilink->next;
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/* Precondition: jac->bs is set to a meaningful value */
static PetscErrorCode PCFieldSplitSetRuntimeSplits_Private(PC pc)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscInt i, nfields, *ifields, nfields_col, *ifields_col;
PetscBool flg, flg_col;
char optionname[128], splitname[8], optionname_col[128];
PetscFunctionBegin;
PetscCall(PetscMalloc1(jac->bs, &ifields));
PetscCall(PetscMalloc1(jac->bs, &ifields_col));
for (i = 0, flg = PETSC_TRUE;; i++) {
PetscCall(PetscSNPrintf(splitname, sizeof(splitname), "%" PetscInt_FMT, i));
PetscCall(PetscSNPrintf(optionname, sizeof(optionname), "-pc_fieldsplit_%" PetscInt_FMT "_fields", i));
PetscCall(PetscSNPrintf(optionname_col, sizeof(optionname_col), "-pc_fieldsplit_%" PetscInt_FMT "_fields_col", i));
nfields = jac->bs;
nfields_col = jac->bs;
PetscCall(PetscOptionsGetIntArray(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, optionname, ifields, &nfields, &flg));
PetscCall(PetscOptionsGetIntArray(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, optionname_col, ifields_col, &nfields_col, &flg_col));
if (!flg) break;
else if (flg && !flg_col) {
PetscCheck(nfields, PETSC_COMM_SELF, PETSC_ERR_USER, "Cannot list zero fields");
PetscCall(PCFieldSplitSetFields(pc, splitname, nfields, ifields, ifields));
} else {
PetscCheck(nfields && nfields_col, PETSC_COMM_SELF, PETSC_ERR_USER, "Cannot list zero fields");
PetscCheck(nfields == nfields_col, PETSC_COMM_SELF, PETSC_ERR_USER, "Number of row and column fields must match");
PetscCall(PCFieldSplitSetFields(pc, splitname, nfields, ifields, ifields_col));
}
}
if (i > 0) {
/* Makes command-line setting of splits take precedence over setting them in code.
Otherwise subsequent calls to PCFieldSplitSetIS() or PCFieldSplitSetFields() would
create new splits, which would probably not be what the user wanted. */
jac->splitdefined = PETSC_TRUE;
}
PetscCall(PetscFree(ifields));
PetscCall(PetscFree(ifields_col));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetDefaults(PC pc)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head;
PetscBool fieldsplit_default = PETSC_FALSE, coupling = PETSC_FALSE;
PetscInt i;
PetscFunctionBegin;
/*
Kinda messy, but at least this now uses DMCreateFieldDecomposition().
Should probably be rewritten.
*/
if (!ilink) {
PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, "-pc_fieldsplit_detect_coupling", &coupling, NULL));
if (pc->dm && jac->dm_splits && !jac->detect && !coupling) {
PetscInt numFields, f, i, j;
char **fieldNames;
IS *fields;
DM *dms;
DM subdm[128];
PetscBool flg;
PetscCall(DMCreateFieldDecomposition(pc->dm, &numFields, &fieldNames, &fields, &dms));
/* Allow the user to prescribe the splits */
for (i = 0, flg = PETSC_TRUE;; i++) {
PetscInt ifields[128];
IS compField;
char optionname[128], splitname[8];
PetscInt nfields = numFields;
PetscCall(PetscSNPrintf(optionname, sizeof(optionname), "-pc_fieldsplit_%" PetscInt_FMT "_fields", i));
PetscCall(PetscOptionsGetIntArray(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, optionname, ifields, &nfields, &flg));
if (!flg) break;
PetscCheck(numFields <= 128, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot currently support %" PetscInt_FMT " > 128 fields", numFields);
PetscCall(DMCreateSubDM(pc->dm, nfields, ifields, &compField, &subdm[i]));
if (nfields == 1) {
PetscCall(PCFieldSplitSetIS(pc, fieldNames[ifields[0]], compField));
} else {
PetscCall(PetscSNPrintf(splitname, sizeof(splitname), "%" PetscInt_FMT, i));
PetscCall(PCFieldSplitSetIS(pc, splitname, compField));
}
PetscCall(ISDestroy(&compField));
for (j = 0; j < nfields; ++j) {
f = ifields[j];
PetscCall(PetscFree(fieldNames[f]));
PetscCall(ISDestroy(&fields[f]));
}
}
if (i == 0) {
for (f = 0; f < numFields; ++f) {
PetscCall(PCFieldSplitSetIS(pc, fieldNames[f], fields[f]));
PetscCall(PetscFree(fieldNames[f]));
PetscCall(ISDestroy(&fields[f]));
}
} else {
for (j = 0; j < numFields; j++) PetscCall(DMDestroy(dms + j));
PetscCall(PetscFree(dms));
PetscCall(PetscMalloc1(i, &dms));
for (j = 0; j < i; ++j) dms[j] = subdm[j];
}
PetscCall(PetscFree(fieldNames));
PetscCall(PetscFree(fields));
if (dms) {
PetscCall(PetscInfo(pc, "Setting up physics based fieldsplit preconditioner using the embedded DM\n"));
for (ilink = jac->head, i = 0; ilink; ilink = ilink->next, ++i) {
const char *prefix;
PetscCall(PetscObjectGetOptionsPrefix((PetscObject)(ilink->ksp), &prefix));
PetscCall(PetscObjectSetOptionsPrefix((PetscObject)(dms[i]), prefix));
PetscCall(KSPSetDM(ilink->ksp, dms[i]));
PetscCall(KSPSetDMActive(ilink->ksp, PETSC_FALSE));
{
PetscErrorCode (*func)(KSP, Mat, Mat, void *);
void *ctx;
PetscCall(DMKSPGetComputeOperators(pc->dm, &func, &ctx));
PetscCall(DMKSPSetComputeOperators(dms[i], func, ctx));
}
PetscCall(PetscObjectIncrementTabLevel((PetscObject)dms[i], (PetscObject)ilink->ksp, 0));
PetscCall(DMDestroy(&dms[i]));
}
PetscCall(PetscFree(dms));
}
} else {
if (jac->bs <= 0) {
if (pc->pmat) {
PetscCall(MatGetBlockSize(pc->pmat, &jac->bs));
} else jac->bs = 1;
}
if (jac->detect) {
IS zerodiags, rest;
PetscInt nmin, nmax;
PetscCall(MatGetOwnershipRange(pc->mat, &nmin, &nmax));
if (jac->diag_use_amat) {
PetscCall(MatFindZeroDiagonals(pc->mat, &zerodiags));
} else {
PetscCall(MatFindZeroDiagonals(pc->pmat, &zerodiags));
}
PetscCall(ISComplement(zerodiags, nmin, nmax, &rest));
PetscCall(PCFieldSplitSetIS(pc, "0", rest));
PetscCall(PCFieldSplitSetIS(pc, "1", zerodiags));
PetscCall(ISDestroy(&zerodiags));
PetscCall(ISDestroy(&rest));
} else if (coupling) {
IS coupling, rest;
PetscInt nmin, nmax;
PetscCall(MatGetOwnershipRange(pc->mat, &nmin, &nmax));
if (jac->offdiag_use_amat) {
PetscCall(MatFindOffBlockDiagonalEntries(pc->mat, &coupling));
} else {
PetscCall(MatFindOffBlockDiagonalEntries(pc->pmat, &coupling));
}
PetscCall(ISCreateStride(PetscObjectComm((PetscObject)pc->mat), nmax - nmin, nmin, 1, &rest));
PetscCall(ISSetIdentity(rest));
PetscCall(PCFieldSplitSetIS(pc, "0", rest));
PetscCall(PCFieldSplitSetIS(pc, "1", coupling));
PetscCall(ISDestroy(&coupling));
PetscCall(ISDestroy(&rest));
} else {
PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, "-pc_fieldsplit_default", &fieldsplit_default, NULL));
if (!fieldsplit_default) {
/* Allow user to set fields from command line, if bs was known at the time of PCSetFromOptions_FieldSplit()
then it is set there. This is not ideal because we should only have options set in XXSetFromOptions(). */
PetscCall(PCFieldSplitSetRuntimeSplits_Private(pc));
if (jac->splitdefined) PetscCall(PetscInfo(pc, "Splits defined using the options database\n"));
}
if ((fieldsplit_default || !jac->splitdefined) && !jac->isrestrict) {
Mat M = pc->pmat;
PetscBool isnest;
PetscCall(PetscInfo(pc, "Using default splitting of fields\n"));
PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATNEST, &isnest));
if (!isnest) {
M = pc->mat;
PetscCall(PetscObjectTypeCompare((PetscObject)pc->mat, MATNEST, &isnest));
}
if (isnest) {
IS *fields;
PetscInt nf;
PetscCall(MatNestGetSize(M, &nf, NULL));
PetscCall(PetscMalloc1(nf, &fields));
PetscCall(MatNestGetISs(M, fields, NULL));
for (i = 0; i < nf; i++) PetscCall(PCFieldSplitSetIS(pc, NULL, fields[i]));
PetscCall(PetscFree(fields));
} else {
for (i = 0; i < jac->bs; i++) {
char splitname[8];
PetscCall(PetscSNPrintf(splitname, sizeof(splitname), "%" PetscInt_FMT, i));
PetscCall(PCFieldSplitSetFields(pc, splitname, 1, &i, &i));
}
jac->defaultsplit = PETSC_TRUE;
}
}
}
}
} else if (jac->nsplits == 1) {
IS is2;
PetscInt nmin, nmax;
PetscCheck(ilink->is, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Must provide at least two sets of fields to PCFieldSplit()");
PetscCall(MatGetOwnershipRange(pc->mat, &nmin, &nmax));
PetscCall(ISComplement(ilink->is, nmin, nmax, &is2));
PetscCall(PCFieldSplitSetIS(pc, "1", is2));
PetscCall(ISDestroy(&is2));
}
PetscCheck(jac->nsplits >= 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "Unhandled case, must have at least two fields, not %" PetscInt_FMT, jac->nsplits);
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode MatGolubKahanComputeExplicitOperator(Mat A, Mat B, Mat C, Mat *H, PetscReal gkbnu)
{
Mat BT, T;
PetscReal nrmT, nrmB;
PetscFunctionBegin;
PetscCall(MatHermitianTranspose(C, MAT_INITIAL_MATRIX, &T)); /* Test if augmented matrix is symmetric */
PetscCall(MatAXPY(T, -1.0, B, DIFFERENT_NONZERO_PATTERN));
PetscCall(MatNorm(T, NORM_1, &nrmT));
PetscCall(MatNorm(B, NORM_1, &nrmB));
PetscCheck(nrmB <= 0 || nrmT / nrmB < PETSC_SMALL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Matrix is not symmetric/hermitian, GKB is not applicable.");
/* Compute augmented Lagrangian matrix H = A00 + nu*A01*A01'. This corresponds to */
/* setting N := 1/nu*I in [Ar13]. */
PetscCall(MatHermitianTranspose(B, MAT_INITIAL_MATRIX, &BT));
PetscCall(MatMatMult(B, BT, MAT_INITIAL_MATRIX, PETSC_DEFAULT, H)); /* H = A01*A01' */
PetscCall(MatAYPX(*H, gkbnu, A, DIFFERENT_NONZERO_PATTERN)); /* H = A00 + nu*A01*A01' */
PetscCall(MatDestroy(&BT));
PetscCall(MatDestroy(&T));
PetscFunctionReturn(PETSC_SUCCESS);
}
PETSC_EXTERN PetscErrorCode PetscOptionsFindPairPrefix_Private(PetscOptions, const char pre[], const char name[], const char *value[], PetscBool *flg);
static PetscErrorCode PCSetUp_FieldSplit(PC pc)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink;
PetscInt i, nsplit;
PetscBool sorted, sorted_col;
PetscFunctionBegin;
pc->failedreason = PC_NOERROR;
PetscCall(PCFieldSplitSetDefaults(pc));
nsplit = jac->nsplits;
ilink = jac->head;
/* get the matrices for each split */
if (!jac->issetup) {
PetscInt rstart, rend, nslots, bs;
jac->issetup = PETSC_TRUE;
/* This is done here instead of in PCFieldSplitSetFields() because may not have matrix at that point */
if (jac->defaultsplit || !ilink->is) {
if (jac->bs <= 0) jac->bs = nsplit;
}
/* MatCreateSubMatrix() for [S]BAIJ matrices can only work if the indices include entire blocks of the matrix */
PetscCall(MatGetBlockSize(pc->pmat, &bs));
if (bs > 1 && (jac->bs <= bs || jac->bs % bs)) {
PetscBool blk;
PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &blk, MATBAIJ, MATSBAIJ, MATSEQBAIJ, MATSEQSBAIJ, MATMPIBAIJ, MATMPISBAIJ, NULL));
PetscCheck(!blk, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "Cannot use MATBAIJ with PCFIELDSPLIT and currently set matrix and PC blocksizes");
}
bs = jac->bs;
PetscCall(MatGetOwnershipRange(pc->pmat, &rstart, &rend));
nslots = (rend - rstart) / bs;
for (i = 0; i < nsplit; i++) {
if (jac->defaultsplit) {
PetscCall(ISCreateStride(PetscObjectComm((PetscObject)pc), nslots, rstart + i, nsplit, &ilink->is));
PetscCall(ISDuplicate(ilink->is, &ilink->is_col));
} else if (!ilink->is) {
if (ilink->nfields > 1) {
PetscInt *ii, *jj, j, k, nfields = ilink->nfields, *fields = ilink->fields, *fields_col = ilink->fields_col;
PetscCall(PetscMalloc1(ilink->nfields * nslots, &ii));
PetscCall(PetscMalloc1(ilink->nfields * nslots, &jj));
for (j = 0; j < nslots; j++) {
for (k = 0; k < nfields; k++) {
ii[nfields * j + k] = rstart + bs * j + fields[k];
jj[nfields * j + k] = rstart + bs * j + fields_col[k];
}
}
PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), nslots * nfields, ii, PETSC_OWN_POINTER, &ilink->is));
PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), nslots * nfields, jj, PETSC_OWN_POINTER, &ilink->is_col));
PetscCall(ISSetBlockSize(ilink->is, nfields));
PetscCall(ISSetBlockSize(ilink->is_col, nfields));
} else {
PetscCall(ISCreateStride(PetscObjectComm((PetscObject)pc), nslots, rstart + ilink->fields[0], bs, &ilink->is));
PetscCall(ISCreateStride(PetscObjectComm((PetscObject)pc), nslots, rstart + ilink->fields_col[0], bs, &ilink->is_col));
}
}
PetscCall(ISSorted(ilink->is, &sorted));
if (ilink->is_col) PetscCall(ISSorted(ilink->is_col, &sorted_col));
PetscCheck(sorted && sorted_col, PETSC_COMM_SELF, PETSC_ERR_USER, "Fields must be sorted when creating split");
ilink = ilink->next;
}
}
ilink = jac->head;
if (!jac->pmat) {
Vec xtmp;
PetscCall(MatCreateVecs(pc->pmat, &xtmp, NULL));
PetscCall(PetscMalloc1(nsplit, &jac->pmat));
PetscCall(PetscMalloc2(nsplit, &jac->x, nsplit, &jac->y));
for (i = 0; i < nsplit; i++) {
MatNullSpace sp;
/* Check for preconditioning matrix attached to IS */
PetscCall(PetscObjectQuery((PetscObject)ilink->is, "pmat", (PetscObject *)&jac->pmat[i]));
if (jac->pmat[i]) {
PetscCall(PetscObjectReference((PetscObject)jac->pmat[i]));
if (jac->type == PC_COMPOSITE_SCHUR) {
jac->schur_user = jac->pmat[i];
PetscCall(PetscObjectReference((PetscObject)jac->schur_user));
}
} else {
const char *prefix;
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ilink->is_col, MAT_INITIAL_MATRIX, &jac->pmat[i]));
PetscCall(KSPGetOptionsPrefix(ilink->ksp, &prefix));
PetscCall(MatSetOptionsPrefix(jac->pmat[i], prefix));
PetscCall(MatViewFromOptions(jac->pmat[i], NULL, "-mat_view"));
}
/* create work vectors for each split */
PetscCall(MatCreateVecs(jac->pmat[i], &jac->x[i], &jac->y[i]));
ilink->x = jac->x[i];
ilink->y = jac->y[i];
ilink->z = NULL;
/* compute scatter contexts needed by multiplicative versions and non-default splits */
PetscCall(VecScatterCreate(xtmp, ilink->is, jac->x[i], NULL, &ilink->sctx));
PetscCall(PetscObjectQuery((PetscObject)ilink->is, "nearnullspace", (PetscObject *)&sp));
if (sp) PetscCall(MatSetNearNullSpace(jac->pmat[i], sp));
ilink = ilink->next;
}
PetscCall(VecDestroy(&xtmp));
} else {
MatReuse scall;
if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
for (i = 0; i < nsplit; i++) PetscCall(MatDestroy(&jac->pmat[i]));
scall = MAT_INITIAL_MATRIX;
} else scall = MAT_REUSE_MATRIX;
for (i = 0; i < nsplit; i++) {
Mat pmat;
/* Check for preconditioning matrix attached to IS */
PetscCall(PetscObjectQuery((PetscObject)ilink->is, "pmat", (PetscObject *)&pmat));
if (!pmat) PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ilink->is_col, scall, &jac->pmat[i]));
ilink = ilink->next;
}
}
if (jac->diag_use_amat) {
ilink = jac->head;
if (!jac->mat) {
PetscCall(PetscMalloc1(nsplit, &jac->mat));
for (i = 0; i < nsplit; i++) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ilink->is_col, MAT_INITIAL_MATRIX, &jac->mat[i]));
ilink = ilink->next;
}
} else {
MatReuse scall;
if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
for (i = 0; i < nsplit; i++) PetscCall(MatDestroy(&jac->mat[i]));
scall = MAT_INITIAL_MATRIX;
} else scall = MAT_REUSE_MATRIX;
for (i = 0; i < nsplit; i++) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ilink->is_col, scall, &jac->mat[i]));
ilink = ilink->next;
}
}
} else {
jac->mat = jac->pmat;
}
/* Check for null space attached to IS */
ilink = jac->head;
for (i = 0; i < nsplit; i++) {
MatNullSpace sp;
PetscCall(PetscObjectQuery((PetscObject)ilink->is, "nullspace", (PetscObject *)&sp));
if (sp) PetscCall(MatSetNullSpace(jac->mat[i], sp));
ilink = ilink->next;
}
if (jac->type != PC_COMPOSITE_ADDITIVE && jac->type != PC_COMPOSITE_SCHUR && jac->type != PC_COMPOSITE_GKB) {
/* extract the rows of the matrix associated with each field: used for efficient computation of residual inside algorithm */
/* FIXME: Can/should we reuse jac->mat whenever (jac->diag_use_amat) is true? */
ilink = jac->head;
if (nsplit == 2 && jac->type == PC_COMPOSITE_MULTIPLICATIVE) {
/* special case need where Afield[0] is not needed and only certain columns of Afield[1] are needed since update is only on those rows of the solution */
if (!jac->Afield) {
PetscCall(PetscCalloc1(nsplit, &jac->Afield));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->next->is, ilink->is, MAT_INITIAL_MATRIX, &jac->Afield[1]));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->next->is, ilink->is, MAT_INITIAL_MATRIX, &jac->Afield[1]));
}
} else {
MatReuse scall;
if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
PetscCall(MatDestroy(&jac->Afield[1]));
scall = MAT_INITIAL_MATRIX;
} else scall = MAT_REUSE_MATRIX;
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->next->is, ilink->is, scall, &jac->Afield[1]));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->next->is, ilink->is, scall, &jac->Afield[1]));
}
}
} else {
if (!jac->Afield) {
PetscCall(PetscMalloc1(nsplit, &jac->Afield));
for (i = 0; i < nsplit; i++) {
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, NULL, MAT_INITIAL_MATRIX, &jac->Afield[i]));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, NULL, MAT_INITIAL_MATRIX, &jac->Afield[i]));
}
ilink = ilink->next;
}
} else {
MatReuse scall;
if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
for (i = 0; i < nsplit; i++) PetscCall(MatDestroy(&jac->Afield[i]));
scall = MAT_INITIAL_MATRIX;
} else scall = MAT_REUSE_MATRIX;
for (i = 0; i < nsplit; i++) {
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, NULL, scall, &jac->Afield[i]));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, NULL, scall, &jac->Afield[i]));
}
ilink = ilink->next;
}
}
}
}
if (jac->type == PC_COMPOSITE_SCHUR) {
IS ccis;
PetscBool isset, isspd;
PetscInt rstart, rend;
char lscname[256];
PetscObject LSC_L;
PetscCheck(nsplit == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "To use Schur complement preconditioner you must have exactly 2 fields");
/* If pc->mat is SPD, don't scale by -1 the Schur complement */
if (jac->schurscale == (PetscScalar)-1.0) {
PetscCall(MatIsSPDKnown(pc->pmat, &isset, &isspd));
jac->schurscale = (isset && isspd) ? 1.0 : -1.0;
}
/* When extracting off-diagonal submatrices, we take complements from this range */
PetscCall(MatGetOwnershipRangeColumn(pc->mat, &rstart, &rend));
if (jac->schur) {
KSP kspA = jac->head->ksp, kspInner = NULL, kspUpper = jac->kspupper;
MatReuse scall;
if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
scall = MAT_INITIAL_MATRIX;
PetscCall(MatDestroy(&jac->B));
PetscCall(MatDestroy(&jac->C));
} else scall = MAT_REUSE_MATRIX;
PetscCall(MatSchurComplementGetKSP(jac->schur, &kspInner));
ilink = jac->head;
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, scall, &jac->B));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, scall, &jac->B));
}
PetscCall(ISDestroy(&ccis));
ilink = ilink->next;
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, scall, &jac->C));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, scall, &jac->C));
}
PetscCall(ISDestroy(&ccis));
PetscCall(MatSchurComplementUpdateSubMatrices(jac->schur, jac->mat[0], jac->pmat[0], jac->B, jac->C, jac->mat[1]));
if (jac->schurpre == PC_FIELDSPLIT_SCHUR_PRE_SELFP) {
PetscCall(MatDestroy(&jac->schurp));
PetscCall(MatSchurComplementGetPmat(jac->schur, MAT_INITIAL_MATRIX, &jac->schurp));
}
if (kspA != kspInner) PetscCall(KSPSetOperators(kspA, jac->mat[0], jac->pmat[0]));
if (kspUpper != kspA) PetscCall(KSPSetOperators(kspUpper, jac->mat[0], jac->pmat[0]));
PetscCall(KSPSetOperators(jac->kspschur, jac->schur, FieldSplitSchurPre(jac)));
} else {
const char *Dprefix;
char schurprefix[256], schurmatprefix[256];
char schurtestoption[256];
MatNullSpace sp;
PetscBool flg;
KSP kspt;
/* extract the A01 and A10 matrices */
ilink = jac->head;
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->B));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->B));
}
PetscCall(ISDestroy(&ccis));
ilink = ilink->next;
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->C));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->C));
}
PetscCall(ISDestroy(&ccis));
/* Use mat[0] (diagonal block of Amat) preconditioned by pmat[0] to define Schur complement */
PetscCall(MatCreate(((PetscObject)jac->mat[0])->comm, &jac->schur));
PetscCall(MatSetType(jac->schur, MATSCHURCOMPLEMENT));
PetscCall(MatSchurComplementSetSubMatrices(jac->schur, jac->mat[0], jac->pmat[0], jac->B, jac->C, jac->mat[1]));
PetscCall(PetscSNPrintf(schurmatprefix, sizeof(schurmatprefix), "%sfieldsplit_%s_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ilink->splitname));
PetscCall(MatSetOptionsPrefix(jac->schur, schurmatprefix));
PetscCall(MatSchurComplementGetKSP(jac->schur, &kspt));
PetscCall(KSPSetOptionsPrefix(kspt, schurmatprefix));
/* Note: this is not true in general */
PetscCall(MatGetNullSpace(jac->mat[1], &sp));
if (sp) PetscCall(MatSetNullSpace(jac->schur, sp));
PetscCall(PetscSNPrintf(schurtestoption, sizeof(schurtestoption), "-fieldsplit_%s_inner_", ilink->splitname));
PetscCall(PetscOptionsFindPairPrefix_Private(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, schurtestoption, NULL, &flg));
if (flg) {
DM dmInner;
KSP kspInner;
PC pcInner;
PetscCall(MatSchurComplementGetKSP(jac->schur, &kspInner));
PetscCall(KSPReset(kspInner));
PetscCall(KSPSetOperators(kspInner, jac->mat[0], jac->pmat[0]));
PetscCall(PetscSNPrintf(schurprefix, sizeof(schurprefix), "%sfieldsplit_%s_inner_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ilink->splitname));
/* Indent this deeper to emphasize the "inner" nature of this solver. */
PetscCall(PetscObjectIncrementTabLevel((PetscObject)kspInner, (PetscObject)pc, 2));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)kspInner->pc, (PetscObject)pc, 2));
PetscCall(KSPSetOptionsPrefix(kspInner, schurprefix));
/* Set DM for new solver */
PetscCall(KSPGetDM(jac->head->ksp, &dmInner));
PetscCall(KSPSetDM(kspInner, dmInner));
PetscCall(KSPSetDMActive(kspInner, PETSC_FALSE));
/* Defaults to PCKSP as preconditioner */
PetscCall(KSPGetPC(kspInner, &pcInner));
PetscCall(PCSetType(pcInner, PCKSP));
PetscCall(PCKSPSetKSP(pcInner, jac->head->ksp));
} else {
/* Use the outer solver for the inner solve, but revert the KSPPREONLY from PCFieldSplitSetFields_FieldSplit or
* PCFieldSplitSetIS_FieldSplit. We don't want KSPPREONLY because it makes the Schur complement inexact,
* preventing Schur complement reduction to be an accurate solve. Usually when an iterative solver is used for
* S = D - C A_inner^{-1} B, we expect S to be defined using an accurate definition of A_inner^{-1}, so we make
* GMRES the default. Note that it is also common to use PREONLY for S, in which case S may not be used
* directly, and the user is responsible for setting an inexact method for fieldsplit's A^{-1}. */
PetscCall(KSPSetType(jac->head->ksp, KSPGMRES));
PetscCall(MatSchurComplementSetKSP(jac->schur, jac->head->ksp));
}
PetscCall(KSPSetOperators(jac->head->ksp, jac->mat[0], jac->pmat[0]));
PetscCall(KSPSetFromOptions(jac->head->ksp));
PetscCall(MatSetFromOptions(jac->schur));
PetscCall(PetscObjectTypeCompare((PetscObject)jac->schur, MATSCHURCOMPLEMENT, &flg));
if (flg) { /* Need to do this otherwise PCSetUp_KSP will overwrite the amat of jac->head->ksp */
KSP kspInner;
PC pcInner;
PetscCall(MatSchurComplementGetKSP(jac->schur, &kspInner));
PetscCall(KSPGetPC(kspInner, &pcInner));
PetscCall(PetscObjectTypeCompare((PetscObject)pcInner, PCKSP, &flg));
if (flg) {
KSP ksp;
PetscCall(PCKSPGetKSP(pcInner, &ksp));
if (ksp == jac->head->ksp) PetscCall(PCSetUseAmat(pcInner, PETSC_TRUE));
}
}
PetscCall(PetscSNPrintf(schurtestoption, sizeof(schurtestoption), "-fieldsplit_%s_upper_", ilink->splitname));
PetscCall(PetscOptionsFindPairPrefix_Private(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, schurtestoption, NULL, &flg));
if (flg) {
DM dmInner;
PetscCall(PetscSNPrintf(schurprefix, sizeof(schurprefix), "%sfieldsplit_%s_upper_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ilink->splitname));
PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &jac->kspupper));
PetscCall(KSPSetNestLevel(jac->kspupper, pc->kspnestlevel));
PetscCall(KSPSetErrorIfNotConverged(jac->kspupper, pc->erroriffailure));
PetscCall(KSPSetOptionsPrefix(jac->kspupper, schurprefix));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)jac->kspupper, (PetscObject)pc, 1));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)jac->kspupper->pc, (PetscObject)pc, 1));
PetscCall(KSPGetDM(jac->head->ksp, &dmInner));
PetscCall(KSPSetDM(jac->kspupper, dmInner));
PetscCall(KSPSetDMActive(jac->kspupper, PETSC_FALSE));
PetscCall(KSPSetFromOptions(jac->kspupper));
PetscCall(KSPSetOperators(jac->kspupper, jac->mat[0], jac->pmat[0]));
PetscCall(VecDuplicate(jac->head->x, &jac->head->z));
} else {
jac->kspupper = jac->head->ksp;
PetscCall(PetscObjectReference((PetscObject)jac->head->ksp));
}
if (jac->schurpre == PC_FIELDSPLIT_SCHUR_PRE_SELFP) PetscCall(MatSchurComplementGetPmat(jac->schur, MAT_INITIAL_MATRIX, &jac->schurp));
PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &jac->kspschur));
PetscCall(KSPSetNestLevel(jac->kspschur, pc->kspnestlevel));
PetscCall(KSPSetErrorIfNotConverged(jac->kspschur, pc->erroriffailure));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)jac->kspschur, (PetscObject)pc, 1));
if (jac->schurpre == PC_FIELDSPLIT_SCHUR_PRE_SELF) {
PC pcschur;
PetscCall(KSPGetPC(jac->kspschur, &pcschur));
PetscCall(PCSetType(pcschur, PCNONE));
/* Note: This is bad if there exist preconditioners for MATSCHURCOMPLEMENT */
} else if (jac->schurpre == PC_FIELDSPLIT_SCHUR_PRE_FULL) {
PetscCall(MatSchurComplementComputeExplicitOperator(jac->schur, &jac->schur_user));
}
PetscCall(KSPSetOperators(jac->kspschur, jac->schur, FieldSplitSchurPre(jac)));
PetscCall(KSPGetOptionsPrefix(jac->head->next->ksp, &Dprefix));
PetscCall(KSPSetOptionsPrefix(jac->kspschur, Dprefix));
/* propagate DM */
{
DM sdm;
PetscCall(KSPGetDM(jac->head->next->ksp, &sdm));
if (sdm) {
PetscCall(KSPSetDM(jac->kspschur, sdm));
PetscCall(KSPSetDMActive(jac->kspschur, PETSC_FALSE));
}
}
/* really want setfromoptions called in PCSetFromOptions_FieldSplit(), but it is not ready yet */
/* need to call this every time, since the jac->kspschur is freshly created, otherwise its options never get set */
PetscCall(KSPSetFromOptions(jac->kspschur));
}
PetscCall(MatAssemblyBegin(jac->schur, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(jac->schur, MAT_FINAL_ASSEMBLY));
/* HACK: special support to forward L and Lp matrices that might be used by PCLSC */
PetscCall(PetscSNPrintf(lscname, sizeof(lscname), "%s_LSC_L", ilink->splitname));
PetscCall(PetscObjectQuery((PetscObject)pc->mat, lscname, (PetscObject *)&LSC_L));
if (!LSC_L) PetscCall(PetscObjectQuery((PetscObject)pc->pmat, lscname, (PetscObject *)&LSC_L));
if (LSC_L) PetscCall(PetscObjectCompose((PetscObject)jac->schur, "LSC_L", (PetscObject)LSC_L));
PetscCall(PetscSNPrintf(lscname, sizeof(lscname), "%s_LSC_Lp", ilink->splitname));
PetscCall(PetscObjectQuery((PetscObject)pc->pmat, lscname, (PetscObject *)&LSC_L));
if (!LSC_L) PetscCall(PetscObjectQuery((PetscObject)pc->mat, lscname, (PetscObject *)&LSC_L));
if (LSC_L) PetscCall(PetscObjectCompose((PetscObject)jac->schur, "LSC_Lp", (PetscObject)LSC_L));
} else if (jac->type == PC_COMPOSITE_GKB) {
IS ccis;
PetscInt rstart, rend;
PetscCheck(nsplit == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "To use GKB preconditioner you must have exactly 2 fields");
ilink = jac->head;
/* When extracting off-diagonal submatrices, we take complements from this range */
PetscCall(MatGetOwnershipRangeColumn(pc->mat, &rstart, &rend));
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->B));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->B));
}
PetscCall(ISDestroy(&ccis));
/* Create work vectors for GKB algorithm */
PetscCall(VecDuplicate(ilink->x, &jac->u));
PetscCall(VecDuplicate(ilink->x, &jac->Hu));
PetscCall(VecDuplicate(ilink->x, &jac->w2));
ilink = ilink->next;
PetscCall(ISComplement(ilink->is_col, rstart, rend, &ccis));
if (jac->offdiag_use_amat) {
PetscCall(MatCreateSubMatrix(pc->mat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->C));
} else {
PetscCall(MatCreateSubMatrix(pc->pmat, ilink->is, ccis, MAT_INITIAL_MATRIX, &jac->C));
}
PetscCall(ISDestroy(&ccis));
/* Create work vectors for GKB algorithm */
PetscCall(VecDuplicate(ilink->x, &jac->v));
PetscCall(VecDuplicate(ilink->x, &jac->d));
PetscCall(VecDuplicate(ilink->x, &jac->w1));
PetscCall(MatGolubKahanComputeExplicitOperator(jac->mat[0], jac->B, jac->C, &jac->H, jac->gkbnu));
PetscCall(PetscCalloc1(jac->gkbdelay, &jac->vecz));
ilink = jac->head;
PetscCall(KSPSetOperators(ilink->ksp, jac->H, jac->H));
if (!jac->suboptionsset) PetscCall(KSPSetFromOptions(ilink->ksp));
/* Create gkb_monitor context */
if (jac->gkbmonitor) {
PetscInt tablevel;
PetscCall(PetscViewerCreate(PETSC_COMM_WORLD, &jac->gkbviewer));
PetscCall(PetscViewerSetType(jac->gkbviewer, PETSCVIEWERASCII));
PetscCall(PetscObjectGetTabLevel((PetscObject)ilink->ksp, &tablevel));
PetscCall(PetscViewerASCIISetTab(jac->gkbviewer, tablevel));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)ilink->ksp, (PetscObject)ilink->ksp, 1));
}
} else {
/* set up the individual splits' PCs */
i = 0;
ilink = jac->head;
while (ilink) {
PetscCall(KSPSetOperators(ilink->ksp, jac->mat[i], jac->pmat[i]));
/* really want setfromoptions called in PCSetFromOptions_FieldSplit(), but it is not ready yet */
if (!jac->suboptionsset) PetscCall(KSPSetFromOptions(ilink->ksp));
i++;
ilink = ilink->next;
}
}
/* Set coordinates to the sub PC objects whenever these are set */
if (jac->coordinates_set) {
PC pc_coords;
if (jac->type == PC_COMPOSITE_SCHUR) {
// Head is first block.
PetscCall(KSPGetPC(jac->head->ksp, &pc_coords));
PetscCall(PCSetCoordinates(pc_coords, jac->head->dim, jac->head->ndofs, jac->head->coords));
// Second one is Schur block, but its KSP object is in kspschur.
PetscCall(KSPGetPC(jac->kspschur, &pc_coords));
PetscCall(PCSetCoordinates(pc_coords, jac->head->next->dim, jac->head->next->ndofs, jac->head->next->coords));
} else if (jac->type == PC_COMPOSITE_GKB) {
PetscCall(PetscInfo(pc, "Warning: Setting coordinates does nothing for the GKB Fieldpslit preconditioner\n"));
} else {
ilink = jac->head;
while (ilink) {
PetscCall(KSPGetPC(ilink->ksp, &pc_coords));
PetscCall(PCSetCoordinates(pc_coords, ilink->dim, ilink->ndofs, ilink->coords));
ilink = ilink->next;
}
}
}
jac->suboptionsset = PETSC_TRUE;
PetscFunctionReturn(PETSC_SUCCESS);
}
#define FieldSplitSplitSolveAdd(ilink, xx, yy) \
((PetscErrorCode)(VecScatterBegin(ilink->sctx, xx, ilink->x, INSERT_VALUES, SCATTER_FORWARD) || VecScatterEnd(ilink->sctx, xx, ilink->x, INSERT_VALUES, SCATTER_FORWARD) || PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL) || \
KSPSolve(ilink->ksp, ilink->x, ilink->y) || KSPCheckSolve(ilink->ksp, pc, ilink->y) || PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL) || VecScatterBegin(ilink->sctx, ilink->y, yy, ADD_VALUES, SCATTER_REVERSE) || \
VecScatterEnd(ilink->sctx, ilink->y, yy, ADD_VALUES, SCATTER_REVERSE)))
static PetscErrorCode PCApply_FieldSplit_Schur(PC pc, Vec x, Vec y)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilinkA = jac->head, ilinkD = ilinkA->next;
KSP kspA = ilinkA->ksp, kspLower = kspA, kspUpper = jac->kspupper;
PetscFunctionBegin;
switch (jac->schurfactorization) {
case PC_FIELDSPLIT_SCHUR_FACT_DIAG:
/* [A00 0; 0 -S], positive definite, suitable for MINRES */
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolve(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScale(ilinkD->y, jac->schurscale));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_LOWER:
/* [A00 0; A10 S], suitable for left preconditioning */
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(MatMult(jac->C, ilinkA->y, ilinkD->x));
PetscCall(VecScale(ilinkD->x, -1.));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolve(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_UPPER:
/* [A00 A01; 0 S], suitable for right preconditioning */
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolve(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(MatMult(jac->B, ilinkD->y, ilinkA->x));
PetscCall(VecScale(ilinkA->x, -1.));
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_FULL:
/* [1 0; A10 A00^{-1} 1] [A00 0; 0 S] [1 A00^{-1}A01; 0 1] */
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_L, kspLower, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspLower, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspLower, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_L, kspLower, ilinkA->x, ilinkA->y, NULL));
PetscCall(MatMult(jac->C, ilinkA->y, ilinkD->x));
PetscCall(VecScale(ilinkD->x, -1.0));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolve(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
if (kspUpper == kspA) {
PetscCall(MatMult(jac->B, ilinkD->y, ilinkA->y));
PetscCall(VecAXPY(ilinkA->x, -1.0, ilinkA->y));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
} else {
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(MatMult(jac->B, ilinkD->y, ilinkA->x));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_U, kspUpper, ilinkA->x, ilinkA->z, NULL));
PetscCall(KSPSolve(kspUpper, ilinkA->x, ilinkA->z));
PetscCall(KSPCheckSolve(kspUpper, pc, ilinkA->z));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_U, kspUpper, ilinkA->x, ilinkA->z, NULL));
PetscCall(VecAXPY(ilinkA->y, -1.0, ilinkA->z));
}
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCApplyTranspose_FieldSplit_Schur(PC pc, Vec x, Vec y)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilinkA = jac->head, ilinkD = ilinkA->next;
KSP kspA = ilinkA->ksp, kspLower = kspA, kspUpper = jac->kspupper;
PetscFunctionBegin;
switch (jac->schurfactorization) {
case PC_FIELDSPLIT_SCHUR_FACT_DIAG:
/* [A00 0; 0 -S], positive definite, suitable for MINRES */
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolveTranspose(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScale(ilinkD->y, jac->schurscale));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_UPPER:
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(MatMultTranspose(jac->B, ilinkA->y, ilinkD->x));
PetscCall(VecScale(ilinkD->x, -1.));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolveTranspose(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_LOWER:
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolveTranspose(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(MatMultTranspose(jac->C, ilinkD->y, ilinkA->x));
PetscCall(VecScale(ilinkA->x, -1.));
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
break;
case PC_FIELDSPLIT_SCHUR_FACT_FULL:
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_U, kspUpper, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspUpper, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspUpper, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_U, kspUpper, ilinkA->x, ilinkA->y, NULL));
PetscCall(MatMultTranspose(jac->B, ilinkA->y, ilinkD->x));
PetscCall(VecScale(ilinkD->x, -1.0));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(KSPSolveTranspose(jac->kspschur, ilinkD->x, ilinkD->y));
PetscCall(KSPCheckSolve(jac->kspschur, pc, ilinkD->y));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_S, jac->kspschur, ilinkD->x, ilinkD->y, NULL));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
if (kspLower == kspA) {
PetscCall(MatMultTranspose(jac->C, ilinkD->y, ilinkA->y));
PetscCall(VecAXPY(ilinkA->x, -1.0, ilinkA->y));
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
} else {
PetscCall(PetscLogEventBegin(ilinkA->event, kspA, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolveTranspose(kspA, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(kspA, pc, ilinkA->y));
PetscCall(MatMultTranspose(jac->C, ilinkD->y, ilinkA->x));
PetscCall(PetscLogEventBegin(KSP_Solve_FS_L, kspLower, ilinkA->x, ilinkA->z, NULL));
PetscCall(KSPSolveTranspose(kspLower, ilinkA->x, ilinkA->z));
PetscCall(KSPCheckSolve(kspLower, pc, ilinkA->z));
PetscCall(PetscLogEventEnd(KSP_Solve_FS_L, kspLower, ilinkA->x, ilinkA->z, NULL));
PetscCall(VecAXPY(ilinkA->y, -1.0, ilinkA->z));
}
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCApply_FieldSplit(PC pc, Vec x, Vec y)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head;
PetscInt cnt, bs;
PetscFunctionBegin;
if (jac->type == PC_COMPOSITE_ADDITIVE) {
if (jac->defaultsplit) {
PetscCall(VecGetBlockSize(x, &bs));
PetscCheck(jac->bs <= 0 || bs == jac->bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Blocksize of x vector %" PetscInt_FMT " does not match fieldsplit blocksize %" PetscInt_FMT, bs, jac->bs);
PetscCall(VecGetBlockSize(y, &bs));
PetscCheck(jac->bs <= 0 || bs == jac->bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Blocksize of y vector %" PetscInt_FMT " does not match fieldsplit blocksize %" PetscInt_FMT, bs, jac->bs);
PetscCall(VecStrideGatherAll(x, jac->x, INSERT_VALUES));
while (ilink) {
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolve(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
ilink = ilink->next;
}
PetscCall(VecStrideScatterAll(jac->y, y, INSERT_VALUES));
} else {
PetscCall(VecSet(y, 0.0));
while (ilink) {
PetscCall(FieldSplitSplitSolveAdd(ilink, x, y));
ilink = ilink->next;
}
}
} else if (jac->type == PC_COMPOSITE_MULTIPLICATIVE && jac->nsplits == 2) {
PetscCall(VecSet(y, 0.0));
/* solve on first block for first block variables */
PetscCall(VecScatterBegin(ilink->sctx, x, ilink->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilink->sctx, x, ilink->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolve(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(VecScatterBegin(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
/* compute the residual only onto second block variables using first block variables */
PetscCall(MatMult(jac->Afield[1], ilink->y, ilink->next->x));
ilink = ilink->next;
PetscCall(VecScale(ilink->x, -1.0));
PetscCall(VecScatterBegin(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
/* solve on second block variables */
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolve(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(VecScatterBegin(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
} else if (jac->type == PC_COMPOSITE_MULTIPLICATIVE || jac->type == PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE) {
if (!jac->w1) {
PetscCall(VecDuplicate(x, &jac->w1));
PetscCall(VecDuplicate(x, &jac->w2));
}
PetscCall(VecSet(y, 0.0));
PetscCall(FieldSplitSplitSolveAdd(ilink, x, y));
cnt = 1;
while (ilink->next) {
ilink = ilink->next;
/* compute the residual only over the part of the vector needed */
PetscCall(MatMult(jac->Afield[cnt++], y, ilink->x));
PetscCall(VecScale(ilink->x, -1.0));
PetscCall(VecScatterBegin(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolve(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(VecScatterBegin(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
}
if (jac->type == PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE) {
cnt -= 2;
while (ilink->previous) {
ilink = ilink->previous;
/* compute the residual only over the part of the vector needed */
PetscCall(MatMult(jac->Afield[cnt--], y, ilink->x));
PetscCall(VecScale(ilink->x, -1.0));
PetscCall(VecScatterBegin(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilink->sctx, x, ilink->x, ADD_VALUES, SCATTER_FORWARD));
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolve(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(VecScatterBegin(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilink->sctx, ilink->y, y, ADD_VALUES, SCATTER_REVERSE));
}
}
} else SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Unsupported or unknown composition %d", (int)jac->type);
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCApply_FieldSplit_GKB(PC pc, Vec x, Vec y)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilinkA = jac->head, ilinkD = ilinkA->next;
KSP ksp = ilinkA->ksp;
Vec u, v, Hu, d, work1, work2;
PetscScalar alpha, z, nrmz2, *vecz;
PetscReal lowbnd, nu, beta;
PetscInt j, iterGKB;
PetscFunctionBegin;
PetscCall(VecScatterBegin(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkA->sctx, x, ilinkA->x, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(ilinkD->sctx, x, ilinkD->x, INSERT_VALUES, SCATTER_FORWARD));
u = jac->u;
v = jac->v;
Hu = jac->Hu;
d = jac->d;
work1 = jac->w1;
work2 = jac->w2;
vecz = jac->vecz;
/* Change RHS to comply with matrix regularization H = A + nu*B*B' */
/* Add q = q + nu*B*b */
if (jac->gkbnu) {
nu = jac->gkbnu;
PetscCall(VecScale(ilinkD->x, jac->gkbnu));
PetscCall(MatMultAdd(jac->B, ilinkD->x, ilinkA->x, ilinkA->x)); /* q = q + nu*B*b */
} else {
/* Situation when no augmented Lagrangian is used. Then we set inner */
/* matrix N = I in [Ar13], and thus nu = 1. */
nu = 1;
}
/* Transform rhs from [q,tilde{b}] to [0,b] */
PetscCall(PetscLogEventBegin(ilinkA->event, ksp, ilinkA->x, ilinkA->y, NULL));
PetscCall(KSPSolve(ksp, ilinkA->x, ilinkA->y));
PetscCall(KSPCheckSolve(ksp, pc, ilinkA->y));
PetscCall(PetscLogEventEnd(ilinkA->event, ksp, ilinkA->x, ilinkA->y, NULL));
PetscCall(MatMultHermitianTranspose(jac->B, ilinkA->y, work1));
PetscCall(VecAXPBY(work1, 1.0 / nu, -1.0, ilinkD->x)); /* c = b - B'*x */
/* First step of algorithm */
PetscCall(VecNorm(work1, NORM_2, &beta)); /* beta = sqrt(nu*c'*c)*/
KSPCheckDot(ksp, beta);
beta = PetscSqrtReal(nu) * beta;
PetscCall(VecAXPBY(v, nu / beta, 0.0, work1)); /* v = nu/beta *c */
PetscCall(MatMult(jac->B, v, work2)); /* u = H^{-1}*B*v */
PetscCall(PetscLogEventBegin(ilinkA->event, ksp, work2, u, NULL));
PetscCall(KSPSolve(ksp, work2, u));
PetscCall(KSPCheckSolve(ksp, pc, u));
PetscCall(PetscLogEventEnd(ilinkA->event, ksp, work2, u, NULL));
PetscCall(MatMult(jac->H, u, Hu)); /* alpha = u'*H*u */
PetscCall(VecDot(Hu, u, &alpha));
KSPCheckDot(ksp, alpha);
PetscCheck(PetscRealPart(alpha) > 0.0, PETSC_COMM_SELF, PETSC_ERR_NOT_CONVERGED, "GKB preconditioner diverged, H is not positive definite");
alpha = PetscSqrtReal(PetscAbsScalar(alpha));
PetscCall(VecScale(u, 1.0 / alpha));
PetscCall(VecAXPBY(d, 1.0 / alpha, 0.0, v)); /* v = nu/beta *c */
z = beta / alpha;
vecz[1] = z;
/* Computation of first iterate x(1) and p(1) */
PetscCall(VecAXPY(ilinkA->y, z, u));
PetscCall(VecCopy(d, ilinkD->y));
PetscCall(VecScale(ilinkD->y, -z));
iterGKB = 1;
lowbnd = 2 * jac->gkbtol;
if (jac->gkbmonitor) PetscCall(PetscViewerASCIIPrintf(jac->gkbviewer, "%3" PetscInt_FMT " GKB Lower bound estimate %14.12e\n", iterGKB, (double)lowbnd));
while (iterGKB < jac->gkbmaxit && lowbnd > jac->gkbtol) {
iterGKB += 1;
PetscCall(MatMultHermitianTranspose(jac->B, u, work1)); /* v <- nu*(B'*u-alpha/nu*v) */
PetscCall(VecAXPBY(v, nu, -alpha, work1));
PetscCall(VecNorm(v, NORM_2, &beta)); /* beta = sqrt(nu)*v'*v */
beta = beta / PetscSqrtReal(nu);
PetscCall(VecScale(v, 1.0 / beta));
PetscCall(MatMult(jac->B, v, work2)); /* u <- H^{-1}*(B*v-beta*H*u) */
PetscCall(MatMult(jac->H, u, Hu));
PetscCall(VecAXPY(work2, -beta, Hu));
PetscCall(PetscLogEventBegin(ilinkA->event, ksp, work2, u, NULL));
PetscCall(KSPSolve(ksp, work2, u));
PetscCall(KSPCheckSolve(ksp, pc, u));
PetscCall(PetscLogEventEnd(ilinkA->event, ksp, work2, u, NULL));
PetscCall(MatMult(jac->H, u, Hu)); /* alpha = u'*H*u */
PetscCall(VecDot(Hu, u, &alpha));
KSPCheckDot(ksp, alpha);
PetscCheck(PetscRealPart(alpha) > 0.0, PETSC_COMM_SELF, PETSC_ERR_NOT_CONVERGED, "GKB preconditioner diverged, H is not positive definite");
alpha = PetscSqrtReal(PetscAbsScalar(alpha));
PetscCall(VecScale(u, 1.0 / alpha));
z = -beta / alpha * z; /* z <- beta/alpha*z */
vecz[0] = z;
/* Computation of new iterate x(i+1) and p(i+1) */
PetscCall(VecAXPBY(d, 1.0 / alpha, -beta / alpha, v)); /* d = (v-beta*d)/alpha */
PetscCall(VecAXPY(ilinkA->y, z, u)); /* r = r + z*u */
PetscCall(VecAXPY(ilinkD->y, -z, d)); /* p = p - z*d */
PetscCall(MatMult(jac->H, ilinkA->y, Hu)); /* ||u||_H = u'*H*u */
PetscCall(VecDot(Hu, ilinkA->y, &nrmz2));
/* Compute Lower Bound estimate */
if (iterGKB > jac->gkbdelay) {
lowbnd = 0.0;
for (j = 0; j < jac->gkbdelay; j++) lowbnd += PetscAbsScalar(vecz[j] * vecz[j]);
lowbnd = PetscSqrtReal(lowbnd / PetscAbsScalar(nrmz2));
}
for (j = 0; j < jac->gkbdelay - 1; j++) vecz[jac->gkbdelay - j - 1] = vecz[jac->gkbdelay - j - 2];
if (jac->gkbmonitor) PetscCall(PetscViewerASCIIPrintf(jac->gkbviewer, "%3" PetscInt_FMT " GKB Lower bound estimate %14.12e\n", iterGKB, (double)lowbnd));
}
PetscCall(VecScatterBegin(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkA->sctx, ilinkA->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterBegin(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscCall(VecScatterEnd(ilinkD->sctx, ilinkD->y, y, INSERT_VALUES, SCATTER_REVERSE));
PetscFunctionReturn(PETSC_SUCCESS);
}
#define FieldSplitSplitSolveAddTranspose(ilink, xx, yy) \
((PetscErrorCode)(VecScatterBegin(ilink->sctx, xx, ilink->y, INSERT_VALUES, SCATTER_FORWARD) || VecScatterEnd(ilink->sctx, xx, ilink->y, INSERT_VALUES, SCATTER_FORWARD) || PetscLogEventBegin(ilink->event, ilink->ksp, ilink->y, ilink->x, NULL) || \
KSPSolveTranspose(ilink->ksp, ilink->y, ilink->x) || KSPCheckSolve(ilink->ksp, pc, ilink->x) || PetscLogEventEnd(ilink->event, ilink->ksp, ilink->y, ilink->x, NULL) || VecScatterBegin(ilink->sctx, ilink->x, yy, ADD_VALUES, SCATTER_REVERSE) || \
VecScatterEnd(ilink->sctx, ilink->x, yy, ADD_VALUES, SCATTER_REVERSE)))
static PetscErrorCode PCApplyTranspose_FieldSplit(PC pc, Vec x, Vec y)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head;
PetscInt bs;
PetscFunctionBegin;
if (jac->type == PC_COMPOSITE_ADDITIVE) {
if (jac->defaultsplit) {
PetscCall(VecGetBlockSize(x, &bs));
PetscCheck(jac->bs <= 0 || bs == jac->bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Blocksize of x vector %" PetscInt_FMT " does not match fieldsplit blocksize %" PetscInt_FMT, bs, jac->bs);
PetscCall(VecGetBlockSize(y, &bs));
PetscCheck(jac->bs <= 0 || bs == jac->bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Blocksize of y vector %" PetscInt_FMT " does not match fieldsplit blocksize %" PetscInt_FMT, bs, jac->bs);
PetscCall(VecStrideGatherAll(x, jac->x, INSERT_VALUES));
while (ilink) {
PetscCall(PetscLogEventBegin(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
PetscCall(KSPSolveTranspose(ilink->ksp, ilink->x, ilink->y));
PetscCall(KSPCheckSolve(ilink->ksp, pc, ilink->y));
PetscCall(PetscLogEventEnd(ilink->event, ilink->ksp, ilink->x, ilink->y, NULL));
ilink = ilink->next;
}
PetscCall(VecStrideScatterAll(jac->y, y, INSERT_VALUES));
} else {
PetscCall(VecSet(y, 0.0));
while (ilink) {
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, x, y));
ilink = ilink->next;
}
}
} else {
if (!jac->w1) {
PetscCall(VecDuplicate(x, &jac->w1));
PetscCall(VecDuplicate(x, &jac->w2));
}
PetscCall(VecSet(y, 0.0));
if (jac->type == PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE) {
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, x, y));
while (ilink->next) {
ilink = ilink->next;
PetscCall(MatMultTranspose(pc->mat, y, jac->w1));
PetscCall(VecWAXPY(jac->w2, -1.0, jac->w1, x));
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, jac->w2, y));
}
while (ilink->previous) {
ilink = ilink->previous;
PetscCall(MatMultTranspose(pc->mat, y, jac->w1));
PetscCall(VecWAXPY(jac->w2, -1.0, jac->w1, x));
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, jac->w2, y));
}
} else {
while (ilink->next) { /* get to last entry in linked list */
ilink = ilink->next;
}
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, x, y));
while (ilink->previous) {
ilink = ilink->previous;
PetscCall(MatMultTranspose(pc->mat, y, jac->w1));
PetscCall(VecWAXPY(jac->w2, -1.0, jac->w1, x));
PetscCall(FieldSplitSplitSolveAddTranspose(ilink, jac->w2, y));
}
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCReset_FieldSplit(PC pc)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head, next;
PetscFunctionBegin;
while (ilink) {
PetscCall(KSPDestroy(&ilink->ksp));
PetscCall(VecDestroy(&ilink->x));
PetscCall(VecDestroy(&ilink->y));
PetscCall(VecDestroy(&ilink->z));
PetscCall(VecScatterDestroy(&ilink->sctx));
PetscCall(ISDestroy(&ilink->is));
PetscCall(ISDestroy(&ilink->is_col));
PetscCall(PetscFree(ilink->splitname));
PetscCall(PetscFree(ilink->fields));
PetscCall(PetscFree(ilink->fields_col));
next = ilink->next;
PetscCall(PetscFree(ilink));
ilink = next;
}
jac->head = NULL;
PetscCall(PetscFree2(jac->x, jac->y));
if (jac->mat && jac->mat != jac->pmat) {
PetscCall(MatDestroyMatrices(jac->nsplits, &jac->mat));
} else if (jac->mat) {
jac->mat = NULL;
}
if (jac->pmat) PetscCall(MatDestroyMatrices(jac->nsplits, &jac->pmat));
if (jac->Afield) PetscCall(MatDestroyMatrices(jac->nsplits, &jac->Afield));
jac->nsplits = 0;
PetscCall(VecDestroy(&jac->w1));
PetscCall(VecDestroy(&jac->w2));
PetscCall(MatDestroy(&jac->schur));
PetscCall(MatDestroy(&jac->schurp));
PetscCall(MatDestroy(&jac->schur_user));
PetscCall(KSPDestroy(&jac->kspschur));
PetscCall(KSPDestroy(&jac->kspupper));
PetscCall(MatDestroy(&jac->B));
PetscCall(MatDestroy(&jac->C));
PetscCall(MatDestroy(&jac->H));
PetscCall(VecDestroy(&jac->u));
PetscCall(VecDestroy(&jac->v));
PetscCall(VecDestroy(&jac->Hu));
PetscCall(VecDestroy(&jac->d));
PetscCall(PetscFree(jac->vecz));
PetscCall(PetscViewerDestroy(&jac->gkbviewer));
jac->isrestrict = PETSC_FALSE;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCDestroy_FieldSplit(PC pc)
{
PetscFunctionBegin;
PetscCall(PCReset_FieldSplit(pc));
PetscCall(PetscFree(pc->data));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetFields_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetIS_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetType_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetBlockSize_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitRestrictIS_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSchurGetSubKSP_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBTol_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBMaxit_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBNu_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBDelay_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurPre_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSchurPre_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurFactType_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurScale_C", NULL));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCSetFromOptions_FieldSplit(PC pc, PetscOptionItems *PetscOptionsObject)
{
PetscInt bs;
PetscBool flg;
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PCCompositeType ctype;
PetscFunctionBegin;
PetscOptionsHeadBegin(PetscOptionsObject, "FieldSplit options");
PetscCall(PetscOptionsBool("-pc_fieldsplit_dm_splits", "Whether to use DMCreateFieldDecomposition() for splits", "PCFieldSplitSetDMSplits", jac->dm_splits, &jac->dm_splits, NULL));
PetscCall(PetscOptionsInt("-pc_fieldsplit_block_size", "Blocksize that defines number of fields", "PCFieldSplitSetBlockSize", jac->bs, &bs, &flg));
if (flg) PetscCall(PCFieldSplitSetBlockSize(pc, bs));
jac->diag_use_amat = pc->useAmat;
PetscCall(PetscOptionsBool("-pc_fieldsplit_diag_use_amat", "Use Amat (not Pmat) to extract diagonal fieldsplit blocks", "PCFieldSplitSetDiagUseAmat", jac->diag_use_amat, &jac->diag_use_amat, NULL));
jac->offdiag_use_amat = pc->useAmat;
PetscCall(PetscOptionsBool("-pc_fieldsplit_off_diag_use_amat", "Use Amat (not Pmat) to extract off-diagonal fieldsplit blocks", "PCFieldSplitSetOffDiagUseAmat", jac->offdiag_use_amat, &jac->offdiag_use_amat, NULL));
PetscCall(PetscOptionsBool("-pc_fieldsplit_detect_saddle_point", "Form 2-way split by detecting zero diagonal entries", "PCFieldSplitSetDetectSaddlePoint", jac->detect, &jac->detect, NULL));
PetscCall(PCFieldSplitSetDetectSaddlePoint(pc, jac->detect)); /* Sets split type and Schur PC type */
PetscCall(PetscOptionsEnum("-pc_fieldsplit_type", "Type of composition", "PCFieldSplitSetType", PCCompositeTypes, (PetscEnum)jac->type, (PetscEnum *)&ctype, &flg));
if (flg) PetscCall(PCFieldSplitSetType(pc, ctype));
/* Only setup fields once */
if ((jac->bs > 0) && (jac->nsplits == 0)) {
/* only allow user to set fields from command line if bs is already known.
otherwise user can set them in PCFieldSplitSetDefaults() */
PetscCall(PCFieldSplitSetRuntimeSplits_Private(pc));
if (jac->splitdefined) PetscCall(PetscInfo(pc, "Splits defined using the options database\n"));
}
if (jac->type == PC_COMPOSITE_SCHUR) {
PetscCall(PetscOptionsGetEnum(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, "-pc_fieldsplit_schur_factorization_type", PCFieldSplitSchurFactTypes, (PetscEnum *)&jac->schurfactorization, &flg));
if (flg) PetscCall(PetscInfo(pc, "Deprecated use of -pc_fieldsplit_schur_factorization_type\n"));
PetscCall(PetscOptionsEnum("-pc_fieldsplit_schur_fact_type", "Which off-diagonal parts of the block factorization to use", "PCFieldSplitSetSchurFactType", PCFieldSplitSchurFactTypes, (PetscEnum)jac->schurfactorization, (PetscEnum *)&jac->schurfactorization, NULL));
PetscCall(PetscOptionsEnum("-pc_fieldsplit_schur_precondition", "How to build preconditioner for Schur complement", "PCFieldSplitSetSchurPre", PCFieldSplitSchurPreTypes, (PetscEnum)jac->schurpre, (PetscEnum *)&jac->schurpre, NULL));
PetscCall(PetscOptionsScalar("-pc_fieldsplit_schur_scale", "Scale Schur complement", "PCFieldSplitSetSchurScale", jac->schurscale, &jac->schurscale, NULL));
} else if (jac->type == PC_COMPOSITE_GKB) {
PetscCall(PetscOptionsReal("-pc_fieldsplit_gkb_tol", "The tolerance for the lower bound stopping criterion", "PCFieldSplitGKBTol", jac->gkbtol, &jac->gkbtol, NULL));
PetscCall(PetscOptionsInt("-pc_fieldsplit_gkb_delay", "The delay value for lower bound criterion", "PCFieldSplitGKBDelay", jac->gkbdelay, &jac->gkbdelay, NULL));
PetscCall(PetscOptionsReal("-pc_fieldsplit_gkb_nu", "Parameter in augmented Lagrangian approach", "PCFieldSplitGKBNu", jac->gkbnu, &jac->gkbnu, NULL));
PetscCheck(jac->gkbnu >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nu cannot be less than 0: value %g", (double)jac->gkbnu);
PetscCall(PetscOptionsInt("-pc_fieldsplit_gkb_maxit", "Maximum allowed number of iterations", "PCFieldSplitGKBMaxit", jac->gkbmaxit, &jac->gkbmaxit, NULL));
PetscCall(PetscOptionsBool("-pc_fieldsplit_gkb_monitor", "Prints number of GKB iterations and error", "PCFieldSplitGKB", jac->gkbmonitor, &jac->gkbmonitor, NULL));
}
/*
In the initial call to this routine the sub-solver data structures do not exist so we cannot call KSPSetFromOptions() on them yet.
But after the initial setup of ALL the layers of sub-solvers is completed we do want to call KSPSetFromOptions() on the sub-solvers every time it
is called on the outer solver in case changes were made in the options database
But even after PCSetUp_FieldSplit() is called all the options inside the inner levels of sub-solvers may still not have been set thus we only call the KSPSetFromOptions()
if we know that the entire stack of sub-solvers below this have been complete instantiated, we check this by seeing if any solver iterations are complete.
Without this extra check test p2p1fetidp_olof_full and others fail with incorrect matrix types.
There could be a negative side effect of calling the KSPSetFromOptions() below.
If one captured the PetscObjectState of the options database one could skip these calls if the database has not changed from the previous call
*/
if (jac->issetup) {
PC_FieldSplitLink ilink = jac->head;
if (jac->type == PC_COMPOSITE_SCHUR) {
if (jac->kspupper && jac->kspupper->totalits > 0) PetscCall(KSPSetFromOptions(jac->kspupper));
if (jac->kspschur && jac->kspschur->totalits > 0) PetscCall(KSPSetFromOptions(jac->kspschur));
}
while (ilink) {
if (ilink->ksp->totalits > 0) PetscCall(KSPSetFromOptions(ilink->ksp));
ilink = ilink->next;
}
}
PetscOptionsHeadEnd();
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetFields_FieldSplit(PC pc, const char splitname[], PetscInt n, const PetscInt *fields, const PetscInt *fields_col)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink, next = jac->head;
char prefix[128];
PetscInt i;
PetscFunctionBegin;
if (jac->splitdefined) {
PetscCall(PetscInfo(pc, "Ignoring new split \"%s\" because the splits have already been defined\n", splitname));
PetscFunctionReturn(PETSC_SUCCESS);
}
for (i = 0; i < n; i++) {
PetscCheck(fields[i] < jac->bs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " requested but only %" PetscInt_FMT " exist", fields[i], jac->bs);
PetscCheck(fields[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative field %" PetscInt_FMT " requested", fields[i]);
}
PetscCall(PetscNew(&ilink));
if (splitname) {
PetscCall(PetscStrallocpy(splitname, &ilink->splitname));
} else {
PetscCall(PetscMalloc1(3, &ilink->splitname));
PetscCall(PetscSNPrintf(ilink->splitname, 2, "%" PetscInt_FMT, jac->nsplits));
}
ilink->event = jac->nsplits < 5 ? KSP_Solve_FS_0 + jac->nsplits : KSP_Solve_FS_0 + 4; /* Any split great than 4 gets logged in the 4th split */
PetscCall(PetscMalloc1(n, &ilink->fields));
PetscCall(PetscArraycpy(ilink->fields, fields, n));
PetscCall(PetscMalloc1(n, &ilink->fields_col));
PetscCall(PetscArraycpy(ilink->fields_col, fields_col, n));
ilink->nfields = n;
ilink->next = NULL;
PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &ilink->ksp));
PetscCall(KSPSetNestLevel(ilink->ksp, pc->kspnestlevel));
PetscCall(KSPSetErrorIfNotConverged(ilink->ksp, pc->erroriffailure));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)ilink->ksp, (PetscObject)pc, 1));
PetscCall(KSPSetType(ilink->ksp, KSPPREONLY));
PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%sfieldsplit_%s_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ilink->splitname));
PetscCall(KSPSetOptionsPrefix(ilink->ksp, prefix));
if (!next) {
jac->head = ilink;
ilink->previous = NULL;
} else {
while (next->next) next = next->next;
next->next = ilink;
ilink->previous = next;
}
jac->nsplits++;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSchurGetSubKSP_FieldSplit(PC pc, PetscInt *n, KSP **subksp)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
*subksp = NULL;
if (n) *n = 0;
if (jac->type == PC_COMPOSITE_SCHUR) {
PetscInt nn;
PetscCheck(jac->schur, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Must call KSPSetUp() or PCSetUp() before calling PCFieldSplitSchurGetSubKSP()");
PetscCheck(jac->nsplits == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "Unexpected number of splits %" PetscInt_FMT " != 2", jac->nsplits);
nn = jac->nsplits + (jac->kspupper != jac->head->ksp ? 1 : 0);
PetscCall(PetscMalloc1(nn, subksp));
(*subksp)[0] = jac->head->ksp;
(*subksp)[1] = jac->kspschur;
if (jac->kspupper != jac->head->ksp) (*subksp)[2] = jac->kspupper;
if (n) *n = nn;
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitGetSubKSP_FieldSplit_Schur(PC pc, PetscInt *n, KSP **subksp)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
PetscCheck(jac->schur, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Must call KSPSetUp() or PCSetUp() before calling PCFieldSplitGetSubKSP()");
PetscCall(PetscMalloc1(jac->nsplits, subksp));
PetscCall(MatSchurComplementGetKSP(jac->schur, *subksp));
(*subksp)[1] = jac->kspschur;
if (n) *n = jac->nsplits;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitGetSubKSP_FieldSplit(PC pc, PetscInt *n, KSP **subksp)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscInt cnt = 0;
PC_FieldSplitLink ilink = jac->head;
PetscFunctionBegin;
PetscCall(PetscMalloc1(jac->nsplits, subksp));
while (ilink) {
(*subksp)[cnt++] = ilink->ksp;
ilink = ilink->next;
}
PetscCheck(cnt == jac->nsplits, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Corrupt PCFIELDSPLIT object: number of splits in linked list %" PetscInt_FMT " does not match number in object %" PetscInt_FMT, cnt, jac->nsplits);
if (n) *n = jac->nsplits;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitRestrictIS - Restricts the fieldsplit `IS`s to be within a given `IS`.
Input Parameters:
+ pc - the preconditioner context
- isy - the index set that defines the indices to which the fieldsplit is to be restricted
Level: advanced
Developer Notes:
It seems the resulting `IS`s will not cover the entire space, so
how can they define a convergent preconditioner? Needs explaining.
.seealso: [](sec_block_matrices), `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSetIS()`
@*/
PetscErrorCode PCFieldSplitRestrictIS(PC pc, IS isy)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidHeaderSpecific(isy, IS_CLASSID, 2);
PetscTryMethod(pc, "PCFieldSplitRestrictIS_C", (PC, IS), (pc, isy));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitRestrictIS_FieldSplit(PC pc, IS isy)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head, next;
PetscInt localsize, size, sizez, i;
const PetscInt *ind, *indz;
PetscInt *indc, *indcz;
PetscBool flg;
PetscFunctionBegin;
PetscCall(ISGetLocalSize(isy, &localsize));
PetscCallMPI(MPI_Scan(&localsize, &size, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)isy)));
size -= localsize;
while (ilink) {
IS isrl, isr;
PC subpc;
PetscCall(ISEmbed(ilink->is, isy, PETSC_TRUE, &isrl));
PetscCall(ISGetLocalSize(isrl, &localsize));
PetscCall(PetscMalloc1(localsize, &indc));
PetscCall(ISGetIndices(isrl, &ind));
PetscCall(PetscArraycpy(indc, ind, localsize));
PetscCall(ISRestoreIndices(isrl, &ind));
PetscCall(ISDestroy(&isrl));
for (i = 0; i < localsize; i++) *(indc + i) += size;
PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)isy), localsize, indc, PETSC_OWN_POINTER, &isr));
PetscCall(PetscObjectReference((PetscObject)isr));
PetscCall(ISDestroy(&ilink->is));
ilink->is = isr;
PetscCall(PetscObjectReference((PetscObject)isr));
PetscCall(ISDestroy(&ilink->is_col));
ilink->is_col = isr;
PetscCall(ISDestroy(&isr));
PetscCall(KSPGetPC(ilink->ksp, &subpc));
PetscCall(PetscObjectTypeCompare((PetscObject)subpc, PCFIELDSPLIT, &flg));
if (flg) {
IS iszl, isz;
MPI_Comm comm;
PetscCall(ISGetLocalSize(ilink->is, &localsize));
comm = PetscObjectComm((PetscObject)ilink->is);
PetscCall(ISEmbed(isy, ilink->is, PETSC_TRUE, &iszl));
PetscCallMPI(MPI_Scan(&localsize, &sizez, 1, MPIU_INT, MPI_SUM, comm));
sizez -= localsize;
PetscCall(ISGetLocalSize(iszl, &localsize));
PetscCall(PetscMalloc1(localsize, &indcz));
PetscCall(ISGetIndices(iszl, &indz));
PetscCall(PetscArraycpy(indcz, indz, localsize));
PetscCall(ISRestoreIndices(iszl, &indz));
PetscCall(ISDestroy(&iszl));
for (i = 0; i < localsize; i++) *(indcz + i) += sizez;
PetscCall(ISCreateGeneral(comm, localsize, indcz, PETSC_OWN_POINTER, &isz));
PetscCall(PCFieldSplitRestrictIS(subpc, isz));
PetscCall(ISDestroy(&isz));
}
next = ilink->next;
ilink = next;
}
jac->isrestrict = PETSC_TRUE;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetIS_FieldSplit(PC pc, const char splitname[], IS is)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink, next = jac->head;
char prefix[128];
PetscFunctionBegin;
if (jac->splitdefined) {
PetscCall(PetscInfo(pc, "Ignoring new split \"%s\" because the splits have already been defined\n", splitname));
PetscFunctionReturn(PETSC_SUCCESS);
}
PetscCall(PetscNew(&ilink));
if (splitname) {
PetscCall(PetscStrallocpy(splitname, &ilink->splitname));
} else {
PetscCall(PetscMalloc1(8, &ilink->splitname));
PetscCall(PetscSNPrintf(ilink->splitname, 7, "%" PetscInt_FMT, jac->nsplits));
}
ilink->event = jac->nsplits < 5 ? KSP_Solve_FS_0 + jac->nsplits : KSP_Solve_FS_0 + 4; /* Any split great than 4 gets logged in the 4th split */
PetscCall(PetscObjectReference((PetscObject)is));
PetscCall(ISDestroy(&ilink->is));
ilink->is = is;
PetscCall(PetscObjectReference((PetscObject)is));
PetscCall(ISDestroy(&ilink->is_col));
ilink->is_col = is;
ilink->next = NULL;
PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &ilink->ksp));
PetscCall(KSPSetNestLevel(ilink->ksp, pc->kspnestlevel));
PetscCall(KSPSetErrorIfNotConverged(ilink->ksp, pc->erroriffailure));
PetscCall(PetscObjectIncrementTabLevel((PetscObject)ilink->ksp, (PetscObject)pc, 1));
PetscCall(KSPSetType(ilink->ksp, KSPPREONLY));
PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%sfieldsplit_%s_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ilink->splitname));
PetscCall(KSPSetOptionsPrefix(ilink->ksp, prefix));
if (!next) {
jac->head = ilink;
ilink->previous = NULL;
} else {
while (next->next) next = next->next;
next->next = ilink;
ilink->previous = next;
}
jac->nsplits++;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitSetFields - Sets the fields that define one particular split in `PCFIELDSPLIT`
Logically Collective
Input Parameters:
+ pc - the preconditioner context
. splitname - name of this split, if `NULL` the number of the split is used
. n - the number of fields in this split
. fields - the fields in this split
- fields_col - generally the same as fields, if it does not match fields then the matrix block that is solved for this set of fields comes from an off-diagonal block
of the matrix and fields_col provides the column indices for that block
Level: intermediate
Notes:
Use `PCFieldSplitSetIS()` to set a general set of indices as a split.
`PCFieldSplitSetFields()` is for defining fields as strided blocks. For example, if the block
size is three then one can define a split as 0, or 1 or 2 or 0,1 or 0,2 or 1,2 which mean
0xx3xx6xx9xx12 ... x1xx4xx7xx ... xx2xx5xx8xx.. 01x34x67x... 0x1x3x5x7.. x12x45x78x....
where the numbered entries indicate what is in the split.
This function is called once per split (it creates a new split each time). Solve options
for this split will be available under the prefix `-fieldsplit_SPLITNAME_`.
`PCFieldSplitSetIS()` does not support having a fields_col different from fields
Developer Notes:
This routine does not actually create the `IS` representing the split, that is delayed
until `PCSetUp_FieldSplit()`, because information about the vector/matrix layouts may not be
available when this routine is called.
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetBlockSize()`, `PCFieldSplitSetIS()`, `PCFieldSplitRestrictIS()`
@*/
PetscErrorCode PCFieldSplitSetFields(PC pc, const char splitname[], PetscInt n, const PetscInt *fields, const PetscInt *fields_col)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(splitname, 2);
PetscCheck(n >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Provided number of fields %" PetscInt_FMT " in split \"%s\" not positive", n, splitname);
PetscAssertPointer(fields, 4);
PetscTryMethod(pc, "PCFieldSplitSetFields_C", (PC, const char[], PetscInt, const PetscInt *, const PetscInt *), (pc, splitname, n, fields, fields_col));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetDiagUseAmat - set flag indicating whether to extract diagonal blocks from Amat (rather than Pmat) to build
the sub-matrices associated with each split. Where `KSPSetOperators`(ksp,Amat,Pmat)) was used to supply the operators.
Logically Collective
Input Parameters:
+ pc - the preconditioner object
- flg - boolean flag indicating whether or not to use Amat to extract the diagonal blocks from
Options Database Key:
. -pc_fieldsplit_diag_use_amat - use the Amat to provide the diagonal blocks
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCSetOperators()`, `KSPSetOperators()`, `PCFieldSplitGetDiagUseAmat()`, `PCFieldSplitSetOffDiagUseAmat()`, `PCFIELDSPLIT`
@*/
PetscErrorCode PCFieldSplitSetDiagUseAmat(PC pc, PetscBool flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "PC not of type %s", PCFIELDSPLIT);
jac->diag_use_amat = flg;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitGetDiagUseAmat - get the flag indicating whether to extract diagonal blocks from Amat (rather than Pmat) to build
the sub-matrices associated with each split. Where `KSPSetOperators`(ksp,Amat,Pmat)) was used to supply the operators.
Logically Collective
Input Parameter:
. pc - the preconditioner object
Output Parameter:
. flg - boolean flag indicating whether or not to use Amat to extract the diagonal blocks from
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCSetOperators()`, `KSPSetOperators()`, `PCFieldSplitSetDiagUseAmat()`, `PCFieldSplitGetOffDiagUseAmat()`, `PCFIELDSPLIT`
@*/
PetscErrorCode PCFieldSplitGetDiagUseAmat(PC pc, PetscBool *flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(flg, 2);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "PC not of type %s", PCFIELDSPLIT);
*flg = jac->diag_use_amat;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetOffDiagUseAmat - set flag indicating whether to extract off-diagonal blocks from Amat (rather than Pmat) to build
the sub-matrices associated with each split. Where `KSPSetOperators`(ksp,Amat,Pmat)) was used to supply the operators.
Logically Collective
Input Parameters:
+ pc - the preconditioner object
- flg - boolean flag indicating whether or not to use Amat to extract the off-diagonal blocks from
Options Database Key:
. -pc_fieldsplit_off_diag_use_amat <bool> - use the Amat to extract the off-diagonal blocks
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCSetOperators()`, `KSPSetOperators()`, `PCFieldSplitGetOffDiagUseAmat()`, `PCFieldSplitSetDiagUseAmat()`, `PCFIELDSPLIT`
@*/
PetscErrorCode PCFieldSplitSetOffDiagUseAmat(PC pc, PetscBool flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "PC not of type %s", PCFIELDSPLIT);
jac->offdiag_use_amat = flg;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitGetOffDiagUseAmat - get the flag indicating whether to extract off-diagonal blocks from Amat (rather than Pmat) to build
the sub-matrices associated with each split. Where `KSPSetOperators`(ksp,Amat,Pmat)) was used to supply the operators.
Logically Collective
Input Parameter:
. pc - the preconditioner object
Output Parameter:
. flg - boolean flag indicating whether or not to use Amat to extract the off-diagonal blocks from
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCSetOperators()`, `KSPSetOperators()`, `PCFieldSplitSetOffDiagUseAmat()`, `PCFieldSplitGetDiagUseAmat()`, `PCFIELDSPLIT`
@*/
PetscErrorCode PCFieldSplitGetOffDiagUseAmat(PC pc, PetscBool *flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(flg, 2);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "PC not of type %s", PCFIELDSPLIT);
*flg = jac->offdiag_use_amat;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitSetIS - Sets the exact elements for a split in a `PCFIELDSPLIT`
Logically Collective
Input Parameters:
+ pc - the preconditioner context
. splitname - name of this split, if `NULL` the number of the split is used
- is - the index set that defines the elements in this split
Level: intermediate
Notes:
Use `PCFieldSplitSetFields()`, for splits defined by strided types.
This function is called once per split (it creates a new split each time). Solve options
for this split will be available under the prefix -fieldsplit_SPLITNAME_.
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetBlockSize()`
@*/
PetscErrorCode PCFieldSplitSetIS(PC pc, const char splitname[], IS is)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
if (splitname) PetscAssertPointer(splitname, 2);
PetscValidHeaderSpecific(is, IS_CLASSID, 3);
PetscTryMethod(pc, "PCFieldSplitSetIS_C", (PC, const char[], IS), (pc, splitname, is));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitGetIS - Retrieves the elements for a split as an `IS`
Logically Collective
Input Parameters:
+ pc - the preconditioner context
- splitname - name of this split
Output Parameter:
. is - the index set that defines the elements in this split, or `NULL` if the split is not found
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetIS()`
@*/
PetscErrorCode PCFieldSplitGetIS(PC pc, const char splitname[], IS *is)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(splitname, 2);
PetscAssertPointer(is, 3);
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head;
PetscBool found;
*is = NULL;
while (ilink) {
PetscCall(PetscStrcmp(ilink->splitname, splitname, &found));
if (found) {
*is = ilink->is;
break;
}
ilink = ilink->next;
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitGetISByIndex - Retrieves the elements for a given split as an `IS`
Logically Collective
Input Parameters:
+ pc - the preconditioner context
- index - index of this split
Output Parameter:
. is - the index set that defines the elements in this split
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitGetIS()`, `PCFieldSplitSetIS()`
@*/
PetscErrorCode PCFieldSplitGetISByIndex(PC pc, PetscInt index, IS *is)
{
PetscFunctionBegin;
PetscCheck(index >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative field %" PetscInt_FMT " requested", index);
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(is, 3);
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink = jac->head;
PetscInt i = 0;
PetscCheck(index < jac->nsplits, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Field %" PetscInt_FMT " requested but only %" PetscInt_FMT " exist", index, jac->nsplits);
while (i < index) {
ilink = ilink->next;
++i;
}
PetscCall(PCFieldSplitGetIS(pc, ilink->splitname, is));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetBlockSize - Sets the block size for defining where fields start in the
fieldsplit preconditioner when calling `PCFieldSplitSetIS()`. If not set the matrix block size is used.
Logically Collective
Input Parameters:
+ pc - the preconditioner context
- bs - the block size
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSetIS()`
@*/
PetscErrorCode PCFieldSplitSetBlockSize(PC pc, PetscInt bs)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveInt(pc, bs, 2);
PetscTryMethod(pc, "PCFieldSplitSetBlockSize_C", (PC, PetscInt), (pc, bs));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitGetSubKSP - Gets the `KSP` contexts for all splits
Collective
Input Parameter:
. pc - the preconditioner context
Output Parameters:
+ n - the number of splits
- subksp - the array of `KSP` contexts
Level: advanced
Notes:
After `PCFieldSplitGetSubKSP()` the array of `KSP`s is to be freed by the user with `PetscFree()`
(not the `KSP`, just the array that contains them).
You must call `PCSetUp()` before calling `PCFieldSplitGetSubKSP()`.
If the fieldsplit is of type `PC_COMPOSITE_SCHUR`, it returns the `KSP` object used inside the
Schur complement and the `KSP` object used to iterate over the Schur complement.
To access all the `KSP` objects used in `PC_COMPOSITE_SCHUR`, use `PCFieldSplitSchurGetSubKSP()`.
If the fieldsplit is of type `PC_COMPOSITE_GKB`, it returns the `KSP` object used to solve the
inner linear system defined by the matrix H in each loop.
Fortran Notes:
You must pass in a `KSP` array that is large enough to contain all the `KSP`s.
You can call `PCFieldSplitGetSubKSP`(pc,n,`PETSC_NULL_KSP`,ierr) to determine how large the
`KSP` array must be.
Developer Notes:
There should be a `PCFieldSplitRestoreSubKSP()` instead of requiring the user to call `PetscFree()`
The Fortran interface should be modernized to return directly the array of values.
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSetIS()`, `PCFieldSplitSchurGetSubKSP()`
@*/
PetscErrorCode PCFieldSplitGetSubKSP(PC pc, PetscInt *n, KSP *subksp[])
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
if (n) PetscAssertPointer(n, 2);
PetscUseMethod(pc, "PCFieldSplitGetSubKSP_C", (PC, PetscInt *, KSP **), (pc, n, subksp));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitSchurGetSubKSP - Gets the `KSP` contexts used inside the Schur complement based `PCFIELDSPLIT`
Collective
Input Parameter:
. pc - the preconditioner context
Output Parameters:
+ n - the number of splits
- subksp - the array of `KSP` contexts
Level: advanced
Notes:
After `PCFieldSplitSchurGetSubKSP()` the array of `KSP`s is to be freed by the user with `PetscFree()`
(not the `KSP` just the array that contains them).
You must call `PCSetUp()` before calling `PCFieldSplitSchurGetSubKSP()`.
If the fieldsplit type is of type `PC_COMPOSITE_SCHUR`, it returns (in order)
+ 1 - the `KSP` used for the (1,1) block
. 2 - the `KSP` used for the Schur complement (not the one used for the interior Schur solver)
- 3 - the `KSP` used for the (1,1) block in the upper triangular factor (if different from that of the (1,1) block).
It returns a null array if the fieldsplit is not of type `PC_COMPOSITE_SCHUR`; in this case, you should use `PCFieldSplitGetSubKSP()`.
Fortran Notes:
You must pass in a `KSP` array that is large enough to contain all the local `KSP`s.
You can call `PCFieldSplitSchurGetSubKSP`(pc,n,`PETSC_NULL_KSP`,ierr) to determine how large the
`KSP` array must be.
Developer Notes:
There should be a `PCFieldSplitRestoreSubKSP()` instead of requiring the user to call `PetscFree()`
Should the functionality of `PCFieldSplitSchurGetSubKSP()` and `PCFieldSplitGetSubKSP()` be merged?
The Fortran interface should be modernized to return directly the array of values.
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSetIS()`, `PCFieldSplitGetSubKSP()`
@*/
PetscErrorCode PCFieldSplitSchurGetSubKSP(PC pc, PetscInt *n, KSP *subksp[])
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
if (n) PetscAssertPointer(n, 2);
PetscUseMethod(pc, "PCFieldSplitSchurGetSubKSP_C", (PC, PetscInt *, KSP **), (pc, n, subksp));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetSchurPre - Indicates from what operator the preconditioner is constructucted for the Schur complement.
The default is the A11 matrix.
Collective
Input Parameters:
+ pc - the preconditioner context
. ptype - which matrix to use for preconditioning the Schur complement: `PC_FIELDSPLIT_SCHUR_PRE_A11` (default),
`PC_FIELDSPLIT_SCHUR_PRE_SELF`, `PC_FIELDSPLIT_SCHUR_PRE_USER`,
`PC_FIELDSPLIT_SCHUR_PRE_SELFP`, and `PC_FIELDSPLIT_SCHUR_PRE_FULL`
- pre - matrix to use for preconditioning, or `NULL`
Options Database Keys:
+ -pc_fieldsplit_schur_precondition <self,selfp,user,a11,full> - default is `a11`. See notes for meaning of various arguments
- -fieldsplit_1_pc_type <pctype> - the preconditioner algorithm that is used to construct the preconditioner from the operator
Level: intermediate
Notes:
If ptype is
+ a11 - the preconditioner for the Schur complement is generated from the block diagonal part of the preconditioner
matrix associated with the Schur complement (i.e. A11), not the Schur complement matrix
. self - the preconditioner for the Schur complement is generated from the symbolic representation of the Schur complement matrix:
The only preconditioner that currently works with this symbolic representation matrix object is the `PCLSC`
preconditioner
. user - the preconditioner for the Schur complement is generated from the user provided matrix (pre argument
to this function).
. selfp - the preconditioning for the Schur complement is generated from an explicitly-assembled approximation Sp = A11 - A10 inv(diag(A00)) A01
This is only a good preconditioner when diag(A00) is a good preconditioner for A00. Optionally, A00 can be
lumped before extracting the diagonal using the additional option `-fieldsplit_1_mat_schur_complement_ainv_type lump`
- full - the preconditioner for the Schur complement is generated from the exact Schur complement matrix representation
computed internally by `PCFIELDSPLIT` (this is expensive)
useful mostly as a test that the Schur complement approach can work for your problem
When solving a saddle point problem, where the A11 block is identically zero, using `a11` as the ptype only makes sense
with the additional option `-fieldsplit_1_pc_type none`. Usually for saddle point problems one would use a ptype of self and
`-fieldsplit_1_pc_type lsc` which uses the least squares commutator to compute a preconditioner for the Schur complement.
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSchurPre()`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSchurPreType`,
`MatSchurComplementSetAinvType()`, `PCLSC`,
@*/
PetscErrorCode PCFieldSplitSetSchurPre(PC pc, PCFieldSplitSchurPreType ptype, Mat pre)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscTryMethod(pc, "PCFieldSplitSetSchurPre_C", (PC, PCFieldSplitSchurPreType, Mat), (pc, ptype, pre));
PetscFunctionReturn(PETSC_SUCCESS);
}
PetscErrorCode PCFieldSplitSchurPrecondition(PC pc, PCFieldSplitSchurPreType ptype, Mat pre)
{
return PCFieldSplitSetSchurPre(pc, ptype, pre);
} /* Deprecated name */
/*@
PCFieldSplitGetSchurPre - For Schur complement fieldsplit, determine how the Schur complement will be
preconditioned. See `PCFieldSplitSetSchurPre()` for details.
Logically Collective
Input Parameter:
. pc - the preconditioner context
Output Parameters:
+ ptype - which matrix to use for preconditioning the Schur complement: `PC_FIELDSPLIT_SCHUR_PRE_A11`, `PC_FIELDSPLIT_SCHUR_PRE_SELF`, `PC_FIELDSPLIT_SCHUR_PRE_USER`
- pre - matrix to use for preconditioning (with `PC_FIELDSPLIT_SCHUR_PRE_USER`), or `NULL`
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitSetSchurPre()`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSchurPreType`, `PCLSC`
@*/
PetscErrorCode PCFieldSplitGetSchurPre(PC pc, PCFieldSplitSchurPreType *ptype, Mat *pre)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscUseMethod(pc, "PCFieldSplitGetSchurPre_C", (PC, PCFieldSplitSchurPreType *, Mat *), (pc, ptype, pre));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSchurGetS - extract the `MATSCHURCOMPLEMENT` object used by this `PCFIELDSPLIT` in case it needs to be configured separately
Not Collective
Input Parameter:
. pc - the preconditioner context
Output Parameter:
. S - the Schur complement matrix
Level: advanced
Note:
This matrix should not be destroyed using `MatDestroy()`; rather, use `PCFieldSplitSchurRestoreS()`.
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSchurPreType`, `PCFieldSplitSetSchurPre()`, `MATSCHURCOMPLEMENT`, `PCFieldSplitSchurRestoreS()`,
`MatCreateSchurComplement()`, `MatSchurComplementGetKSP()`, `MatSchurComplementComputeExplicitOperator()`, `MatGetSchurComplement()`
@*/
PetscErrorCode PCFieldSplitSchurGetS(PC pc, Mat *S)
{
const char *t;
PetscBool isfs;
PC_FieldSplit *jac;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscCall(PetscObjectGetType((PetscObject)pc, &t));
PetscCall(PetscStrcmp(t, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Expected PC of type PCFIELDSPLIT, got %s instead", t);
jac = (PC_FieldSplit *)pc->data;
PetscCheck(jac->type == PC_COMPOSITE_SCHUR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Expected PCFIELDSPLIT of type SCHUR, got %d instead", jac->type);
if (S) *S = jac->schur;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSchurRestoreS - returns the `MATSCHURCOMPLEMENT` matrix used by this `PC`
Not Collective
Input Parameters:
+ pc - the preconditioner context
- S - the Schur complement matrix
Level: advanced
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSchurPreType`, `PCFieldSplitSetSchurPre()`, `MatSchurComplement`, `PCFieldSplitSchurGetS()`
@*/
PetscErrorCode PCFieldSplitSchurRestoreS(PC pc, Mat *S)
{
const char *t;
PetscBool isfs;
PC_FieldSplit *jac;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscCall(PetscObjectGetType((PetscObject)pc, &t));
PetscCall(PetscStrcmp(t, PCFIELDSPLIT, &isfs));
PetscCheck(isfs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Expected PC of type PCFIELDSPLIT, got %s instead", t);
jac = (PC_FieldSplit *)pc->data;
PetscCheck(jac->type == PC_COMPOSITE_SCHUR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Expected PCFIELDSPLIT of type SCHUR, got %d instead", jac->type);
PetscCheck(S && (*S == jac->schur), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatSchurComplement restored is not the same as gotten");
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetSchurPre_FieldSplit(PC pc, PCFieldSplitSchurPreType ptype, Mat pre)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->schurpre = ptype;
if (ptype == PC_FIELDSPLIT_SCHUR_PRE_USER && pre) {
PetscCall(MatDestroy(&jac->schur_user));
jac->schur_user = pre;
PetscCall(PetscObjectReference((PetscObject)jac->schur_user));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitGetSchurPre_FieldSplit(PC pc, PCFieldSplitSchurPreType *ptype, Mat *pre)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
if (ptype) *ptype = jac->schurpre;
if (pre) *pre = jac->schur_user;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetSchurFactType - sets which blocks of the approximate block factorization to retain in the preconditioner
Collective
Input Parameters:
+ pc - the preconditioner context
- ftype - which blocks of factorization to retain, `PC_FIELDSPLIT_SCHUR_FACT_FULL` is default
Options Database Key:
. -pc_fieldsplit_schur_fact_type <diag,lower,upper,full> - default is `full`
Level: intermediate
Notes:
The FULL factorization is
.vb
(A B) = (1 0) (A 0) (1 Ainv*B) = L D U
(C E) (C*Ainv 1) (0 S) (0 1)
.vb
where S = E - C*Ainv*B. In practice, the full factorization is applied via block triangular solves with the grouping L*(D*U). UPPER uses D*U, LOWER uses L*D,
and DIAG is the diagonal part with the sign of S flipped (because this makes the preconditioner positive definite for many formulations, thus allowing the use of `KSPMINRES)`.
Sign flipping of S can be turned off with `PCFieldSplitSetSchurScale()`.
If A and S are solved exactly
.vb
*) FULL factorization is a direct solver.
*) The preconditioned operator with LOWER or UPPER has all eigenvalues equal to 1 and minimal polynomial of degree 2, so `KSPGMRES` converges in 2 iterations.
*) With DIAG, the preconditioned operator has three distinct nonzero eigenvalues and minimal polynomial of degree at most 4, so `KSPGMRES` converges in at most 4 iterations.
.ve
If the iteration count is very low, consider using `KSPFGMRES` or `KSPGCR` which can use one less preconditioner
application in this case. Note that the preconditioned operator may be highly non-normal, so such fast convergence may not be observed in practice.
For symmetric problems in which A is positive definite and S is negative definite, DIAG can be used with `KSPMINRES`.
A flexible method like `KSPFGMRES` or `KSPGCR` must be used if the fieldsplit preconditioner is nonlinear (e.g. a few iterations of a Krylov method is used to solve with A or S).
References:
+ * - Murphy, Golub, and Wathen, A note on preconditioning indefinite linear systems, SIAM J. Sci. Comput., 21 (2000).
- * - Ipsen, A note on preconditioning nonsymmetric matrices, SIAM J. Sci. Comput., 23 (2001).
.seealso: [](sec_block_matrices), `PC`, `PCFieldSplitGetSubKSP()`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSchurPreType`, `PCFieldSplitSetSchurScale()`
@*/
PetscErrorCode PCFieldSplitSetSchurFactType(PC pc, PCFieldSplitSchurFactType ftype)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscTryMethod(pc, "PCFieldSplitSetSchurFactType_C", (PC, PCFieldSplitSchurFactType), (pc, ftype));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetSchurFactType_FieldSplit(PC pc, PCFieldSplitSchurFactType ftype)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->schurfactorization = ftype;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetSchurScale - Controls the sign flip of S for `PC_FIELDSPLIT_SCHUR_FACT_DIAG`.
Collective
Input Parameters:
+ pc - the preconditioner context
- scale - scaling factor for the Schur complement
Options Database Key:
. -pc_fieldsplit_schur_scale - default is -1.0
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetFields()`, `PCFieldSplitSchurFactType`, `PCFieldSplitSetSchurFactType()`
@*/
PetscErrorCode PCFieldSplitSetSchurScale(PC pc, PetscScalar scale)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveScalar(pc, scale, 2);
PetscTryMethod(pc, "PCFieldSplitSetSchurScale_C", (PC, PetscScalar), (pc, scale));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetSchurScale_FieldSplit(PC pc, PetscScalar scale)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->schurscale = scale;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
PCFieldSplitGetSchurBlocks - Gets all matrix blocks for the Schur complement
Collective
Input Parameter:
. pc - the preconditioner context
Output Parameters:
+ A00 - the (0,0) block
. A01 - the (0,1) block
. A10 - the (1,0) block
- A11 - the (1,1) block
Level: advanced
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `MatSchurComplementGetSubMatrices()`, `MatSchurComplementSetSubMatrices()`
@*/
PetscErrorCode PCFieldSplitGetSchurBlocks(PC pc, Mat *A00, Mat *A01, Mat *A10, Mat *A11)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscCheck(jac->type == PC_COMPOSITE_SCHUR, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "FieldSplit is not using a Schur complement approach.");
if (A00) *A00 = jac->pmat[0];
if (A01) *A01 = jac->B;
if (A10) *A10 = jac->C;
if (A11) *A11 = jac->pmat[1];
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetGKBTol - Sets the solver tolerance for the generalized Golub-Kahan bidiagonalization preconditioner in `PCFIELDSPLIT`
Collective
Input Parameters:
+ pc - the preconditioner context
- tolerance - the solver tolerance
Options Database Key:
. -pc_fieldsplit_gkb_tol - default is 1e-5
Level: intermediate
Note:
The generalized GKB algorithm uses a lower bound estimate of the error in energy norm as stopping criterion.
It stops once the lower bound estimate undershoots the required solver tolerance. Although the actual error might be bigger than
this estimate, the stopping criterion is satisfactory in practical cases [A13].
References:
[Ar13] Generalized Golub-Kahan bidiagonalization and stopping criteria, SIAM J. Matrix Anal. Appl., Vol. 34, No. 2, pp. 571-592, 2013.
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetGKBDelay()`, `PCFieldSplitSetGKBNu()`, `PCFieldSplitSetGKBMaxit()`
@*/
PetscErrorCode PCFieldSplitSetGKBTol(PC pc, PetscReal tolerance)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveReal(pc, tolerance, 2);
PetscTryMethod(pc, "PCFieldSplitSetGKBTol_C", (PC, PetscReal), (pc, tolerance));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetGKBTol_FieldSplit(PC pc, PetscReal tolerance)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->gkbtol = tolerance;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetGKBMaxit - Sets the maximum number of iterations for the generalized Golub-Kahan bidiagonalization preconditioner in `PCFIELDSPLIT`
Collective
Input Parameters:
+ pc - the preconditioner context
- maxit - the maximum number of iterations
Options Database Key:
. -pc_fieldsplit_gkb_maxit - default is 100
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetGKBDelay()`, `PCFieldSplitSetGKBTol()`, `PCFieldSplitSetGKBNu()`
@*/
PetscErrorCode PCFieldSplitSetGKBMaxit(PC pc, PetscInt maxit)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveInt(pc, maxit, 2);
PetscTryMethod(pc, "PCFieldSplitSetGKBMaxit_C", (PC, PetscInt), (pc, maxit));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetGKBMaxit_FieldSplit(PC pc, PetscInt maxit)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->gkbmaxit = maxit;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetGKBDelay - Sets the delay in the lower bound error estimate in the generalized Golub-Kahan bidiagonalization in `PCFIELDSPLIT`
preconditioner.
Collective
Input Parameters:
+ pc - the preconditioner context
- delay - the delay window in the lower bound estimate
Options Database Key:
. -pc_fieldsplit_gkb_delay - default is 5
Level: intermediate
Note:
The algorithm uses a lower bound estimate of the error in energy norm as stopping criterion. The lower bound of the error ||u-u^k||_H
is expressed as a truncated sum. The error at iteration k can only be measured at iteration (k + delay), and thus the algorithm needs
at least (delay + 1) iterations to stop. For more details on the generalized Golub-Kahan bidiagonalization method and its lower bound stopping criterion, please refer to
References:
[Ar13] Generalized Golub-Kahan bidiagonalization and stopping criteria, SIAM J. Matrix Anal. Appl., Vol. 34, No. 2, pp. 571-592, 2013.
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetGKBNu()`, `PCFieldSplitSetGKBTol()`, `PCFieldSplitSetGKBMaxit()`
@*/
PetscErrorCode PCFieldSplitSetGKBDelay(PC pc, PetscInt delay)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveInt(pc, delay, 2);
PetscTryMethod(pc, "PCFieldSplitSetGKBDelay_C", (PC, PetscInt), (pc, delay));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetGKBDelay_FieldSplit(PC pc, PetscInt delay)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->gkbdelay = delay;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetGKBNu - Sets the scalar value nu >= 0 in the transformation H = A00 + nu*A01*A01' of the (1,1) block in the Golub-Kahan bidiagonalization preconditioner
in `PCFIELDSPLIT`
Collective
Input Parameters:
+ pc - the preconditioner context
- nu - the shift parameter
Options Database Key:
. -pc_fieldsplit_gkb_nu - default is 1
Level: intermediate
Notes:
This shift is in general done to obtain better convergence properties for the outer loop of the algorithm. This is often achieved by choosing nu sufficiently big. However,
if nu is chosen too big, the matrix H might be badly conditioned and the solution of the linear system Hx = b in the inner loop becomes difficult. It is therefore
necessary to find a good balance in between the convergence of the inner and outer loop.
For nu = 0, no shift is done. In this case A00 has to be positive definite. The matrix N in [Ar13] is then chosen as identity.
References:
[Ar13] Generalized Golub-Kahan bidiagonalization and stopping criteria, SIAM J. Matrix Anal. Appl., Vol. 34, No. 2, pp. 571-592, 2013.
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetGKBDelay()`, `PCFieldSplitSetGKBTol()`, `PCFieldSplitSetGKBMaxit()`
@*/
PetscErrorCode PCFieldSplitSetGKBNu(PC pc, PetscReal nu)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveReal(pc, nu, 2);
PetscTryMethod(pc, "PCFieldSplitSetGKBNu_C", (PC, PetscReal), (pc, nu));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetGKBNu_FieldSplit(PC pc, PetscReal nu)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->gkbnu = nu;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetType_FieldSplit(PC pc, PCCompositeType type)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->type = type;
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurPre_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSchurPre_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurFactType_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurScale_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBTol_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBMaxit_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBNu_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBDelay_C", NULL));
if (type == PC_COMPOSITE_SCHUR) {
pc->ops->apply = PCApply_FieldSplit_Schur;
pc->ops->applytranspose = PCApplyTranspose_FieldSplit_Schur;
pc->ops->view = PCView_FieldSplit_Schur;
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", PCFieldSplitGetSubKSP_FieldSplit_Schur));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurPre_C", PCFieldSplitSetSchurPre_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSchurPre_C", PCFieldSplitGetSchurPre_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurFactType_C", PCFieldSplitSetSchurFactType_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetSchurScale_C", PCFieldSplitSetSchurScale_FieldSplit));
} else if (type == PC_COMPOSITE_GKB) {
pc->ops->apply = PCApply_FieldSplit_GKB;
pc->ops->view = PCView_FieldSplit_GKB;
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", PCFieldSplitGetSubKSP_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBTol_C", PCFieldSplitSetGKBTol_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBMaxit_C", PCFieldSplitSetGKBMaxit_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBNu_C", PCFieldSplitSetGKBNu_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetGKBDelay_C", PCFieldSplitSetGKBDelay_FieldSplit));
} else {
pc->ops->apply = PCApply_FieldSplit;
pc->ops->view = PCView_FieldSplit;
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", PCFieldSplitGetSubKSP_FieldSplit));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCFieldSplitSetBlockSize_FieldSplit(PC pc, PetscInt bs)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
PetscCheck(bs >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Blocksize must be positive, you gave %" PetscInt_FMT, bs);
PetscCheck(jac->bs <= 0 || jac->bs == bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Cannot change fieldsplit blocksize from %" PetscInt_FMT " to %" PetscInt_FMT " after it has been set", jac->bs, bs);
jac->bs = bs;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode PCSetCoordinates_FieldSplit(PC pc, PetscInt dim, PetscInt nloc, PetscReal coords[])
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PC_FieldSplitLink ilink_current = jac->head;
IS is_owned;
PetscFunctionBegin;
jac->coordinates_set = PETSC_TRUE; // Internal flag
PetscCall(MatGetOwnershipIS(pc->mat, &is_owned, NULL));
while (ilink_current) {
// For each IS, embed it to get local coords indces
IS is_coords;
PetscInt ndofs_block;
const PetscInt *block_dofs_enumeration; // Numbering of the dofs relevant to the current block
// Setting drop to true for safety. It should make no difference.
PetscCall(ISEmbed(ilink_current->is, is_owned, PETSC_TRUE, &is_coords));
PetscCall(ISGetLocalSize(is_coords, &ndofs_block));
PetscCall(ISGetIndices(is_coords, &block_dofs_enumeration));
// Allocate coordinates vector and set it directly
PetscCall(PetscMalloc1(ndofs_block * dim, &(ilink_current->coords)));
for (PetscInt dof = 0; dof < ndofs_block; ++dof) {
for (PetscInt d = 0; d < dim; ++d) (ilink_current->coords)[dim * dof + d] = coords[dim * block_dofs_enumeration[dof] + d];
}
ilink_current->dim = dim;
ilink_current->ndofs = ndofs_block;
PetscCall(ISRestoreIndices(is_coords, &block_dofs_enumeration));
PetscCall(ISDestroy(&is_coords));
ilink_current = ilink_current->next;
}
PetscCall(ISDestroy(&is_owned));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetType - Sets the type, `PCCompositeType`, of a `PCFIELDSPLIT`
Collective
Input Parameters:
+ pc - the preconditioner context
- type - `PC_COMPOSITE_ADDITIVE`, `PC_COMPOSITE_MULTIPLICATIVE` (default), `PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE`, `PC_COMPOSITE_SPECIAL`, `PC_COMPOSITE_SCHUR`
Options Database Key:
. -pc_fieldsplit_type <type: one of multiplicative, additive, symmetric_multiplicative, special, schur> - Sets fieldsplit preconditioner type
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCCompositeType`, `PCCompositeGetType()`, `PC_COMPOSITE_ADDITIVE`, `PC_COMPOSITE_MULTIPLICATIVE`,
`PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE`, `PC_COMPOSITE_SPECIAL`, `PC_COMPOSITE_SCHUR`
@*/
PetscErrorCode PCFieldSplitSetType(PC pc, PCCompositeType type)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscTryMethod(pc, "PCFieldSplitSetType_C", (PC, PCCompositeType), (pc, type));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitGetType - Gets the type, `PCCompositeType`, of a `PCFIELDSPLIT`
Not collective
Input Parameter:
. pc - the preconditioner context
Output Parameter:
. type - `PC_COMPOSITE_ADDITIVE`, `PC_COMPOSITE_MULTIPLICATIVE` (default), `PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE`, `PC_COMPOSITE_SPECIAL`, `PC_COMPOSITE_SCHUR`
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCCompositeSetType()`, `PCFIELDSPLIT`, `PCCompositeType`, `PC_COMPOSITE_ADDITIVE`, `PC_COMPOSITE_MULTIPLICATIVE`,
`PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE`, `PC_COMPOSITE_SPECIAL`, `PC_COMPOSITE_SCHUR`
@*/
PetscErrorCode PCFieldSplitGetType(PC pc, PCCompositeType *type)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(type, 2);
*type = jac->type;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetDMSplits - Flags whether `DMCreateFieldDecomposition()` should be used to define the splits in a `PCFIELDSPLIT`, whenever possible.
Logically Collective
Input Parameters:
+ pc - the preconditioner context
- flg - boolean indicating whether to use field splits defined by the `DM`
Options Database Key:
. -pc_fieldsplit_dm_splits <bool> - use the field splits defined by the `DM`
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitGetDMSplits()`, `PCFieldSplitSetFields()`, `PCFieldsplitSetIS()`
@*/
PetscErrorCode PCFieldSplitSetDMSplits(PC pc, PetscBool flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscValidLogicalCollectiveBool(pc, flg, 2);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
if (isfs) jac->dm_splits = flg;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitGetDMSplits - Returns flag indicating whether `DMCreateFieldDecomposition()` should be used to define the splits in a `PCFIELDSPLIT`, whenever possible.
Logically Collective
Input Parameter:
. pc - the preconditioner context
Output Parameter:
. flg - boolean indicating whether to use field splits defined by the `DM`
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetDMSplits()`, `PCFieldSplitSetFields()`, `PCFieldsplitSetIS()`
@*/
PetscErrorCode PCFieldSplitGetDMSplits(PC pc, PetscBool *flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscBool isfs;
PetscFunctionBegin;
PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
PetscAssertPointer(flg, 2);
PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &isfs));
if (isfs) {
if (flg) *flg = jac->dm_splits;
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitGetDetectSaddlePoint - Returns flag indicating whether `PCFIELDSPLIT` will attempt to automatically determine fields based on zero diagonal entries.
Logically Collective
Input Parameter:
. pc - the preconditioner context
Output Parameter:
. flg - boolean indicating whether to detect fields or not
Level: intermediate
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitSetDetectSaddlePoint()`
@*/
PetscErrorCode PCFieldSplitGetDetectSaddlePoint(PC pc, PetscBool *flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
*flg = jac->detect;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
PCFieldSplitSetDetectSaddlePoint - Sets flag indicating whether `PCFIELDSPLIT` will attempt to automatically determine fields based on zero diagonal entries.
Logically Collective
Input Parameter:
. pc - the preconditioner context
Output Parameter:
. flg - boolean indicating whether to detect fields or not
Options Database Key:
. -pc_fieldsplit_detect_saddle_point <bool> - detect and use the saddle point
Level: intermediate
Note:
Also sets the split type to `PC_COMPOSITE_SCHUR` (see `PCFieldSplitSetType()`) and the Schur preconditioner type to `PC_FIELDSPLIT_SCHUR_PRE_SELF` (see `PCFieldSplitSetSchurPre()`).
.seealso: [](sec_block_matrices), `PC`, `PCFIELDSPLIT`, `PCFieldSplitGetDetectSaddlePoint()`, `PCFieldSplitSetType()`, `PCFieldSplitSetSchurPre()`, `PC_FIELDSPLIT_SCHUR_PRE_SELF`
@*/
PetscErrorCode PCFieldSplitSetDetectSaddlePoint(PC pc, PetscBool flg)
{
PC_FieldSplit *jac = (PC_FieldSplit *)pc->data;
PetscFunctionBegin;
jac->detect = flg;
if (jac->detect) {
PetscCall(PCFieldSplitSetType(pc, PC_COMPOSITE_SCHUR));
PetscCall(PCFieldSplitSetSchurPre(pc, PC_FIELDSPLIT_SCHUR_PRE_SELF, NULL));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*MC
PCFIELDSPLIT - Preconditioner created by combining separate preconditioners for individual
collections of variables (that may overlap) called splits. See [the users manual section on "Solving Block Matrices"](sec_block_matrices) for more details.
Options Database Keys:
+ -pc_fieldsplit_%d_fields <a,b,..> - indicates the fields to be used in the `%d`'th split
. -pc_fieldsplit_default - automatically add any fields to additional splits that have not
been supplied explicitly by `-pc_fieldsplit_%d_fields`
. -pc_fieldsplit_block_size <bs> - size of block that defines fields (i.e. there are bs fields)
. -pc_fieldsplit_type <additive,multiplicative,symmetric_multiplicative,schur,gkb> - type of relaxation or factorization splitting
. -pc_fieldsplit_schur_precondition <self,selfp,user,a11,full> - default is `a11`; see `PCFieldSplitSetSchurPre()`
. -pc_fieldsplit_schur_fact_type <diag,lower,upper,full> - set factorization type when using `-pc_fieldsplit_type schur`; see `PCFieldSplitSetSchurFactType()`
- -pc_fieldsplit_detect_saddle_point - automatically finds rows with zero diagonal and uses Schur complement with no preconditioner as the solver
Options prefixes for inner solvers when using the Schur complement preconditioner are `-fieldsplit_0_` and `-fieldsplit_1_` .
The options prefix for the inner solver when using the Golub-Kahan biadiagonalization preconditioner is `-fieldsplit_0_`
For all other solvers they are `-fieldsplit_%d_` for the `%d`'th field; use `-fieldsplit_` for all fields.
To set options on the solvers for each block append `-fieldsplit_` to all the `PC`
options database keys. For example, `-fieldsplit_pc_type ilu` `-fieldsplit_pc_factor_levels 1`
To set the options on the solvers separate for each block call `PCFieldSplitGetSubKSP()`
and set the options directly on the resulting `KSP` object
Level: intermediate
Notes:
Use `PCFieldSplitSetFields()` to set splits defined by "strided" entries and `PCFieldSplitSetIS()`
to define a split by an arbitrary collection of entries.
If no splits are set the default is used. The splits are defined by entries strided by bs,
beginning at 0 then 1, etc to bs-1. The block size can be set with `PCFieldSplitSetBlockSize()`,
if this is not called the block size defaults to the blocksize of the second matrix passed
to `KSPSetOperators()`/`PCSetOperators()`.
For the Schur complement preconditioner if
```{math}
J = \left[\begin{array}{cc} A_{00} & A_{01} \\ A_{10} & A_{11} \end{array}\right]
```
the preconditioner using `full` factorization is logically
```{math}
\left[\begin{array}{cc} I & -\text{ksp}(A_{00}) \\ 0 & I \end{array}\right] \left[\begin{array}{cc} \text{inv}(A_{00}) & 0 \\ 0 & \text{ksp}(S) \end{array}\right] \left[\begin{array}{cc} I & 0 \\ -A_{10} \text{ksp}(A_{00}) & I \end{array}\right]
```
where the action of $\text{inv}(A_{00})$ is applied using the KSP solver with prefix `-fieldsplit_0_`. $S$ is the Schur complement
```{math}
S = A_{11} - A_{10} \text{ksp}(A_{00}) A_{01}
```
which is usually dense and not stored explicitly. The action of $\text{ksp}(S)$ is computed using the KSP solver with prefix `-fieldsplit_splitname_` (where `splitname` was given
in providing the SECOND split or 1 if not given). For `PCFieldSplitGetSubKSP()` when field number is 0,
it returns the KSP associated with `-fieldsplit_0_` while field number 1 gives `-fieldsplit_1_` KSP. By default
$A_{11}$ is used to construct a preconditioner for $S$, use `PCFieldSplitSetSchurPre()` for all the possible ways to construct the preconditioner for $S$.
The factorization type is set using `-pc_fieldsplit_schur_fact_type <diag, lower, upper, full>`. `full` is shown above,
`diag` gives
```{math}
\left[\begin{array}{cc} \text{inv}(A_{00}) & 0 \\ 0 & -\text{ksp}(S) \end{array}\right]
```
Note that, slightly counter intuitively, there is a negative in front of the $\text{ksp}(S)$ so that the preconditioner is positive definite. For SPD matrices $J$, the sign flip
can be turned off with `PCFieldSplitSetSchurScale()` or by command line `-pc_fieldsplit_schur_scale 1.0`. The `lower` factorization is the inverse of
```{math}
\left[\begin{array}{cc} A_{00} & 0 \\ A_{10} & S \end{array}\right]
```
where the inverses of A_{00} and S are applied using KSPs. The upper factorization is the inverse of
```{math}
\left[\begin{array}{cc} A_{00} & A_{01} \\ 0 & S \end{array}\right]
```
where again the inverses of $A_{00}$ and $S$ are applied using `KSP`s.
If only one set of indices (one `IS`) is provided with `PCFieldSplitSetIS()` then the complement of that `IS`
is used automatically for a second block.
The fieldsplit preconditioner cannot currently be used with the `MATBAIJ` or `MATSBAIJ` data formats if the blocksize is larger than 1.
Generally it should be used with the `MATAIJ` format.
The forms of these preconditioners are closely related if not identical to forms derived as "Distributive Iterations", see,
for example, page 294 in "Principles of Computational Fluid Dynamics" by Pieter Wesseling {cite}`Wesseling2009`.
One can also use `PCFIELDSPLIT`
inside a smoother resulting in "Distributive Smoothers".
See "A taxonomy and comparison of parallel block multi-level preconditioners for the incompressible Navier-Stokes equations" {cite}`elman2008tcp`.
The Constrained Pressure Preconditioner (CPR) can be implemented using `PCCOMPOSITE` with `PCGALERKIN`. CPR first solves an $R A P$ subsystem, updates the
residual on all variables (`PCCompositeSetType(pc,PC_COMPOSITE_MULTIPLICATIVE)`), and then applies a simple ILU like preconditioner on all the variables.
The generalized Golub-Kahan bidiagonalization preconditioner (GKB) can be applied to symmetric $2 \times 2$ block matrices of the shape
```{math}
\left[\begin{array}{cc} A_{00} & A_{01} \\ A_{01}' & 0 \end{array}\right]
```
with $A_{00}$ positive semi-definite. The implementation follows {cite}`Arioli2013`. Therein, we choose $N := 1/\nu * I$ and the $(1,1)$-block of the matrix is modified to $H = _{A00} + \nu*A_{01}*A_{01}'$.
A linear system $Hx = b$ has to be solved in each iteration of the GKB algorithm. This solver is chosen with the option prefix `-fieldsplit_0_`.
Developer Note:
The Schur complement functionality of `PCFIELDSPLIT` should likely be factored into its own `PC` thus simplifying the implementation of the preconditioners and their
user API.
References:
```{bibliography}
:filter: docname in docnames
```
.seealso: [](sec_block_matrices), `PC`, `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCLSC`,
`PCFieldSplitGetSubKSP()`, `PCFieldSplitSchurGetSubKSP()`, `PCFieldSplitSetFields()`,
`PCFieldSplitSetType()`, `PCFieldSplitSetIS()`, `PCFieldSplitSetSchurPre()`, `PCFieldSplitSetSchurFactType()`,
`MatSchurComplementSetAinvType()`, `PCFieldSplitSetSchurScale()`, `PCFieldSplitSetDetectSaddlePoint()`
M*/
PETSC_EXTERN PetscErrorCode PCCreate_FieldSplit(PC pc)
{
PC_FieldSplit *jac;
PetscFunctionBegin;
PetscCall(PetscNew(&jac));
jac->bs = -1;
jac->nsplits = 0;
jac->type = PC_COMPOSITE_MULTIPLICATIVE;
jac->schurpre = PC_FIELDSPLIT_SCHUR_PRE_USER; /* Try user preconditioner first, fall back on diagonal */
jac->schurfactorization = PC_FIELDSPLIT_SCHUR_FACT_FULL;
jac->schurscale = -1.0;
jac->dm_splits = PETSC_TRUE;
jac->detect = PETSC_FALSE;
jac->gkbtol = 1e-5;
jac->gkbdelay = 5;
jac->gkbnu = 1;
jac->gkbmaxit = 100;
jac->gkbmonitor = PETSC_FALSE;
jac->coordinates_set = PETSC_FALSE;
pc->data = (void *)jac;
pc->ops->apply = PCApply_FieldSplit;
pc->ops->applytranspose = PCApplyTranspose_FieldSplit;
pc->ops->setup = PCSetUp_FieldSplit;
pc->ops->reset = PCReset_FieldSplit;
pc->ops->destroy = PCDestroy_FieldSplit;
pc->ops->setfromoptions = PCSetFromOptions_FieldSplit;
pc->ops->view = PCView_FieldSplit;
pc->ops->applyrichardson = NULL;
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSchurGetSubKSP_C", PCFieldSplitSchurGetSubKSP_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitGetSubKSP_C", PCFieldSplitGetSubKSP_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetFields_C", PCFieldSplitSetFields_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetIS_C", PCFieldSplitSetIS_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetType_C", PCFieldSplitSetType_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitSetBlockSize_C", PCFieldSplitSetBlockSize_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCFieldSplitRestrictIS_C", PCFieldSplitRestrictIS_FieldSplit));
PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", PCSetCoordinates_FieldSplit));
PetscFunctionReturn(PETSC_SUCCESS);
}
|
26edf4e2185689db49ffd941c51e57e8e808da15
|
7e41167bfae6d2c38689b7e0993b308e045cbd05
|
/shell_cmds/kill/kill.c
|
258f691dbc9525bb292797d2ceb29905056c9c95
|
[
"BSD-3-Clause",
"curl",
"GPL-1.0-or-later",
"MIT",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
holzschu/ios_system
|
7b18993dbcb33331c353e0257ca54847a5d1b1bb
|
6a83eb1c6c383a562fbe33a7e97677e88d305b51
|
refs/heads/master
| 2023-08-14T09:11:40.627903
| 2023-04-18T15:12:29
| 2023-04-18T15:12:29
| 113,187,304
| 882
| 155
|
BSD-3-Clause
| 2023-08-19T19:15:35
| 2017-12-05T13:42:50
|
C
|
UTF-8
|
C
| false
| false
| 5,032
|
c
|
kill.c
|
/*-
* Copyright (c) 1988, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Important: This file is used both as a standalone program /bin/kill and
* as a builtin for /bin/sh (#define SHELL).
*/
#if 0
#ifndef lint
static char const copyright[] =
"@(#) Copyright (c) 1988, 1993, 1994\n\
The Regents of the University of California. All rights reserved.\n";
#endif /* not lint */
#ifndef lint
static char sccsid[] = "@(#)kill.c 8.4 (Berkeley) 4/28/95";
#endif /* not lint */
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef SHELL
#define main killcmd
#include "bltin/bltin.h"
#endif
static void nosig(const char *);
static void printsignals(FILE *);
static int signame_to_signum(const char *);
static void usage(void);
#ifdef __APPLE__
#define sys_nsig NSIG
#endif /* __APPLE__ */
int
main(int argc, char *argv[])
{
int errors, numsig, pid, ret;
char *ep;
if (argc < 2)
usage();
numsig = SIGTERM;
argc--, argv++;
if (!strcmp(*argv, "-l")) {
argc--, argv++;
if (argc > 1)
usage();
if (argc == 1) {
if (!isdigit(**argv))
usage();
numsig = strtol(*argv, &ep, 10);
if (!**argv || *ep)
errx(2, "illegal signal number: %s", *argv);
if (numsig >= 128)
numsig -= 128;
if (numsig <= 0 || numsig >= sys_nsig)
nosig(*argv);
printf("%s\n", sys_signame[numsig]);
return (0);
}
printsignals(stdout);
return (0);
}
if (!strcmp(*argv, "-s")) {
argc--, argv++;
if (argc < 1) {
warnx("option requires an argument -- s");
usage();
}
if (strcmp(*argv, "0")) {
if ((numsig = signame_to_signum(*argv)) < 0)
nosig(*argv);
} else
numsig = 0;
argc--, argv++;
} else if (**argv == '-' && *(*argv + 1) != '-') {
++*argv;
if (isalpha(**argv)) {
if ((numsig = signame_to_signum(*argv)) < 0)
nosig(*argv);
} else if (isdigit(**argv)) {
numsig = strtol(*argv, &ep, 10);
if (!**argv || *ep)
errx(2, "illegal signal number: %s", *argv);
if (numsig < 0)
nosig(*argv);
} else
nosig(*argv);
argc--, argv++;
}
if (argc > 0 && strncmp(*argv, "--", 2) == 0)
argc--, argv++;
if (argc == 0)
usage();
for (errors = 0; argc; argc--, argv++) {
#ifdef SHELL
if (**argv == '%')
ret = killjob(*argv, numsig);
else
#endif
{
pid = strtol(*argv, &ep, 10);
if (!**argv || *ep)
errx(2, "illegal process id: %s", *argv);
ret = kill(pid, numsig);
}
if (ret == -1) {
warn("%s", *argv);
errors = 1;
}
}
return (errors);
}
static int
signame_to_signum(const char *sig)
{
int n;
if (strncasecmp(sig, "SIG", 3) == 0)
sig += 3;
for (n = 1; n < sys_nsig; n++) {
if (!strcasecmp(sys_signame[n], sig))
return (n);
}
return (-1);
}
static void
nosig(const char *name)
{
warnx("unknown signal %s; valid signals:", name);
printsignals(stderr);
#ifdef SHELL
error(NULL);
#else
exit(2);
#endif
}
static void
printsignals(FILE *fp)
{
int n;
for (n = 1; n < sys_nsig; n++) {
(void)fprintf(fp, "%s", sys_signame[n]);
if (n == (sys_nsig / 2) || n == (sys_nsig - 1))
(void)fprintf(fp, "\n");
else
(void)fprintf(fp, " ");
}
}
static void
usage(void)
{
(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
"usage: kill [-s signal_name] pid ...",
" kill -l [exit_status]",
" kill -signal_name pid ...",
" kill -signal_number pid ...");
#ifdef SHELL
error(NULL);
#else
exit(2);
#endif
}
|
cb7c2483f2b78fff0f9de3f6bbb244016feeec35
|
b732361d6b3405c3e79ac0a7d8361cf5b329b015
|
/ext/phalcon/db/columninterface.zep.c
|
fab33a72bf8b8a0c3466971137a64e1061ef33ed
|
[
"BSD-3-Clause"
] |
permissive
|
phalcon/cphalcon
|
4a5b26f47b5c2a4107541d7fd73c595c0d90ed73
|
fc183e11e8b96c43daf7d893244846206dc2aa73
|
refs/heads/master
| 2023-03-07T22:09:48.814291
| 2023-02-28T16:45:15
| 2023-02-28T16:45:15
| 2,854,337
| 8,135
| 2,343
|
BSD-3-Clause
| 2023-09-12T12:41:13
| 2011-11-26T05:52:50
|
PHP
|
UTF-8
|
C
| false
| true
| 2,270
|
c
|
columninterface.zep.c
|
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif
#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"
#include <Zend/zend_exceptions.h>
#include "kernel/main.h"
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalcon.io>
*
* For the full copyright and license information, please view the
* LICENSE.txt file that was distributed with this source code.
*/
/**
* Interface for Phalcon\Db\Column
*/
ZEPHIR_INIT_CLASS(Phalcon_Db_ColumnInterface)
{
ZEPHIR_REGISTER_INTERFACE(Phalcon\\Db, ColumnInterface, phalcon, db_columninterface, phalcon_db_columninterface_method_entry);
return SUCCESS;
}
/**
* Check whether field absolute to position in table
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getAfterPosition);
/**
* Returns the type of bind handling
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getBindType);
/**
* Returns default value of column
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getDefault);
/**
* Returns column name
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getName);
/**
* Returns column scale
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getScale);
/**
* Returns column size
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getSize);
/**
* Returns column type
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getType);
/**
* Returns column type reference
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getTypeReference);
/**
* Returns column type values
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, getTypeValues);
/**
* Check whether column has default value
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, hasDefault);
/**
* Auto-Increment
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isAutoIncrement);
/**
* Check whether column have first position in table
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isFirst);
/**
* Not null
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isNotNull);
/**
* Check whether column have an numeric type
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isNumeric);
/**
* Column is part of the primary key?
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isPrimary);
/**
* Returns true if number column is unsigned
*/
ZEPHIR_DOC_METHOD(Phalcon_Db_ColumnInterface, isUnsigned);
|
54919e8200e1b312d062045de930c338abdf53f9
|
7be8e3636bf08ebdc6662879dc5afec548705537
|
/ios/Pods/Headers/Private/Flipper-Folly/folly/synchronization/detail/Sleeper.h
|
40e9658de03a43444dbfa7020b535f3d05039ca9
|
[
"MIT"
] |
permissive
|
rdhox/react-native-smooth-picker
|
3c7384f1fed0e37f076361cce96071d01b70e209
|
ae9316c49512f7ed9824c5a3ad50cdf5e80fffa9
|
refs/heads/master
| 2023-01-08T16:59:40.709147
| 2021-07-03T14:13:21
| 2021-07-03T14:13:21
| 160,224,312
| 230
| 31
|
MIT
| 2023-01-06T01:46:04
| 2018-12-03T16:54:10
|
TypeScript
|
UTF-8
|
C
| false
| false
| 70
|
h
|
Sleeper.h
|
../../../../../../Flipper-Folly/folly/synchronization/detail/Sleeper.h
|
2e55c017c183e7db18bdd9daa54765bb98d44d5c
|
ca414d0345d2d1486da1126960a164a655965968
|
/src/sys/tss.h
|
a7fc3eb00e713d70c67f59df4ea66383acf8841e
|
[] |
permissive
|
Menotdan/DripOS
|
6d2ee8fbd87145d789fbe5781e2f6ae825a5aba6
|
2a3110338e84a8a14f1e9217cea2082de888189c
|
refs/heads/dev
| 2023-07-20T01:50:26.166067
| 2023-05-26T02:59:52
| 2023-05-26T02:59:52
| 149,795,128
| 119
| 15
|
MIT
| 2020-03-26T20:43:19
| 2018-09-21T17:21:05
|
C
|
UTF-8
|
C
| false
| false
| 1,304
|
h
|
tss.h
|
#ifndef TSS_H
#define TSS_H
#include <stdint.h>
#define TSS_GDT_OFFSET 0x30
typedef struct {
uint32_t reserved;
uint64_t rsp0;
uint64_t rsp1;
uint64_t rsp2;
uint32_t reserved_1;
uint32_t reserved_2;
uint64_t ist_stack1;
uint64_t ist_stack2;
uint64_t ist_stack3;
uint64_t ist_stack4;
uint64_t ist_stack5;
uint64_t ist_stack6;
uint64_t ist_stack7;
uint64_t reserved_3;
uint16_t reserved_4;
uint16_t io_bitmap_offset;
} __attribute__((packed)) tss_64_t;
typedef struct {
uint32_t segment_limit_low : 16;
uint32_t segment_base_low : 16;
uint32_t segment_base_mid : 8;
uint32_t segment_type : 4;
uint32_t zero_1 : 1;
uint32_t segment_dpl : 2;
uint32_t segment_present : 1;
uint32_t segment_limit_high : 4;
uint32_t segment_avail : 1;
uint32_t zero_2 : 2;
uint32_t segment_gran : 1;
uint32_t segment_base_mid2 : 8;
uint32_t segment_base_high : 32;
uint32_t reserved_1 : 8;
uint32_t zero_3 : 5;
uint32_t reserved_2 : 19;
} __attribute__((packed)) tss_64_descriptor_t;
void load_tss();
void set_kernel_stack(uint64_t new_stack_addr);
void set_panic_stack(uint64_t panic_stack_addr);
#endif
|
70f139dfd534dfd7a41a0619722b84cb1808ba8f
|
c26d7b0ed875357278e61627da2da0650da77986
|
/src/cmd/adb/main.c
|
96fda2adfc2b1029a82ca52d85fe1164f8446835
|
[
"BSD-3-Clause"
] |
permissive
|
RetroBSD/retrobsd
|
5343d9e3c424637fc3ad5b03fe720b2744490025
|
486f81f6abff01c7dcc207235cd2979b226a95ff
|
refs/heads/master
| 2023-09-02T23:12:05.110883
| 2023-07-07T18:41:40
| 2023-07-07T18:41:40
| 18,598,087
| 282
| 59
|
BSD-3-Clause
| 2023-07-18T07:35:36
| 2014-04-09T13:25:46
|
C
|
UTF-8
|
C
| false
| false
| 2,931
|
c
|
main.c
|
#include "defs.h"
#include <fcntl.h>
char *Ipath = "/share/adb";
static int exitflg;
long
roundn(a, b)
long a, b;
{
long w;
w = ((a + b - 1) / b) * b;
return w;
}
/*
* error handling
*/
void
chkerr()
{
if (errflg || mkfault)
error(errflg);
}
void
error(msg)
const char *msg;
{
errflg = msg;
iclose(0, 1);
oclose();
longjmp(erradb, 1);
}
void
fault(a)
{
signal(a, fault);
lseek(infile, 0L, 2);
mkfault++;
}
/*
* set up files and initial address mappings
*/
int
main(argc, argv)
register char **argv;
int argc;
{
short mynamelen; /* length of program name */
maxfile = 1L << 24;
if (isatty(0))
myname = *argv;
else
myname = "adb";
mynamelen = strlen(myname);
#ifdef TIOCGETP
ioctl(0, TIOCGETP, &adbtty);
ioctl(0, TIOCGETP, &usrtty);
#else
tcgetattr(0, &adbtty);
tcgetattr(0, &usrtty);
#endif
while (argc > 1) {
if (strcmp("-w", argv[1]) == 0) {
wtflag = O_RDWR;
argc--;
argv++;
continue;
}
if (strcmp("-k", argv[1]) == 0) {
kernel++;
argc--;
argv++;
continue;
}
if (strcmp("-I", argv[1]) == 0) {
Ipath = argv[2];
argc -= 2;
argv += 2;
continue;
}
break;
}
if (argc > 1) {
symfil = argv[1];
}
if (argc > 2) {
corfil = argv[2];
}
argcount = argc;
setsym();
setcor();
/* set up variables for user */
maxoff = MAXOFF;
maxpos = MAXPOS;
var[VARB] = datbas;
var[VARD] = datsiz;
var[VARE] = entrypt;
var[VARM] = magic;
var[VARS] = stksiz;
var[VART] = txtsiz;
sigint = signal(SIGINT, SIG_IGN);
if (sigint != SIG_IGN) {
sigint = fault;
signal(SIGINT, fault);
}
sigqit = signal(SIGQUIT, SIG_IGN);
siginterrupt(SIGINT, 1);
siginterrupt(SIGQUIT, 1);
setjmp(erradb);
if (executing) {
delbp();
}
executing = FALSE;
for (;;) {
flushbuf();
if (errflg) {
print("%s\n", errflg);
exitflg = (errflg != 0);
errflg = 0;
}
if (mkfault) {
mkfault = 0;
printc(EOR);
print("%s\n", myname);
}
if (myname && ! infile) {
write(1, myname, mynamelen);
write(1, "> ", 2);
}
lp = 0;
rdc();
lp--;
if (eof) {
if (infile) {
iclose(-1, 0);
eof = 0;
longjmp(erradb, 1);
}
done();
} else {
exitflg = 0;
}
command(0, lastcom);
if (lp && lastc != EOR) {
error(NOEOR);
}
}
}
void
done()
{
endpcs();
exit(exitflg);
}
|
53cc9ae78b407a961a1c88422de776fe6556c72c
|
bb82a5f977bef455714c16e24e2d8254e2d0faa5
|
/src/vendor/duktape-2.7.0/src-input/duk_util_bitdecoder.c
|
6651993cc1ad3a09b502a2163141dc86a13ae252
|
[
"Unlicense",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
pqrs-org/Karabiner-Elements
|
4ae307d82f8b67547c161c7d46d2083a0fd07630
|
d05057d7c769e2ff35638282e888a6d5eca566be
|
refs/heads/main
| 2023-09-01T03:11:08.474417
| 2023-09-01T00:44:19
| 2023-09-01T00:44:19
| 63,037,806
| 8,197
| 389
|
Unlicense
| 2023-09-01T00:11:00
| 2016-07-11T04:57:55
|
C++
|
UTF-8
|
C
| false
| false
| 5,111
|
c
|
duk_util_bitdecoder.c
|
/*
* Bitstream decoder.
*/
#include "duk_internal.h"
/* Decode 'bits' bits from the input stream (bits must be 1...24).
* When reading past bitstream end, zeroes are shifted in. The result
* is signed to match duk_bd_decode_flagged.
*/
DUK_INTERNAL duk_uint32_t duk_bd_decode(duk_bitdecoder_ctx *ctx, duk_small_int_t bits) {
duk_small_int_t shift;
duk_uint32_t mask;
duk_uint32_t tmp;
/* Note: cannot read more than 24 bits without possibly shifting top bits out.
* Fixable, but adds complexity.
*/
DUK_ASSERT(bits >= 1 && bits <= 24);
while (ctx->currbits < bits) {
#if 0
DUK_DDD(DUK_DDDPRINT("decode_bits: shift more data (bits=%ld, currbits=%ld)",
(long) bits, (long) ctx->currbits));
#endif
ctx->currval <<= 8;
if (ctx->offset < ctx->length) {
/* If ctx->offset >= ctx->length, we "shift zeroes in"
* instead of croaking.
*/
ctx->currval |= ctx->data[ctx->offset++];
}
ctx->currbits += 8;
}
#if 0
DUK_DDD(DUK_DDDPRINT("decode_bits: bits=%ld, currbits=%ld, currval=0x%08lx",
(long) bits, (long) ctx->currbits, (unsigned long) ctx->currval));
#endif
/* Extract 'top' bits of currval; note that the extracted bits do not need
* to be cleared, we just ignore them on next round.
*/
shift = ctx->currbits - bits;
mask = (((duk_uint32_t) 1U) << bits) - 1U;
tmp = (ctx->currval >> shift) & mask;
ctx->currbits = shift; /* remaining */
#if 0
DUK_DDD(DUK_DDDPRINT("decode_bits: %ld bits -> 0x%08lx (%ld), currbits=%ld, currval=0x%08lx",
(long) bits, (unsigned long) tmp, (long) tmp, (long) ctx->currbits, (unsigned long) ctx->currval));
#endif
return tmp;
}
DUK_INTERNAL duk_small_uint_t duk_bd_decode_flag(duk_bitdecoder_ctx *ctx) {
return (duk_small_uint_t) duk_bd_decode(ctx, 1);
}
/* Decode a one-bit flag, and if set, decode a value of 'bits', otherwise return
* default value.
*/
DUK_INTERNAL duk_uint32_t duk_bd_decode_flagged(duk_bitdecoder_ctx *ctx, duk_small_int_t bits, duk_uint32_t def_value) {
if (duk_bd_decode_flag(ctx)) {
return duk_bd_decode(ctx, bits);
} else {
return def_value;
}
}
/* Signed variant, allows negative marker value. */
DUK_INTERNAL duk_int32_t duk_bd_decode_flagged_signed(duk_bitdecoder_ctx *ctx, duk_small_int_t bits, duk_int32_t def_value) {
return (duk_int32_t) duk_bd_decode_flagged(ctx, bits, (duk_uint32_t) def_value);
}
/* Shared varint encoding. Match dukutil.py BitEncode.varuint(). */
DUK_INTERNAL duk_uint32_t duk_bd_decode_varuint(duk_bitdecoder_ctx *ctx) {
duk_small_uint_t t;
/* The bit encoding choices here are based on manual testing against
* the actual varuints generated by genbuiltins.py.
*/
switch (duk_bd_decode(ctx, 2)) {
case 0:
return 0; /* [0,0] */
case 1:
return duk_bd_decode(ctx, 2) + 1; /* [1,4] */
case 2:
return duk_bd_decode(ctx, 5) + 5; /* [5,36] */
default:
t = duk_bd_decode(ctx, 7);
if (t == 0) {
return duk_bd_decode(ctx, 20);
}
return (t - 1) + 37; /* [37,163] */
}
}
/* Decode a bit packed string from a custom format used by genbuiltins.py.
* This function is here because it's used for both heap and thread inits.
* Caller must supply the output buffer whose size is NOT checked!
*/
#define DUK__BITPACK_LETTER_LIMIT 26
#define DUK__BITPACK_LOOKUP1 26
#define DUK__BITPACK_LOOKUP2 27
#define DUK__BITPACK_SWITCH1 28
#define DUK__BITPACK_SWITCH 29
#define DUK__BITPACK_UNUSED1 30
#define DUK__BITPACK_EIGHTBIT 31
DUK_LOCAL const duk_uint8_t duk__bitpacked_lookup[16] = { DUK_ASC_0, DUK_ASC_1, DUK_ASC_2, DUK_ASC_3,
DUK_ASC_4, DUK_ASC_5, DUK_ASC_6, DUK_ASC_7,
DUK_ASC_8, DUK_ASC_9, DUK_ASC_UNDERSCORE, DUK_ASC_SPACE,
0x82, 0x80, DUK_ASC_DOUBLEQUOTE, DUK_ASC_LCURLY };
DUK_INTERNAL duk_small_uint_t duk_bd_decode_bitpacked_string(duk_bitdecoder_ctx *bd, duk_uint8_t *out) {
duk_small_uint_t len;
duk_small_uint_t mode;
duk_small_uint_t t;
duk_small_uint_t i;
len = duk_bd_decode(bd, 5);
if (len == 31) {
len = duk_bd_decode(bd, 8); /* Support up to 256 bytes; rare. */
}
mode = 32; /* 0 = uppercase, 32 = lowercase (= 'a' - 'A') */
for (i = 0; i < len; i++) {
t = duk_bd_decode(bd, 5);
if (t < DUK__BITPACK_LETTER_LIMIT) {
t = t + DUK_ASC_UC_A + mode;
} else if (t == DUK__BITPACK_LOOKUP1) {
t = duk__bitpacked_lookup[duk_bd_decode(bd, 3)];
} else if (t == DUK__BITPACK_LOOKUP2) {
t = duk__bitpacked_lookup[8 + duk_bd_decode(bd, 3)];
} else if (t == DUK__BITPACK_SWITCH1) {
t = duk_bd_decode(bd, 5);
DUK_ASSERT_DISABLE(t >= 0); /* unsigned */
DUK_ASSERT(t <= 25);
t = t + DUK_ASC_UC_A + (mode ^ 32);
} else if (t == DUK__BITPACK_SWITCH) {
mode = mode ^ 32;
t = duk_bd_decode(bd, 5);
DUK_ASSERT_DISABLE(t >= 0);
DUK_ASSERT(t <= 25);
t = t + DUK_ASC_UC_A + mode;
} else if (t == DUK__BITPACK_EIGHTBIT) {
t = duk_bd_decode(bd, 8);
}
out[i] = (duk_uint8_t) t;
}
return len;
}
|
34d4130d265d02e8b65078992415faf3fe5448db
|
e51d227e06363817463efa2650e97d07290aed34
|
/src/Cedar/Layer3.h
|
3e0dd690b3c2e53fcd1468ab895d17eb1e7f693f
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
SoftEtherVPN/SoftEtherVPN_Stable
|
21426b5fdcf3b518be5d9174441192450e54e836
|
89939eb52f1f40e4f75c76e8d5eca019de103532
|
refs/heads/master
| 2023-08-08T09:51:40.139112
| 2023-06-30T03:19:06
| 2023-06-30T03:19:06
| 107,487,278
| 1,710
| 553
|
Apache-2.0
| 2023-06-24T02:56:31
| 2017-10-19T02:19:51
|
C
|
UTF-8
|
C
| false
| false
| 9,489
|
h
|
Layer3.h
|
// SoftEther VPN Source Code - Stable Edition Repository
// Cedar Communication Module
//
// SoftEther VPN Server, Client and Bridge are free software under the Apache License, Version 2.0.
//
// Copyright (c) Daiyuu Nobori.
// Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan.
// Copyright (c) SoftEther Corporation.
// Copyright (c) all contributors on SoftEther VPN project in GitHub.
//
// All Rights Reserved.
//
// http://www.softether.org/
//
// This stable branch is officially managed by Daiyuu Nobori, the owner of SoftEther VPN Project.
// Pull requests should be sent to the Developer Edition Master Repository on https://github.com/SoftEtherVPN/SoftEtherVPN
//
// License: The Apache License, Version 2.0
// https://www.apache.org/licenses/LICENSE-2.0
//
// DISCLAIMER
// ==========
//
// 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.
//
// THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
// JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
// DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
// JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
// AGAINST US (SOFTETHER PROJECT, SOFTETHER CORPORATION, DAIYUU NOBORI OR OTHER
// SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
// OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
// AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
// CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
// JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
// ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
// PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
// LAW OR COURT RULE.
//
// USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS YOU HAVE
// A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY CRIMINAL LAWS OR CIVIL
// RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS SOFTWARE IN OTHER COUNTRIES IS
// COMPLETELY AT YOUR OWN RISK. THE SOFTETHER VPN PROJECT HAS DEVELOPED AND
// DISTRIBUTED THIS SOFTWARE TO COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING
// CIVIL RIGHTS INCLUDING PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER
// COUNTRIES' LAWS OR CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES.
// WE HAVE NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
// INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ COUNTRIES
// AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE WORLD, WITH
// DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY COUNTRIES' LAWS, REGULATIONS
// AND CIVIL RIGHTS TO MAKE THE SOFTWARE COMPLY WITH ALL COUNTRIES' LAWS BY THE
// PROJECT. EVEN IF YOU WILL BE SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A
// PUBLIC SERVANT IN YOUR COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE
// LIABLE TO RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
// RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT JUST A
// STATEMENT FOR WARNING AND DISCLAIMER.
//
// READ AND UNDERSTAND THE 'WARNING.TXT' FILE BEFORE USING THIS SOFTWARE.
// SOME SOFTWARE PROGRAMS FROM THIRD PARTIES ARE INCLUDED ON THIS SOFTWARE WITH
// LICENSE CONDITIONS WHICH ARE DESCRIBED ON THE 'THIRD_PARTY.TXT' FILE.
//
//
// SOURCE CODE CONTRIBUTION
// ------------------------
//
// Your contribution to SoftEther VPN Project is much appreciated.
// Please send patches to us through GitHub.
// Read the SoftEther VPN Patch Acceptance Policy in advance:
// http://www.softether.org/5-download/src/9.patch
//
//
// DEAR SECURITY EXPERTS
// ---------------------
//
// If you find a bug or a security vulnerability please kindly inform us
// about the problem immediately so that we can fix the security problem
// to protect a lot of users around the world as soon as possible.
//
// Our e-mail address for security reports is:
// softether-vpn-security [at] softether.org
//
// Please note that the above e-mail address is not a technical support
// inquiry address. If you need technical assistance, please visit
// http://www.softether.org/ and ask your question on the users forum.
//
// Thank you for your cooperation.
//
//
// NO MEMORY OR RESOURCE LEAKS
// ---------------------------
//
// The memory-leaks and resource-leaks verification under the stress
// test has been passed before release this source code.
// Layer3.h
// Header of Layer3.c
#ifndef LAYER3_H
#define LAYER3_H
// Constants
#define L3_USERNAME "L3SW_"
// L3 ARP table entry
struct L3ARPENTRY
{
UINT IpAddress; // IP address
UCHAR MacAddress[6]; // MAC address
UCHAR Padding[2];
UINT64 Expire; // Expiration date
};
// L3 ARP resolution waiting list entry
struct L3ARPWAIT
{
UINT IpAddress; // IP address
UINT64 LastSentTime; // Time which the data has been sent last
UINT64 Expire; // Expiration date
};
// L3 IP packet table
struct L3PACKET
{
PKT *Packet; // Packet data body
UINT64 Expire; // Expiration date
UINT NextHopIp; // Local delivery destination IP address
};
// L3 routing table definition
struct L3TABLE
{
UINT NetworkAddress; // Network address
UINT SubnetMask; // Subnet mask
UINT GatewayAddress; // Gateway address
UINT Metric; // Metric
};
// L3 interface definition
struct L3IF
{
L3SW *Switch; // Layer-3 switch
char HubName[MAX_HUBNAME_LEN + 1]; // Virtual HUB name
UINT IpAddress; // IP address
UINT SubnetMask; // Subnet mask
HUB *Hub; // Virtual HUB
SESSION *Session; // Session
LIST *ArpTable; // ARP table
LIST *ArpWaitTable; // ARP waiting table
QUEUE *IpPacketQueue; // IP packet queue (for reception from other interfaces)
LIST *IpWaitList; // IP waiting list
QUEUE *SendQueue; // Transmission queue
UCHAR MacAddress[6]; // MAC address
UCHAR Padding[2];
UINT64 LastDeleteOldArpTable; // Time that old ARP table entries are cleared
LIST *CancelList; // Cancellation list
UINT64 LastBeaconSent; // Time which the beacon has been sent last
};
// L3 switch definition
struct L3SW
{
char Name[MAX_HUBNAME_LEN + 1]; // Name
LOCK *lock; // Lock
REF *ref; // Reference counter
CEDAR *Cedar; // Cedar
bool Active; // During operation flag
bool Online; // Online flag
volatile bool Halt; // Halting flag
LIST *IfList; // Interface list
LIST *TableList; // Routing table list
THREAD *Thread; // Thread
};
// Function prototype
int CmpL3Sw(void *p1, void *p2);
int CmpL3ArpEntry(void *p1, void *p2);
int CmpL3ArpWaitTable(void *p1, void *p2);
int CmpL3Table(void *p1, void *p2);
int CmpL3If(void *p1, void *p2);
void InitCedarLayer3(CEDAR *c);
void FreeCedarLayer3(CEDAR *c);
L3SW *NewL3Sw(CEDAR *c, char *name);
void ReleaseL3Sw(L3SW *s);
void CleanupL3Sw(L3SW *s);
bool L3AddIf(L3SW *s, char *hubname, UINT ip, UINT subnet);
bool L3DelIf(L3SW *s, char *hubname);
bool L3AddTable(L3SW *s, L3TABLE *tbl);
bool L3DelTable(L3SW *s, L3TABLE *tbl);
L3IF *L3SearchIf(L3SW *s, char *hubname);
L3SW *L3GetSw(CEDAR *c, char *name);
L3SW *L3AddSw(CEDAR *c, char *name);
bool L3DelSw(CEDAR *c, char *name);
void L3FreeAllSw(CEDAR *c);
void L3SwStart(L3SW *s);
void L3SwStop(L3SW *s);
void L3SwThread(THREAD *t, void *param);
void L3Test(SERVER *s);
void L3InitAllInterfaces(L3SW *s);
void L3FreeAllInterfaces(L3SW *s);
void L3IfThread(THREAD *t, void *param);
void L3InitInterface(L3IF *f);
void L3FreeInterface(L3IF *f);
L3IF *L3GetNextIf(L3SW *s, UINT ip, UINT *next_hop);
L3TABLE *L3GetBestRoute(L3SW *s, UINT ip);
UINT L3GetNextPacket(L3IF *f, void **data);
void L3Polling(L3IF *f);
void L3PollingBeacon(L3IF *f);
void L3DeleteOldArpTable(L3IF *f);
void L3DeleteOldIpWaitList(L3IF *f);
void L3PollingArpWaitTable(L3IF *f);
void L3SendL2Now(L3IF *f, UCHAR *dest_mac, UCHAR *src_mac, USHORT protocol, void *data, UINT size);
void L3SendArpRequestNow(L3IF *f, UINT dest_ip);
void L3SendArpResponseNow(L3IF *f, UCHAR *dest_mac, UINT dest_ip, UINT src_ip);
void L3GenerateMacAddress(L3IF *f);
L3ARPENTRY *L3SearchArpTable(L3IF *f, UINT ip);
void L3SendIpNow(L3IF *f, L3ARPENTRY *a, L3PACKET *p);
void L3SendIp(L3IF *f, L3PACKET *p);
void L3RecvArp(L3IF *f, PKT *p);
void L3RecvArpRequest(L3IF *f, PKT *p);
void L3RecvArpResponse(L3IF *f, PKT *p);
void L3KnownArp(L3IF *f, UINT ip, UCHAR *mac);
void L3SendArp(L3IF *f, UINT ip);
void L3InsertArpTable(L3IF *f, UINT ip, UCHAR *mac);
void L3SendWaitingIp(L3IF *f, UCHAR *mac, UINT ip, L3ARPENTRY *a);
void L3PutPacket(L3IF *f, void *data, UINT size);
void L3RecvL2(L3IF *f, PKT *p);
void L3StoreIpPacketToIf(L3IF *src_if, L3IF *dst_if, L3PACKET *p);
void L3RecvIp(L3IF *f, PKT *p, bool self);
void L3PollingIpQueue(L3IF *f);
#endif // LAYER3_H
|
a130c7d0c3ef4a1f98408344eb85e474f878043b
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWG/muon/RunLinkToMCAnalysisExample.C
|
dc485cf88a6e8c97ddbf3b599a5a1a27bd3e062f
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 4,320
|
c
|
RunLinkToMCAnalysisExample.C
|
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: *
* Artur Szostak <artursz@iafrica.com> *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/// \ingroup macros
/// \file RunLinkToMCAnalysisExample.C
/// \brief Example macro for running the AliAnalysisTaskLinkToMC analysis task.
/// \author Artur Szostak <artursz@iafrica.com>
///
/// This macro shows an example of how to run the AliAnalysisTaskLinkToMC analysis
/// task in local mode. It can be used as a quick check of the analysis task.
/// It will generate AliAOD.root and hists.root files. The hists.root can then
/// be used in the PlotEfficiency.C macro.
/// Run this macro as follows:
///
/// $ aliroot RunLinkToMCAnalysisExample.C\(\"AliESDs.root\"\)
///
/// where AliESDs.root should be the correct path to a root file containing ESD
/// objects created by the offline reconstruction.
#if !defined(__CINT__) || defined(__MAKECINT__)
#error This macro must be run in interpreted mode.
#endif
void RunLinkToMCAnalysisExample(const char* esdFile = "./AliESDs.root")
{
// Load needed libraries
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libPhysics");
gSystem->Load("libSTEERBase");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libPWGHFbase");
gSystem->Load("libPWGmuon");
// Create the TChain for esdTrees in the AliESDs.root file.
TChain* chain = new TChain("esdTree");
chain->Add(esdFile);
if (!chain) return;
// Create the analysis manager and event handlers.
AliAnalysisManager* mgr = new AliAnalysisManager("Analysis Train", "An example analysis train setup for AliAnalysisTaskLinkToMC.");
AliESDInputHandler* esdHandler = new AliESDInputHandler();
mgr->SetInputEventHandler(esdHandler);
AliMCEventHandler* mcHandler = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcHandler);
mcHandler->SetReadTR(kTRUE);
AliAODHandler* aodHandler = new AliAODHandler();
mgr->SetOutputEventHandler(aodHandler);
aodHandler->SetOutputFileName("AliAOD.root");
// Create the analysis task and setup the parameters.
AliAnalysisTaskLinkToMC* linktask = new AliAnalysisTaskLinkToMC("Task to link ESD tracks to corresponding MC tracks.");
linktask->MinClusters(6);
linktask->HardCutLimitX(4);
linktask->HardCutLimitY(4);
linktask->SigmaCut(5.);
linktask->MinClustersInSt45(3);
linktask->StationMustMatch(1, true); // At least one cluster in station 1 must match.
linktask->StationMustMatch(2, true); // At least one cluster in station 2 must match.
linktask->StationMustMatch(3, true); // At least one cluster in station 3 must match.
linktask->GenerateHistograms(true);
mgr->AddTask(linktask);
// Create the input and output containers and connect them up to the analysis task.
AliAnalysisDataContainer* cinEsd = mgr->GetCommonInputContainer();
AliAnalysisDataContainer* coutAod = mgr->GetCommonOutputContainer();
AliAnalysisDataContainer* coutHists = mgr->CreateContainer("cHists", TList::Class(), AliAnalysisManager::kOutputContainer, "hists.root");
mgr->ConnectInput(linktask, 0, cinEsd);
mgr->ConnectOutput(linktask, 0, coutAod);
mgr->ConnectOutput(linktask, 1, coutHists);
if (mgr->InitAnalysis())
{
mgr->PrintStatus();
mgr->StartAnalysis("local", chain);
}
}
|
0b657ab948e87c74c0ad9dfa47cee704363795c5
|
ad782fb4f077a90af2ec7b401d382007da9a6301
|
/MGZ/source/self.c
|
50691e9c53065d5296aafe40e169d238916b4ac4
|
[] |
no_license
|
Zarh/ManaGunZ
|
de1be6b1dadd31a7a5dba6e11241f63dd213060f
|
168d58e7c12ed1a65546e26641e8cb578b685059
|
refs/heads/master
| 2023-05-25T19:47:46.296283
| 2023-05-12T12:08:43
| 2023-05-12T12:08:43
| 76,070,852
| 190
| 143
| null | 2023-05-12T12:08:44
| 2016-12-09T21:15:50
|
C
|
UTF-8
|
C
| false
| false
| 31,895
|
c
|
self.c
|
/*
* Copyright (c) 2011-2013 by naehrwert
* This file is released under the GPLv2.
*/
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "config.h"
#include "util.h"
#include "sce.h"
#include "sce_inlines.h"
#include "self.h"
#include "elf.h"
#include "elf_inlines.h"
#include "tables.h"
#include "sha1.h"
#include "np.h"
static void _get_shdr_flags(char *str, unsigned long long int flags)
{
memset(str, '-', 3);
str[3] = 0;
if(flags & SHF_WRITE)
str[0] = 'W';
if(flags & SHF_ALLOC)
str[1] = 'A';
if(flags & SHF_EXECINSTR)
str[2] = 'E';
}
static void _get_phdr_flags(char *str, unsigned long long int flags)
{
memset(str, '-', 3);
str[3] = 0;
if(flags & PF_X)
str[0] = 'X';
if(flags & PF_W)
str[1] = 'W';
if(flags & PF_R)
str[2] = 'R';
}
void _print_self_header(FILE *fp, self_header_t *h)
{
fprintf(fp, "[*] SELF Header:\n");
fprintf(fp, " Header Type 0x%016llX\n", h->header_type);
fprintf(fp, " App Info Offset 0x%016llX\n", h->app_info_offset);
fprintf(fp, " ELF Offset 0x%016llX\n", h->elf_offset);
fprintf(fp, " PH Offset 0x%016llX\n", h->phdr_offset);
fprintf(fp, " SH Offset 0x%016llX\n", h->shdr_offset);
fprintf(fp, " Section Info Offset 0x%016llX\n", h->section_info_offset);
fprintf(fp, " SCE Version Offset 0x%016llX\n", h->sce_version_offset);
fprintf(fp, " Control Info Offset 0x%016llX\n", h->control_info_offset);
fprintf(fp, " Control Info Size 0x%016llX\n", h->control_info_size);
//fprintf(fp, " padding 0x%016llX\n", h->padding);
}
void _print_app_info(FILE *fp, app_info_t *ai)
{
const char *name;
fprintf(fp, "[*] Application Info:\n");
name = _get_name(_auth_ids, ai->auth_id);
if(name != NULL)
{
fprintf(fp, " Auth-ID ");
_PRINT_RAW(fp, "0x%016llX ", ai->auth_id);
fprintf(fp, "[%s]\n", name);
}
else
fprintf(fp, " Auth-ID 0x%016llX\n", ai->auth_id);
name = _get_name(_vendor_ids, ai->vendor_id);
if(name != NULL)
{
fprintf(fp, " Vendor-ID ");
_PRINT_RAW(fp, "0x%08X ", ai->vendor_id);
fprintf(fp, "[%s]\n", name);
}
else
fprintf(fp, " Vendor-ID 0x%08X\n", ai->vendor_id);
name = _get_name(_self_types, ai->self_type);
if(name != NULL)
fprintf(fp, " SELF-Type [%s]\n", name);
else
fprintf(fp, " SELF-Type 0x%08X\n", ai->self_type);
fprintf(fp, " Version %s\n", sce_version_to_str(ai->version));
//fprintf(fp, " padding 0x%016llX\n", ai->padding);
}
void _print_section_info_header(FILE *fp)
{
fprintf(fp, "[*] Section Infos:\n");
fprintf(fp, " Idx Offset Size Compressed unk0 unk1 Encrypted\n");
}
void _print_section_info(FILE *fp, section_info_t *si, unsigned int idx)
{
fprintf(fp, " %03d %08X %08X %s %08X %08X %s\n",
idx, (unsigned int)si->offset, (unsigned int)si->size, si->compressed == 2 ? "[YES]" : "[NO ]",
si->unknown_0, si->unknown_1, si->encrypted == 1 ? "[YES]" : "[NO ]");
}
void _print_sce_version(FILE *fp, sce_version_t *sv)
{
fprintf(fp, "[*] SCE Version:\n");
fprintf(fp, " Header Type 0x%08X\n", sv->header_type);
fprintf(fp, " Present [%s]\n", sv->present == SCE_VERSION_PRESENT ? "TRUE" : "FALSE");
fprintf(fp, " Size 0x%08X\n", sv->size);
fprintf(fp, " unknown_3 0x%08X\n", sv->unknown_3);
}
void _print_control_info(FILE *fp, control_info_t *ci)
{
const char *name;
fprintf(fp, "[*] Control Info\n");
name = _get_name(_control_info_types, ci->type);
if(name != NULL)
fprintf(fp, " Type %s\n", name);
else
fprintf(fp, " Type 0x%08X\n", ci->type);
fprintf(fp, " Size 0x%08X\n", ci->size);
fprintf(fp, " Next [%s]\n", ci->next == 1 ? "TRUE" : "FALSE");
switch(ci->type)
{
case CONTROL_INFO_TYPE_FLAGS:
_hexdump(fp, " Flags", 0, (unsigned char *)ci + sizeof(control_info_t), ci->size - sizeof(control_info_t), FALSE);
break;
case CONTROL_INFO_TYPE_DIGEST:
if(ci->size == 0x30)
{
ci_data_digest_30_t *dig = (ci_data_digest_30_t *)((unsigned char *)ci + sizeof(control_info_t));
_hexdump(fp, " Digest", 0, dig->digest, 20, FALSE);
}
else if(ci->size == 0x40)
{
ci_data_digest_40_t *dig = (ci_data_digest_40_t *)((unsigned char *)ci + sizeof(control_info_t));
_es_ci_data_digest_40(dig);
_hexdump(fp, " Digest 1 ", 0, dig->digest1, 20, FALSE);
_hexdump(fp, " Digest 2 ", 0, dig->digest2, 20, FALSE);
if(dig->fw_version != 0)
fprintf(fp, " FW Version %d [%02d.%02d]\n", (unsigned int)dig->fw_version, ((unsigned int)dig->fw_version)/10000, (((unsigned int)dig->fw_version)%10000)/100);
}
break;
case CONTROL_INFO_TYPE_NPDRM:
{
ci_data_npdrm_t *np = (ci_data_npdrm_t *)((unsigned char *)ci + sizeof(control_info_t));
//Was already fixed in decrypt_header.
//_es_ci_data_npdrm(np);
fprintf(fp, " Magic 0x%08X [%s]\n", np->magic, (np->magic == NP_CI_MAGIC ? "OK" : "ERROR"));
fprintf(fp, " unknown_0 0x%08X\n", np->unknown_0);
fprintf(fp, " Licence Type 0x%08X\n", np->license_type);
fprintf(fp, " App Type 0x%08X\n", np->app_type);
fprintf(fp, " ContentID %s\n", np->content_id);
_hexdump(fp, " Random Pad ", 0, np->rndpad, 0x10, FALSE);
_hexdump(fp, " CID_FN Hash ", 0, np->hash_cid_fname, 0x10, FALSE);
_hexdump(fp, " CI Hash ", 0, np->hash_ci, 0x10, FALSE);
fprintf(fp, " unknown_1 0x%016llX\n", np->unknown_1);
fprintf(fp, " unknown_2 0x%016llX\n", np->unknown_2);
}
break;
}
}
static void _print_cap_flags_flags(FILE *fp, oh_data_cap_flags_t *cf)
{
if(cf->flags & 0x01)
fprintf(fp, "0x01 ");
if(cf->flags & 0x02)
fprintf(fp, "0x02 ");
if(cf->flags & 0x04)
fprintf(fp, "0x04 ");
if(cf->flags & CAP_FLAG_REFTOOL)
fprintf(fp, "REFTOOL ");
if(cf->flags & CAP_FLAG_DEBUG)
fprintf(fp, "DEBUG ");
if(cf->flags & CAP_FLAG_RETAIL)
fprintf(fp, "RETAIL ");
if(cf->flags & CAP_FLAG_SYSDBG)
fprintf(fp, "SYSDBG ");
}
void _print_opt_header(FILE *fp, opt_header_t *oh)
{
const char *name;
fprintf(fp, "[*] Optional Header\n");
name = _get_name(_optional_header_types, oh->type);
if(name != NULL)
fprintf(fp, " Type %s\n", name);
else
fprintf(fp, " Type 0x%08X\n", oh->type);
fprintf(fp, " Size 0x%08X\n", oh->size);
fprintf(fp, " Next [%s]\n", oh->next == 1 ? "TRUE" : "FALSE");
switch(oh->type)
{
case OPT_HEADER_TYPE_CAP_FLAGS:
{
oh_data_cap_flags_t *cf = (oh_data_cap_flags_t *)((unsigned char *)oh + sizeof(opt_header_t));
_IF_RAW(_hexdump(fp, " Flags", 0, (unsigned char *)cf, sizeof(oh_data_cap_flags_t), FALSE));
_es_oh_data_cap_flags(cf);
fprintf(fp, " unknown_3 0x%016llX\n", cf->unk3);
fprintf(fp, " unknown_4 0x%016llX\n", cf->unk4);
fprintf(fp, " Flags 0x%016llX [ ", cf->flags);
_print_cap_flags_flags(fp, cf);
fprintf(fp, "]\n");
fprintf(fp, " unknown_6 0x%08X\n", cf->unk6);
fprintf(fp, " unknown_7 0x%08X\n", cf->unk7);
}
break;
#ifdef CONFIG_DUMP_INDIV_SEED
case OPT_HEADER_TYPE_INDIV_SEED:
{
unsigned char *is = (unsigned char *)oh + sizeof(opt_header_t);
_hexdump(fp, " Seed", 0, is, oh->size - sizeof(opt_header_t), TRUE);
}
break;
#endif
}
}
void _print_elf32_ehdr(FILE *fp, Elf32_Ehdr *h)
{
const char *name;
fprintf(fp, "[*] ELF32 Header:\n");
name = _get_name(_e_types, h->e_type);
if(name != NULL)
fprintf(fp, " Type [%s]\n", name);
else
fprintf(fp, " Type 0x%04X\n", h->e_type);
name = _get_name(_e_machines, h->e_machine);
if(name != NULL)
fprintf(fp, " Machine [%s]\n", name);
else
fprintf(fp, " Machine 0x%04X\n", h->e_machine);
fprintf(fp, " Version 0x%08X\n", h->e_version);
fprintf(fp, " Entry 0x%08X\n", h->e_entry);
fprintf(fp, " Program Headers Offset 0x%08X\n", h->e_phoff);
fprintf(fp, " Section Headers Offset 0x%08X\n", h->e_shoff);
fprintf(fp, " Flags 0x%08X\n", h->e_flags);
fprintf(fp, " Program Headers Count %04d\n", h->e_phnum);
fprintf(fp, " Section Headers Count %04d\n", h->e_shnum);
fprintf(fp, " SH String Index %04d\n", h->e_shstrndx);
}
void _print_elf64_ehdr(FILE *fp, Elf64_Ehdr *h)
{
const char *name;
fprintf(fp, "[*] ELF64 Header:\n");
name = _get_name(_e_types, h->e_type);
if(name != NULL)
fprintf(fp, " Type [%s]\n", name);
else
fprintf(fp, " Type 0x%04X\n", h->e_type);
name = _get_name(_e_machines, h->e_machine);
if(name != NULL)
fprintf(fp, " Machine [%s]\n", name);
else
fprintf(fp, " Machine 0x%04X\n", h->e_machine);
fprintf(fp, " Version 0x%08X\n", h->e_version);
fprintf(fp, " Entry 0x%016llX\n", h->e_entry);
fprintf(fp, " Program Headers Offset 0x%016llX\n", h->e_phoff);
fprintf(fp, " Section Headers Offset 0x%016llX\n", h->e_shoff);
fprintf(fp, " Flags 0x%08X\n", h->e_flags);
fprintf(fp, " Program Headers Count %04d\n", h->e_phnum);
fprintf(fp, " Section Headers Count %04d\n", h->e_shnum);
fprintf(fp, " SH String Index %04d\n", h->e_shstrndx);
}
void _print_elf32_shdr_header(FILE *fp)
{
fprintf(fp, "[*] ELF32 Section Headers:\n");
fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n");
}
void _print_elf32_shdr(FILE *fp, Elf32_Shdr *h, unsigned int idx)
{
const char *name;
char flags[4];
_get_shdr_flags(flags, h->sh_flags);
fprintf(fp, " %03d %04X ", idx, h->sh_name);
name = _get_name(_sh_types, h->sh_type);
if(name != NULL)
fprintf(fp, "%-13s ", name);
else
fprintf(fp, "%08X ", h->sh_type);
fprintf(fp, "%s %05X %05X %05X %02X %05X %03d\n",
flags, h->sh_addr, h->sh_offset, h->sh_size, h->sh_entsize, h->sh_addralign, h->sh_link);
}
void _print_elf64_shdr_header(FILE *fp)
{
fprintf(fp, "[*] ELF64 Section Headers:\n");
fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n");
}
void _print_elf64_shdr(FILE *fp, Elf64_Shdr *h, unsigned int idx)
{
const char *name;
char flags[4];
_get_shdr_flags(flags, h->sh_flags);
fprintf(fp, " %03d %04X ", idx, h->sh_name);
name = _get_name(_sh_types, h->sh_type);
if(name != NULL)
fprintf(fp, "%-13s ", name);
else
fprintf(fp, "%08X ", h->sh_type);
fprintf(fp, "%s %08X %08X %08X %04X %08X %03d\n",
flags, (unsigned int)h->sh_addr, (unsigned int)h->sh_offset, (unsigned int)h->sh_size, (unsigned int)h->sh_entsize, (unsigned int)h->sh_addralign, h->sh_link);
}
void _print_elf32_phdr_header(FILE *fp)
{
fprintf(fp, "[*] ELF32 Program Headers:\n");
fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize Flags Align\n");
}
void _print_elf32_phdr(FILE *fp, Elf32_Phdr *h, unsigned int idx)
{
const char *name;
char flags[4];
_get_phdr_flags(flags, h->p_flags);
fprintf(fp, " %03d ", idx);
name = _get_name(_ph_types, h->p_type);
if(name != NULL)
fprintf(fp, "%-7s ", name);
else
fprintf(fp, "0x%08X ", h->p_type);
fprintf(fp, "%05X %05X %05X %05X %05X %s %05X\n",
h->p_offset, h->p_vaddr, h->p_paddr, h->p_filesz, h->p_memsz, flags, h->p_align);
}
void _print_elf64_phdr_header(FILE *fp)
{
fprintf(fp, "[*] ELF64 Program Headers:\n");
fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize PPU SPU RSX Align\n");
}
void _print_elf64_phdr(FILE *fp, Elf64_Phdr *h, unsigned int idx)
{
const char *name;
char ppu[4], spu[4], rsx[4];
_get_phdr_flags(ppu, h->p_flags);
_get_phdr_flags(spu, h->p_flags >> 20);
_get_phdr_flags(rsx, h->p_flags >> 24);
fprintf(fp, " %03d ", idx);
name = _get_name(_ph_types, h->p_type);
if(name != NULL)
fprintf(fp, "%-8s ", name);
else
fprintf(fp, "%08X ", h->p_type);
fprintf(fp, "%08X %08X %08X %08X %08X %s %s %s %08X\n",
(unsigned int)h->p_offset, (unsigned int)h->p_vaddr, (unsigned int)h->p_paddr, (unsigned int)h->p_filesz, (unsigned int)h->p_memsz, ppu, spu, rsx, (unsigned int)h->p_align);
}
BOOL self_print_info(FILE *fp, sce_buffer_ctxt_t *ctxt)
{
unsigned int i, self_type;
const unsigned char *eident;
//Check for SELF.
if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF)
return FALSE;
//Print SELF infos.
_print_self_header(fp, ctxt->self.selfh);
_print_app_info(fp, ctxt->self.ai);
if(ctxt->self.sv != NULL)
_print_sce_version(fp, ctxt->self.sv);
//Print control infos.
if(ctxt->self.cis != NULL)
LIST_FOREACH(iter, ctxt->self.cis)
_print_control_info(fp, (control_info_t *)iter->value);
//Print optional headers.
if(ctxt->mdec == TRUE)
{
LIST_FOREACH(iter, ctxt->self.ohs)
{
#ifndef CONFIG_DUMP_INDIV_SEED
if(((opt_header_t *)iter->value)->type != OPT_HEADER_TYPE_INDIV_SEED)
_print_opt_header(fp, (opt_header_t *)iter->value);
#else
_print_opt_header(fp, (opt_header_t *)iter->value);
#endif
}
}
self_type = ctxt->self.ai->self_type;
eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset;
//SPU is 32 bit.
if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32)
{
//32 bit ELF.
Elf32_Ehdr *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset);
_es_elf32_ehdr(eh);
//Print section infos.
_print_section_info_header(fp);
for(i = 0; i < eh->e_phnum; i++)
{
_es_section_info(&ctxt->self.si[i]);
_print_section_info(fp, &ctxt->self.si[i], i);
}
//Print ELF header.
_print_elf32_ehdr(fp, eh);
Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset);
//Print program headers.
_print_elf32_phdr_header(fp);
for(i = 0; i < eh->e_phnum; i++)
{
_es_elf32_phdr(&ph[i]);
_print_elf32_phdr(fp, &ph[i], i);
}
if(eh->e_shnum > 0)
{
Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset);
//Print section headers.
_print_elf32_shdr_header(fp);
for(i = 0; i < eh->e_shnum; i++)
{
_es_elf32_shdr(&sh[i]);
_print_elf32_shdr(fp, &sh[i], i);
}
}
}
else
{
//64 bit ELF.
Elf64_Ehdr *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset);
_es_elf64_ehdr(eh);
//Print section infos.
_print_section_info_header(fp);
for(i = 0; i < eh->e_phnum; i++)
{
_es_section_info(&ctxt->self.si[i]);
_print_section_info(fp, &ctxt->self.si[i], i);
}
//Print ELF header.
_print_elf64_ehdr(stdout, eh);
Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset);
//Print program headers.
_print_elf64_phdr_header(fp);
for(i = 0; i < eh->e_phnum; i++)
{
_es_elf64_phdr(&ph[i]);
_print_elf64_phdr(fp, &ph[i], i);
}
if(eh->e_shnum > 0)
{
Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset);
//Print section headers.
_print_elf64_shdr_header(fp);
for(i = 0; i < eh->e_shnum; i++)
{
_es_elf64_shdr(&sh[i]);
_print_elf64_shdr(fp, &sh[i], i);
}
}
}
return TRUE;
}
//TODO: maybe implement better.
BOOL self_write_to_elf(sce_buffer_ctxt_t *ctxt, const char *elf_out)
{
FILE *fp;
unsigned int i, self_type;
const unsigned char *eident;
//Check for SELF.
if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF)
return FALSE;
if((fp = fopen(elf_out, "wb")) == NULL)
return FALSE;
self_type = ctxt->self.ai->self_type;
eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset;
//SPU is 32 bit.
if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32)
{
#ifdef CONFIG_DUMP_INDIV_SEED
/*
//Print individuals seed.
if(self_type == SELF_TYPE_ISO)
{
unsigned char *indiv_seed = (unsigned char *)ctxt->self.ish + sizeof(iseed_header_t);
char ifile[256];
sprintf(ifile, "%s.indiv_seed.bin", elf_out);
FILE *ifp = fopen(ifile, "wb");
fwrite(indiv_seed, sizeof(unsigned char), ctxt->self.ish->size - sizeof(iseed_header_t), ifp);
fclose(ifp);
}
*/
#endif
//32 bit ELF.
Elf32_Ehdr ceh, *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset);
_copy_es_elf32_ehdr(&ceh, eh);
//Write ELF header.
fwrite(eh, sizeof(Elf32_Ehdr), 1, fp);
//Write program headers.
Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset);
fwrite(ph, sizeof(Elf32_Phdr), ceh.e_phnum, fp);
//Write program data.
metadata_section_header_t *msh = ctxt->metash;
for(i = 0; i < ctxt->metah->section_count; i++)
{
if(msh[i].type == METADATA_SECTION_TYPE_PHDR)
{
_es_elf32_phdr(&ph[msh[i].index]);
fseek(fp, ph[msh[i].index].p_offset, SEEK_SET);
fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(unsigned char), msh[i].data_size, fp);
}
}
//Write section headers.
if(ctxt->self.selfh->shdr_offset != 0)
{
Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset);
fseek(fp, ceh.e_shoff, SEEK_SET);
fwrite(sh, sizeof(Elf32_Shdr), ceh.e_shnum, fp);
}
}
else
{
//64 bit ELF.
Elf64_Ehdr ceh, *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset);
_copy_es_elf64_ehdr(&ceh, eh);
//Write ELF header.
fwrite(eh, sizeof(Elf64_Ehdr), 1, fp);
//Write program headers.
Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset);
fwrite(ph, sizeof(Elf64_Phdr), ceh.e_phnum, fp);
//Write program data.
metadata_section_header_t *msh = ctxt->metash;
for(i = 0; i < ctxt->metah->section_count; i++)
{
if(msh[i].type == METADATA_SECTION_TYPE_PHDR)
{
if(msh[i].compressed == METADATA_SECTION_COMPRESSED)
{
_es_elf64_phdr(&ph[msh[i].index]);
unsigned char *data = (unsigned char *)malloc(ph[msh[i].index].p_filesz);
_zlib_inflate(ctxt->scebuffer + msh[i].data_offset, msh[i].data_size, data, ph[msh[i].index].p_filesz);
fseek(fp, ph[msh[i].index].p_offset, SEEK_SET);
fwrite(data, sizeof(unsigned char), ph[msh[i].index].p_filesz, fp);
free(data);
}
else
{
_es_elf64_phdr(&ph[msh[i].index]);
fseek(fp, ph[msh[i].index].p_offset, SEEK_SET);
fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(unsigned char), msh[i].data_size, fp);
}
}
}
//Write section headers.
if(ctxt->self.selfh->shdr_offset != 0)
{
Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset);
fseek(fp, ceh.e_shoff, SEEK_SET);
fwrite(sh, sizeof(Elf64_Shdr), ceh.e_shnum, fp);
}
}
fclose(fp);
return TRUE;
}
/*! Static zero control flags. */
static unsigned char _static_control_flags[0x20] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/*! Static control digest1. */
static unsigned char _static_control_digest[0x14] =
{
0x62, 0x7C, 0xB1, 0x80, 0x8A, 0xB9, 0x38, 0xE3, 0x2C, 0x8C, 0x09, 0x17, 0x08, 0x72, 0x6A, 0x57, 0x9E, 0x25, 0x86, 0xE4
};
static BOOL _create_control_infos(sce_buffer_ctxt_t *ctxt, self_config_t *sconf)
{
control_info_t *ci;
unsigned int self_type = ctxt->self.ai->self_type;
//Step 1.
switch(self_type)
{
case SELF_TYPE_LV0:
case SELF_TYPE_LV1:
case SELF_TYPE_LV2:
case SELF_TYPE_APP:
case SELF_TYPE_ISO:
case SELF_TYPE_LDR:
case SELF_TYPE_NPDRM: //TODO: <-- figure more out.
{
//Add control flags.
ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_flags_t));
ci->type = CONTROL_INFO_TYPE_FLAGS;
ci->size = sizeof(control_info_t) + sizeof(ci_data_flags_t);
ci->next = 1;
ci_data_flags_t *cif = (ci_data_flags_t *)((unsigned char *)ci + sizeof(control_info_t));
//Add default flags.
if(sconf->ctrl_flags == NULL)
memcpy(cif->data, _static_control_flags, 0x20);
else
memcpy(cif->data, sconf->ctrl_flags, 0x20);
list_add_back(ctxt->self.cis, ci);
}
break;
}
//Step 2.
switch(self_type)
{
case SELF_TYPE_LV0:
case SELF_TYPE_LV1:
case SELF_TYPE_LV2:
case SELF_TYPE_APP:
case SELF_TYPE_ISO:
case SELF_TYPE_LDR:
case SELF_TYPE_NPDRM:
{
//Add digest 0x40.
ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_digest_40_t));
ci->type = CONTROL_INFO_TYPE_DIGEST;
ci->size = sizeof(control_info_t) + sizeof(ci_data_digest_40_t);
if(self_type == SELF_TYPE_NPDRM)
ci->next = 1;
else
ci->next = 0;
ci_data_digest_40_t *cid = (ci_data_digest_40_t *)((unsigned char *)ci + sizeof(control_info_t));
memcpy(cid->digest1, _static_control_digest, 0x14);
memset(cid->digest2, 0, 0x14);
sha1(ctxt->makeself->elf, ctxt->makeself->elf_len, cid->digest2);
//TODO: check that.
if(self_type == SELF_TYPE_NPDRM)
cid->fw_version = sce_hexver_to_decver(sconf->fw_version);
else
cid->fw_version = 0;
//Fixup.
_es_ci_data_digest_40(cid);
list_add_back(ctxt->self.cis, ci);
}
break;
}
//Step 3.
switch(self_type)
{
case SELF_TYPE_NPDRM:
{
//Add NPDRM control info.
if(sconf->npdrm_config == NULL)
return FALSE;
ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_npdrm_t));
ci->type = CONTROL_INFO_TYPE_NPDRM;
ci->size = sizeof(control_info_t) + sizeof(ci_data_npdrm_t);
ci->next = 0;
ci_data_npdrm_t *cinp = (ci_data_npdrm_t *)((unsigned char *)ci + sizeof(control_info_t));
//Create NPDRM control info.
if(np_create_ci(sconf->npdrm_config, cinp) == FALSE)
{
free(ci);
return FALSE;
}
list_add_back(ctxt->self.cis, ci);
}
break;
}
return TRUE;
}
static void _set_cap_flags(unsigned int self_type, oh_data_cap_flags_t *capf)
{
switch(self_type)
{
case SELF_TYPE_LV0:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B;
capf->unk6 = 1;
break;
case SELF_TYPE_LV1:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B;
capf->unk6 = 1;
break;
case SELF_TYPE_LV2:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B;
capf->unk6 = 1;
break;
case SELF_TYPE_APP:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B;
capf->unk6 = 1;
capf->unk7 = 0x20000;
break;
case SELF_TYPE_ISO:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78;
break;
case SELF_TYPE_LDR:
capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78;
break;
case SELF_TYPE_NPDRM:
capf->flags = CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x3B;
capf->unk6 = 1;
capf->unk7 = 0x2000;
break;
}
_es_oh_data_cap_flags(capf);
}
static BOOL _create_optional_headers(sce_buffer_ctxt_t *ctxt, self_config_t *sconf)
{
opt_header_t *oh;
unsigned int self_type = ctxt->self.ai->self_type;
//Step 1.
switch(self_type)
{
case SELF_TYPE_LV0:
case SELF_TYPE_LV1:
case SELF_TYPE_LV2:
case SELF_TYPE_APP:
case SELF_TYPE_ISO:
case SELF_TYPE_LDR:
case SELF_TYPE_NPDRM:
{
//Add capability flags.
oh = (opt_header_t *)malloc(sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t));
oh->type = OPT_HEADER_TYPE_CAP_FLAGS;
oh->size = sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t);
if(self_type == SELF_TYPE_ISO)
oh->next = 1;
else
oh->next = 0;
oh_data_cap_flags_t *capf = (oh_data_cap_flags_t *)((unsigned char *)oh + sizeof(opt_header_t));
//Add default flags.
if(sconf->cap_flags == NULL)
_set_cap_flags(self_type, capf);
else
memcpy(capf, sconf->cap_flags, 0x20);
list_add_back(ctxt->self.ohs, oh);
}
break;
}
//Step 2.
switch(self_type)
{
case SELF_TYPE_ISO:
{
//Add individuals seed.
oh = (opt_header_t *)malloc(sizeof(opt_header_t) + 0x100);
oh->type = OPT_HEADER_TYPE_INDIV_SEED;
oh->size = sizeof(opt_header_t) + 0x100;
oh->next = 0;
unsigned char *is = (unsigned char *)oh + sizeof(opt_header_t);
memset(is, 0, 0x100);
#ifdef CONFIG_CUSTOM_INDIV_SEED
if(sconf->indiv_seed != NULL)
memcpy(is, sconf->indiv_seed, sconf->indiv_seed_size);
#endif
list_add_back(ctxt->self.ohs, oh);
}
break;
}
return TRUE;
}
static void _fill_sce_version(sce_buffer_ctxt_t *ctxt)
{
ctxt->self.sv->header_type = SUB_HEADER_TYPE_SCEVERSION;
ctxt->self.sv->present = SCE_VERSION_NOT_PRESENT;
ctxt->self.sv->size = sizeof(sce_version_t);
ctxt->self.sv->unknown_3 = 0x00000000;
}
static void _add_phdr_section(sce_buffer_ctxt_t *ctxt, unsigned int p_type, unsigned int size, unsigned int idx)
{
//Offset gets set later.
ctxt->self.si[idx].offset = 0;
ctxt->self.si[idx].size = size;
if(p_type == PT_LOAD || p_type == PT_PS3_PRX_RELOC || p_type == 0x700000A8)
ctxt->self.si[idx].encrypted = 1; //Encrypted LOAD (?).
else
ctxt->self.si[idx].encrypted = 0; //No LOAD (?).
ctxt->self.si[idx].compressed = SECTION_INFO_NOT_COMPRESSED;
ctxt->self.si[idx].unknown_0 = 0; //Unknown.
ctxt->self.si[idx].unknown_1 = 0; //Unknown.
}
static BOOL _add_shdrs_section(sce_buffer_ctxt_t *ctxt, unsigned int idx)
{
//Add a section for the section headers.
if(ctxt->makeself->shdrs != NULL)
{
unsigned int shsize = ctxt->makeself->shsize;
void *sec = _memdup(ctxt->makeself->shdrs, shsize);
sce_add_data_section(ctxt, sec, shsize, FALSE);
//Fill metadata section header.
sce_set_metash(ctxt, METADATA_SECTION_TYPE_SHDR, FALSE, idx);
return TRUE;
}
return FALSE;
}
static BOOL _build_self_32(sce_buffer_ctxt_t *ctxt, self_config_t *sconf)
{
unsigned int i;
Elf32_Ehdr *ehdr;
Elf32_Phdr *phdrs;
//Elf32_Shdr *shdrs;
//Copy ELF header.
ctxt->makeself->ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr));
ctxt->makeself->ehsize = sizeof(Elf32_Ehdr);
ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr));
_es_elf32_ehdr(ehdr);
//Copy program headers.
ctxt->makeself->phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum);
ctxt->makeself->phsize = sizeof(Elf32_Phdr) * ehdr->e_phnum;
phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum);
//Copy section headers.
if(ehdr->e_shnum != 0)
{
ctxt->makeself->shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum);
ctxt->makeself->shsize = sizeof(Elf32_Shdr) * ehdr->e_shnum;
//shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum);
}
//Allocate metadata section headers (one for each program header and one for the section headers).
ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1));
//Copy sections, fill section infos and metadata section headers.
ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum);
for(i = 0; i < ehdr->e_phnum; i++)
{
_es_elf32_phdr(&phdrs[i]);
void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz);
//Never compress sections on SPU SELFs.
sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, FALSE);
//Add section info.
_add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i);
//Fill metadata section header.
sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, phdrs[i].p_type == PT_LOAD ? TRUE : FALSE, i);
}
//Section info count.
ctxt->makeself->si_cnt = ehdr->e_phnum;
//Number of section infos that are present as data sections.
ctxt->makeself->si_sec_cnt = ehdr->e_phnum;
//Add a section for the section headers.
if(sconf->add_shdrs == TRUE)
if(_add_shdrs_section(ctxt, i) == TRUE)
i++;
//Metadata.
ctxt->metah->section_count = i;
return TRUE;
}
static BOOL _build_self_64(sce_buffer_ctxt_t *ctxt, self_config_t *sconf)
{
unsigned int i;
Elf64_Ehdr *ehdr;
Elf64_Phdr *phdrs=NULL;
//Elf64_Shdr *shdrs;
//Copy ELF header.
ctxt->makeself->ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr));
ctxt->makeself->ehsize = sizeof(Elf64_Ehdr);
ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr));
_es_elf64_ehdr(ehdr);
//Copy program headers.
ctxt->makeself->phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff , sizeof(Elf64_Phdr) * ehdr->e_phnum);
ctxt->makeself->phsize = sizeof(Elf64_Phdr) * ehdr->e_phnum;
phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf64_Phdr) * ehdr->e_phnum);
//Copy section headers.
if(ehdr->e_shnum != 0)
{
ctxt->makeself->shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff , sizeof(Elf64_Shdr) * ehdr->e_shnum);
ctxt->makeself->shsize = sizeof(Elf64_Shdr) * ehdr->e_shnum;
//shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf64_Shdr) * ehdr->e_shnum);
}
//Allocate metadata section headers (one for each program header and one for the section headers).
ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1));
//Copy sections, fill section infos and metadata section headers.
ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum);
unsigned int loff = 0xFFFFFFFF, skip = 0;
for(i = 0; i < ehdr->e_phnum; i++)
{
//_es_elf64_phdr(&phdrs[i]);
//Add section info.
_add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i);
//TODO: what if the size differs, why skip other program headers?
//Fill metadata section header but skip identical program header offsets.
if(sconf->skip_sections == TRUE && (phdrs[i].p_offset == loff || !(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8)))
{
const char *name = _get_name(_ph_types, phdrs[i].p_type);
if(name != NULL)
_LOG_VERBOSE("Skipped program header %-8s @ 0x%08X (0x%08X)\n", name, (unsigned int) phdrs[i].p_offset, (unsigned int) phdrs[i].p_filesz);
else
_LOG_VERBOSE("Skipped program header 0x%08X @ 0x%08X (0x%08X)\n", (unsigned int) phdrs[i].p_type,(unsigned int) phdrs[i].p_offset,(unsigned int) phdrs[i].p_filesz);
skip++;
}
else
{
void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz);
//PPU sections may be compressed.
sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, TRUE);
sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, TRUE /*(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8) ? TRUE : FALSE*/, i - skip);
}
loff = phdrs[i].p_offset;
}
//Section info count.
ctxt->makeself->si_cnt = ehdr->e_phnum;
//Number of section infos that are present as data sections.
ctxt->makeself->si_sec_cnt = i - skip;
//Add a section for the section headers.
if(sconf->add_shdrs == TRUE)
if(_add_shdrs_section(ctxt, i - skip) == TRUE)
i++;
//Metadata.
i -= skip;
ctxt->metah->section_count = i;
return TRUE;
}
BOOL self_build_self(sce_buffer_ctxt_t *ctxt, self_config_t *sconf)
{
//const unsigned char *eident;
//Fill config values.
ctxt->sceh->key_revision = sconf->key_revision;
ctxt->self.ai->auth_id = sconf->auth_id;
ctxt->self.ai->vendor_id = sconf->vendor_id;
ctxt->self.ai->self_type = sconf->self_type;
ctxt->self.ai->version = sconf->app_version;
//Create control infos.
if(_create_control_infos(ctxt, sconf) == FALSE)
{
printf("[*] Error: Could not create SELF control infos.\n");
return FALSE;
}
#ifdef CONFIG_CUSTOM_INDIV_SEED
if(sconf->indiv_seed != NULL && sconf->self_type != SELF_TYPE_ISO)
printf("[*] Warning: Skipping individuals seed for non-ISO SELF.\n");
#endif
//Create optional headers.
if(_create_optional_headers(ctxt, sconf) == FALSE)
{
printf("[*] Error: Could not create SELF optional headers.\n");
return FALSE;
}
//Set SCE version.
_fill_sce_version(ctxt);
//Check for 32 bit or 64 bit ELF.
//eident = (const unsigned char*)ctxt->makeself->elf;
if(sconf->self_type == SELF_TYPE_LDR || sconf->self_type == SELF_TYPE_ISO /*|| eident[EI_CLASS] == ELFCLASS32*/) return _build_self_32(ctxt, sconf);
return _build_self_64(ctxt, sconf);
}
|
6af0e3689a73abcb27e6d930b450fe87b968b10b
|
c9bc99866cfab223c777cfb741083be3e9439d81
|
/product/sgm776/include/sgm776_mmap_scp.h
|
eb375f5b9561cded32455f8806c03acb1ec4918a
|
[
"BSD-3-Clause"
] |
permissive
|
ARM-software/SCP-firmware
|
4738ca86ce42d82588ddafc2226a1f353ff2c797
|
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
|
refs/heads/master
| 2023-09-01T16:13:36.962036
| 2023-08-17T13:00:20
| 2023-08-31T07:43:37
| 134,399,880
| 211
| 165
|
NOASSERTION
| 2023-09-13T14:27:10
| 2018-05-22T10:35:56
|
C
|
UTF-8
|
C
| false
| false
| 499
|
h
|
sgm776_mmap_scp.h
|
/*
* Arm SCP/MCP Software
* Copyright (c) 2017-2021, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Description:
* SCP ROM and RAM memory bases. These definitions are kept isolated without
* the UINT32_C() or UL decorators allowing them to be used in the linker
* script.
*/
#ifndef SGM776_MMAP_SCP_H
#define SGM776_MMAP_SCP_H
#define SCP_ROM_BASE 0x00000000
#define SCP_RAM_BASE 0x10000000
#endif /* SGM776_MMAP_SCP_H */
|
4043e225cf5ba2ccf0e33b132e8d4375078a5479
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/chip/it83xx/flash.c
|
c0e062bce4706982291b950e2150f349b590f998
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 20,403
|
c
|
flash.c
|
/* Copyright 2015 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "common.h"
#include "console.h"
#include "flash.h"
#include "flash_chip.h"
#include "host_command.h"
#include "intc.h"
#include "system.h"
#include "util.h"
#include "watchdog.h"
#include "registers.h"
#include "task.h"
#include "shared_mem.h"
#include "uart.h"
#define FLASH_DMA_START ((uint32_t) &__flash_dma_start)
#define FLASH_DMA_CODE __attribute__((section(".flash_direct_map")))
/* erase size of sector is 1KB or 4KB */
#define FLASH_SECTOR_ERASE_SIZE CONFIG_FLASH_ERASE_SIZE
#ifdef IT83XX_CHIP_FLASH_IS_KGD
/* page program command */
#define FLASH_CMD_PAGE_WRITE 0x2
/* ector erase command (erase size is 4KB) */
#define FLASH_CMD_SECTOR_ERASE 0x20
/* command for flash write */
#define FLASH_CMD_WRITE FLASH_CMD_PAGE_WRITE
#else
/* Auto address increment programming */
#define FLASH_CMD_AAI_WORD 0xAD
/* Flash sector erase (1K bytes) command */
#define FLASH_CMD_SECTOR_ERASE 0xD7
/* command for flash write */
#define FLASH_CMD_WRITE FLASH_CMD_AAI_WORD
#endif
/* Write status register */
#define FLASH_CMD_WRSR 0x01
/* Write disable */
#define FLASH_CMD_WRDI 0x04
/* Write enable */
#define FLASH_CMD_WREN 0x06
/* Read status register */
#define FLASH_CMD_RS 0x05
#define FLASH_TEXT_START ((uint32_t) &__flash_text_start)
/* The default tag index of immu. */
#define IMMU_TAG_INDEX_BY_DEFAULT 0x7E000
/* immu cache size is 8K bytes. */
#define IMMU_SIZE 0x2000
#if (CONFIG_FLASH_SIZE == 0x80000) && defined(CHIP_CORE_NDS32)
/* Apply workaround of the issue (b:111808417) */
#define IMMU_CACHE_TAG_INVALID
#endif
static int stuck_locked;
static int inconsistent_locked;
static int all_protected;
static int flash_dma_code_enabled;
#define FWP_REG(bank) (bank / 8)
#define FWP_MASK(bank) (1 << (bank % 8))
enum flash_wp_interface {
FLASH_WP_HOST = 0x01,
FLASH_WP_DBGR = 0x02,
FLASH_WP_EC = 0x04,
};
enum flash_wp_status {
FLASH_WP_STATUS_PROTECT_RO = EC_FLASH_PROTECT_RO_NOW,
FLASH_WP_STATUS_PROTECT_ALL = EC_FLASH_PROTECT_ALL_NOW,
};
enum flash_status_mask {
FLASH_SR_NO_BUSY = 0,
/* Internal write operation is in progress */
FLASH_SR_BUSY = 0x01,
/* Device is memory Write enabled */
FLASH_SR_WEL = 0x02,
FLASH_SR_ALL = (FLASH_SR_BUSY | FLASH_SR_WEL),
};
enum dlm_address_view {
SCAR0_ILM0_DLM13 = 0x8D000, /* DLM ~ 0x8DFFF H2RAM map LPC I/O */
SCAR1_ILM1_DLM11 = 0x8B000, /* DLM ~ 0x8BFFF ram 44K ~ 48K */
SCAR2_ILM2_DLM14 = 0x8E000, /* DLM ~ 0x8EFFF RO/RW flash code DMA */
SCAR3_ILM3_DLM6 = 0x86000, /* DLM ~ 0x86FFF ram 24K ~ 28K */
SCAR4_ILM4_DLM7 = 0x87000, /* DLM ~ 0x87FFF ram 28K ~ 32K */
SCAR5_ILM5_DLM8 = 0x88000, /* DLM ~ 0x88FFF ram 32K ~ 36K */
SCAR6_ILM6_DLM9 = 0x89000, /* DLM ~ 0x89FFF ram 36K ~ 40K */
SCAR7_ILM7_DLM10 = 0x8A000, /* DLM ~ 0x8AFFF ram 40K ~ 44K */
SCAR8_ILM8_DLM4 = 0x84000, /* DLM ~ 0x84FFF ram 16K ~ 20K */
SCAR9_ILM9_DLM5 = 0x85000, /* DLM ~ 0x85FFF ram 20K ~ 24K */
SCAR10_ILM10_DLM2 = 0x82000, /* DLM ~ 0x82FFF ram 8K ~ 12K */
SCAR11_ILM11_DLM3 = 0x83000, /* DLM ~ 0x83FFF ram 12K ~ 16K */
SCAR12_ILM12_DLM12 = 0x8C000, /* DLM ~ 0x8CFFF immu cache */
};
void FLASH_DMA_CODE dma_reset_immu(int fill_immu)
{
/* Immu tag sram reset */
IT83XX_GCTRL_MCCR |= 0x10;
/* Make sure the immu(dynamic cache) is reset */
data_serialization_barrier();
IT83XX_GCTRL_MCCR &= ~0x10;
data_serialization_barrier();
#ifdef IMMU_CACHE_TAG_INVALID
/*
* Workaround for (b:111808417):
* After immu reset, we will fill the immu cache with 8KB data
* that are outside address 0x7e000 ~ 0x7ffff.
* When CPU tries to fetch contents from address 0x7e000 ~ 0x7ffff,
* immu will re-fetch the missing contents inside 0x7e000 ~ 0x7ffff.
*/
if (fill_immu) {
volatile int immu __unused;
const uint32_t *ptr = (uint32_t *)FLASH_TEXT_START;
int i = 0;
while (i < IMMU_SIZE) {
immu = *ptr++;
i += sizeof(*ptr);
}
}
#endif
}
void FLASH_DMA_CODE dma_flash_follow_mode(void)
{
/*
* ECINDAR3-0 are EC-indirect memory address registers.
*
* Enter follow mode by writing 0xf to low nibble of ECINDAR3 register,
* and set high nibble as 0x4 to select internal flash.
*/
IT83XX_SMFI_ECINDAR3 = (EC_INDIRECT_READ_INTERNAL_FLASH | 0xf);
/* Set FSCE# as high level by writing 0 to address xfff_fe00h */
IT83XX_SMFI_ECINDAR2 = 0xFF;
IT83XX_SMFI_ECINDAR1 = 0xFE;
IT83XX_SMFI_ECINDAR0 = 0x00;
/* EC-indirect memory data register */
IT83XX_SMFI_ECINDDR = 0x00;
}
void FLASH_DMA_CODE dma_flash_follow_mode_exit(void)
{
/* Exit follow mode, and keep the setting of selecting internal flash */
IT83XX_SMFI_ECINDAR3 = EC_INDIRECT_READ_INTERNAL_FLASH;
IT83XX_SMFI_ECINDAR2 = 0x00;
}
void FLASH_DMA_CODE dma_flash_fsce_high(void)
{
/* FSCE# high level */
IT83XX_SMFI_ECINDAR1 = 0xFE;
IT83XX_SMFI_ECINDDR = 0x00;
}
uint8_t FLASH_DMA_CODE dma_flash_read_dat(void)
{
/* Read data from FMISO */
return IT83XX_SMFI_ECINDDR;
}
void FLASH_DMA_CODE dma_flash_write_dat(uint8_t wdata)
{
/* Write data to FMOSI */
IT83XX_SMFI_ECINDDR = wdata;
}
void FLASH_DMA_CODE dma_flash_transaction(int wlen, uint8_t *wbuf,
int rlen, uint8_t *rbuf, int cmd_end)
{
int i;
/* FSCE# with low level */
IT83XX_SMFI_ECINDAR1 = 0xFD;
/* Write data to FMOSI */
for (i = 0; i < wlen; i++)
IT83XX_SMFI_ECINDDR = wbuf[i];
/* Read data from FMISO */
for (i = 0; i < rlen; i++)
rbuf[i] = IT83XX_SMFI_ECINDDR;
/* FSCE# high level if transaction done */
if (cmd_end)
dma_flash_fsce_high();
}
void FLASH_DMA_CODE dma_flash_cmd_read_status(enum flash_status_mask mask,
enum flash_status_mask target)
{
uint8_t status[1];
uint8_t cmd_rs[] = {FLASH_CMD_RS};
/*
* We prefer no timeout here. We can always get the status
* we want, or wait for watchdog triggered to check
* e-flash's status instead of breaking loop.
* This will avoid fetching unknown instruction from e-flash
* and causing exception.
*/
while (1) {
/* read status */
dma_flash_transaction(sizeof(cmd_rs), cmd_rs, 1, status, 1);
/* only bit[1:0] valid */
if ((status[0] & mask) == target)
break;
}
}
void FLASH_DMA_CODE dma_flash_cmd_write_enable(void)
{
uint8_t cmd_we[] = {FLASH_CMD_WREN};
/* enter EC-indirect follow mode */
dma_flash_follow_mode();
/* send write enable command */
dma_flash_transaction(sizeof(cmd_we), cmd_we, 0, NULL, 1);
/* read status and make sure busy bit cleared and write enabled. */
dma_flash_cmd_read_status(FLASH_SR_ALL, FLASH_SR_WEL);
/* exit EC-indirect follow mode */
dma_flash_follow_mode_exit();
}
void FLASH_DMA_CODE dma_flash_cmd_write_disable(void)
{
uint8_t cmd_wd[] = {FLASH_CMD_WRDI};
/* enter EC-indirect follow mode */
dma_flash_follow_mode();
/* send write disable command */
dma_flash_transaction(sizeof(cmd_wd), cmd_wd, 0, NULL, 1);
/* make sure busy bit cleared. */
dma_flash_cmd_read_status(FLASH_SR_ALL, FLASH_SR_NO_BUSY);
/* exit EC-indirect follow mode */
dma_flash_follow_mode_exit();
}
void FLASH_DMA_CODE dma_flash_cmd_erase(int addr, int cmd)
{
uint8_t cmd_erase[] = {cmd, ((addr >> 16) & 0xFF),
((addr >> 8) & 0xFF), (addr & 0xFF)};
/* enter EC-indirect follow mode */
dma_flash_follow_mode();
/* send erase command */
dma_flash_transaction(sizeof(cmd_erase), cmd_erase, 0, NULL, 1);
/* make sure busy bit cleared. */
dma_flash_cmd_read_status(FLASH_SR_BUSY, FLASH_SR_NO_BUSY);
/* exit EC-indirect follow mode */
dma_flash_follow_mode_exit();
}
void FLASH_DMA_CODE dma_flash_cmd_write(int addr, int wlen, uint8_t *wbuf)
{
int i;
uint8_t flash_write[] = {FLASH_CMD_WRITE, ((addr >> 16) & 0xFF),
((addr >> 8) & 0xFF), (addr & 0xFF)};
/* enter EC-indirect follow mode */
dma_flash_follow_mode();
/* send flash write command (aai word or page program) */
dma_flash_transaction(sizeof(flash_write), flash_write, 0, NULL, 0);
#ifdef IT83XX_CHIP_FLASH_IS_KGD
for (i = 0; i < wlen; i++) {
/* send data byte */
dma_flash_write_dat(wbuf[i]);
/*
* we want to restart the write sequence every IDEAL_SIZE
* chunk worth of data.
*/
if (!(++addr % CONFIG_FLASH_WRITE_IDEAL_SIZE)) {
uint8_t w_en[] = {FLASH_CMD_WREN};
dma_flash_fsce_high();
/* make sure busy bit cleared. */
dma_flash_cmd_read_status(FLASH_SR_BUSY,
FLASH_SR_NO_BUSY);
/* send write enable command */
dma_flash_transaction(sizeof(w_en), w_en, 0, NULL, 1);
/* make sure busy bit cleared and write enabled. */
dma_flash_cmd_read_status(FLASH_SR_ALL, FLASH_SR_WEL);
/* re-send write command */
flash_write[1] = (addr >> 16) & 0xff;
flash_write[2] = (addr >> 8) & 0xff;
flash_write[3] = addr & 0xff;
dma_flash_transaction(sizeof(flash_write), flash_write,
0, NULL, 0);
}
}
dma_flash_fsce_high();
/* make sure busy bit cleared. */
dma_flash_cmd_read_status(FLASH_SR_BUSY, FLASH_SR_NO_BUSY);
#else
for (i = 0; i < wlen; i += 2) {
dma_flash_write_dat(wbuf[i]);
dma_flash_write_dat(wbuf[i + 1]);
dma_flash_fsce_high();
/* make sure busy bit cleared. */
dma_flash_cmd_read_status(FLASH_SR_BUSY, FLASH_SR_NO_BUSY);
/* resend aai word command without address field */
if ((i + 2) < wlen)
dma_flash_transaction(1, flash_write, 0, NULL, 0);
}
#endif
/* exit EC-indirect follow mode */
dma_flash_follow_mode_exit();
}
uint8_t FLASH_DMA_CODE dma_flash_indirect_fast_read(int addr)
{
IT83XX_SMFI_ECINDAR3 = EC_INDIRECT_READ_INTERNAL_FLASH;
IT83XX_SMFI_ECINDAR2 = (addr >> 16) & 0xFF;
IT83XX_SMFI_ECINDAR1 = (addr >> 8) & 0xFF;
IT83XX_SMFI_ECINDAR0 = (addr & 0xFF);
return IT83XX_SMFI_ECINDDR;
}
int FLASH_DMA_CODE dma_flash_verify(int addr, int size, const char *data)
{
int i;
uint8_t *wbuf = (uint8_t *)data;
uint8_t *flash = (uint8_t *)addr;
/* verify for erase */
if (data == NULL) {
for (i = 0; i < size; i++) {
if (flash[i] != 0xFF)
return EC_ERROR_UNKNOWN;
}
/* verify for write */
} else {
for (i = 0; i < size; i++) {
if (flash[i] != wbuf[i])
return EC_ERROR_UNKNOWN;
}
}
return EC_SUCCESS;
}
void FLASH_DMA_CODE dma_flash_write(int addr, int wlen, const char *wbuf)
{
dma_flash_cmd_write_enable();
dma_flash_cmd_write(addr, wlen, (uint8_t *)wbuf);
dma_flash_cmd_write_disable();
}
void FLASH_DMA_CODE dma_flash_erase(int addr, int cmd)
{
dma_flash_cmd_write_enable();
dma_flash_cmd_erase(addr, cmd);
dma_flash_cmd_write_disable();
}
static enum flash_wp_status flash_check_wp(void)
{
enum flash_wp_status wp_status;
int all_bank_count, bank;
all_bank_count = CONFIG_FLASH_SIZE / CONFIG_FLASH_BANK_SIZE;
for (bank = 0; bank < all_bank_count; bank++) {
if (!(IT83XX_GCTRL_EWPR0PFEC(FWP_REG(bank)) & FWP_MASK(bank)))
break;
}
if (bank == WP_BANK_COUNT)
wp_status = FLASH_WP_STATUS_PROTECT_RO;
else if (bank == (WP_BANK_COUNT + PSTATE_BANK_COUNT))
wp_status = FLASH_WP_STATUS_PROTECT_RO;
else if (bank == all_bank_count)
wp_status = FLASH_WP_STATUS_PROTECT_ALL;
else
wp_status = 0;
return wp_status;
}
/**
* Protect flash banks until reboot.
*
* @param start_bank Start bank to protect
* @param bank_count Number of banks to protect
*/
static void flash_protect_banks(int start_bank,
int bank_count,
enum flash_wp_interface wp_if)
{
int bank;
for (bank = start_bank; bank < start_bank + bank_count; bank++) {
if (wp_if & FLASH_WP_EC)
IT83XX_GCTRL_EWPR0PFEC(FWP_REG(bank)) |= FWP_MASK(bank);
if (wp_if & FLASH_WP_HOST)
IT83XX_GCTRL_EWPR0PFH(FWP_REG(bank)) |= FWP_MASK(bank);
if (wp_if & FLASH_WP_DBGR)
IT83XX_GCTRL_EWPR0PFD(FWP_REG(bank)) |= FWP_MASK(bank);
}
}
int FLASH_DMA_CODE flash_physical_read(int offset, int size, char *data)
{
int i;
for (i = 0; i < size; i++) {
data[i] = dma_flash_indirect_fast_read(offset);
offset++;
}
return EC_SUCCESS;
}
/**
* Write to physical flash.
*
* Offset and size must be a multiple of CONFIG_FLASH_WRITE_SIZE.
*
* @param offset Flash offset to write.
* @param size Number of bytes to write.
* @param data Data to write to flash. Must be 32-bit aligned.
*/
int FLASH_DMA_CODE flash_physical_write(int offset, int size, const char *data)
{
int ret = EC_ERROR_UNKNOWN;
if (flash_dma_code_enabled == 0)
return EC_ERROR_ACCESS_DENIED;
if (all_protected)
return EC_ERROR_ACCESS_DENIED;
watchdog_reload();
/*
* CPU can't fetch instruction from flash while use
* EC-indirect follow mode to access flash, interrupts need to be
* disabled.
*/
interrupt_disable();
dma_flash_write(offset, size, data);
dma_reset_immu((offset + size) >= IMMU_TAG_INDEX_BY_DEFAULT);
/*
* Internal flash of N8 or RISC-V core is ILM(Instruction Local Memory)
* mapped, but RISC-V's ILM base address is 0x80000000.
*
* Ensure that we will get the ILM address of a flash offset.
*/
offset |= CONFIG_MAPPED_STORAGE_BASE;
ret = dma_flash_verify(offset, size, data);
interrupt_enable();
return ret;
}
/**
* Erase physical flash.
*
* Offset and size must be a multiple of CONFIG_FLASH_ERASE_SIZE.
*
* @param offset Flash offset to erase.
* @param size Number of bytes to erase.
*/
int FLASH_DMA_CODE flash_physical_erase(int offset, int size)
{
int v_size = size, v_addr = offset, ret = EC_ERROR_UNKNOWN;
if (flash_dma_code_enabled == 0)
return EC_ERROR_ACCESS_DENIED;
if (all_protected)
return EC_ERROR_ACCESS_DENIED;
/*
* CPU can't fetch instruction from flash while use
* EC-indirect follow mode to access flash, interrupts need to be
* disabled.
*/
interrupt_disable();
/* Always use sector erase command (1K or 4K bytes) */
for (; size > 0; size -= FLASH_SECTOR_ERASE_SIZE) {
dma_flash_erase(offset, FLASH_CMD_SECTOR_ERASE);
offset += FLASH_SECTOR_ERASE_SIZE;
}
dma_reset_immu((v_addr + v_size) >= IMMU_TAG_INDEX_BY_DEFAULT);
/* get the ILM address of a flash offset. */
v_addr |= CONFIG_MAPPED_STORAGE_BASE;
ret = dma_flash_verify(v_addr, v_size, NULL);
interrupt_enable();
return ret;
}
/**
* Read physical write protect setting for a flash bank.
*
* @param bank Bank index to check.
* @return non-zero if bank is protected until reboot.
*/
int flash_physical_get_protect(int bank)
{
return IT83XX_GCTRL_EWPR0PFEC(FWP_REG(bank)) & FWP_MASK(bank);
}
/**
* Protect flash now.
*
* @param all Protect all (=1) or just read-only and pstate (=0).
* @return non-zero if error.
*/
int flash_physical_protect_now(int all)
{
if (all) {
/* Protect the entire flash */
flash_protect_banks(0,
CONFIG_FLASH_SIZE / CONFIG_FLASH_BANK_SIZE,
FLASH_WP_EC);
all_protected = 1;
} else {
/* Protect the read-only section and persistent state */
flash_protect_banks(WP_BANK_OFFSET,
WP_BANK_COUNT, FLASH_WP_EC);
#ifdef PSTATE_BANK
flash_protect_banks(PSTATE_BANK,
PSTATE_BANK_COUNT, FLASH_WP_EC);
#endif
}
/*
* bit[0], eflash protect lock register which can only be write 1 and
* only be cleared by power-on reset.
*/
IT83XX_GCTRL_EPLR |= 0x01;
return EC_SUCCESS;
}
/**
* Return flash protect state flags from the physical layer.
*
* This should only be called by flash_get_protect().
*
* Uses the EC_FLASH_PROTECT_* flags from ec_commands.h
*/
uint32_t flash_physical_get_protect_flags(void)
{
uint32_t flags = 0;
flags |= flash_check_wp();
if (all_protected)
flags |= EC_FLASH_PROTECT_ALL_NOW;
/* Check if blocks were stuck locked at pre-init */
if (stuck_locked)
flags |= EC_FLASH_PROTECT_ERROR_STUCK;
/* Check if flash protection is in inconsistent state at pre-init */
if (inconsistent_locked)
flags |= EC_FLASH_PROTECT_ERROR_INCONSISTENT;
return flags;
}
/**
* Return the valid flash protect flags.
*
* @return A combination of EC_FLASH_PROTECT_* flags from ec_commands.h
*/
uint32_t flash_physical_get_valid_flags(void)
{
return EC_FLASH_PROTECT_RO_AT_BOOT |
EC_FLASH_PROTECT_RO_NOW |
EC_FLASH_PROTECT_ALL_NOW;
}
/**
* Return the writable flash protect flags.
*
* @param cur_flags The current flash protect flags.
* @return A combination of EC_FLASH_PROTECT_* flags from ec_commands.h
*/
uint32_t flash_physical_get_writable_flags(uint32_t cur_flags)
{
uint32_t ret = 0;
/* If RO protection isn't enabled, its at-boot state can be changed. */
if (!(cur_flags & EC_FLASH_PROTECT_RO_NOW))
ret |= EC_FLASH_PROTECT_RO_AT_BOOT;
/*
* If entire flash isn't protected at this boot, it can be enabled if
* the WP GPIO is asserted.
*/
if (!(cur_flags & EC_FLASH_PROTECT_ALL_NOW) &&
(cur_flags & EC_FLASH_PROTECT_GPIO_ASSERTED))
ret |= EC_FLASH_PROTECT_ALL_NOW;
return ret;
}
static void flash_code_static_dma(void)
{
/* Make sure no interrupt while enable static DMA */
interrupt_disable();
/* invalid static DMA first */
if (IS_ENABLED(CHIP_CORE_RISCV))
IT83XX_GCTRL_RVILMCR0 &= ~ILMCR_ILM2_ENABLE;
IT83XX_SMFI_SCAR2H = 0x08;
/* Enable DLM 56k~60k region and than copy data into it */
if (IS_ENABLED(CHIP_CORE_NDS32))
IT83XX_GCTRL_MCCR2 |= IT83XX_DLM14_ENABLE;
memcpy((void *)CHIP_RAMCODE_BASE, (const void *)FLASH_DMA_START,
IT83XX_ILM_BLOCK_SIZE);
if (IS_ENABLED(CHIP_CORE_RISCV))
IT83XX_GCTRL_RVILMCR0 |= ILMCR_ILM2_ENABLE;
/* Disable DLM 56k~60k region and be the ram code section */
if (IS_ENABLED(CHIP_CORE_NDS32))
IT83XX_GCTRL_MCCR2 &= ~IT83XX_DLM14_ENABLE;
/*
* Enable ILM
* Set the logic memory address(flash code of RO/RW) in eflash
* by programming the register SCARx bit19-bit0.
*/
IT83XX_SMFI_SCAR2L = FLASH_DMA_START & 0xFF;
IT83XX_SMFI_SCAR2M = (FLASH_DMA_START >> 8) & 0xFF;
#ifdef IT83XX_DAM_ADDR_BIT19_AT_REG_SCARXH_BIT7
IT83XX_SMFI_SCAR2H = (FLASH_DMA_START >> 16) & 0x7;
if (FLASH_DMA_START & BIT(19))
IT83XX_SMFI_SCAR2H |= BIT(7);
else
IT83XX_SMFI_SCAR2H &= ~BIT(7);
#else
IT83XX_SMFI_SCAR2H = (FLASH_DMA_START >> 16) & 0x0F;
#endif
/*
* Validate Direct-map SRAM function by programming
* register SCARx bit20=0
*/
IT83XX_SMFI_SCAR2H &= ~0x10;
flash_dma_code_enabled = 0x01;
interrupt_enable();
}
/**
* Initialize the module.
*
* Applies at-boot protection settings if necessary.
*/
int flash_pre_init(void)
{
int32_t reset_flags, prot_flags, unwanted_prot_flags;
/* By default, select internal flash for indirect fast read. */
IT83XX_SMFI_ECINDAR3 = EC_INDIRECT_READ_INTERNAL_FLASH;
if (IS_ENABLED(IT83XX_CHIP_FLASH_IS_KGD))
IT83XX_SMFI_FLHCTRL6R |= IT83XX_SMFI_MASK_ECINDPP;
flash_code_static_dma();
reset_flags = system_get_reset_flags();
prot_flags = flash_get_protect();
unwanted_prot_flags = EC_FLASH_PROTECT_ALL_NOW |
EC_FLASH_PROTECT_ERROR_INCONSISTENT;
/*
* If we have already jumped between images, an earlier image could
* have applied write protection. Nothing additional needs to be done.
*/
if (reset_flags & EC_RESET_FLAG_SYSJUMP)
return EC_SUCCESS;
if (prot_flags & EC_FLASH_PROTECT_GPIO_ASSERTED) {
/* Protect the entire flash of host interface */
flash_protect_banks(0,
CONFIG_FLASH_SIZE / CONFIG_FLASH_BANK_SIZE,
FLASH_WP_HOST);
/* Protect the entire flash of DBGR interface */
flash_protect_banks(0,
CONFIG_FLASH_SIZE / CONFIG_FLASH_BANK_SIZE,
FLASH_WP_DBGR);
/*
* Write protect is asserted. If we want RO flash protected,
* protect it now.
*/
if ((prot_flags & EC_FLASH_PROTECT_RO_AT_BOOT) &&
!(prot_flags & EC_FLASH_PROTECT_RO_NOW)) {
int rv = flash_set_protect(EC_FLASH_PROTECT_RO_NOW,
EC_FLASH_PROTECT_RO_NOW);
if (rv)
return rv;
/* Re-read flags */
prot_flags = flash_get_protect();
}
} else {
/* Don't want RO flash protected */
unwanted_prot_flags |= EC_FLASH_PROTECT_RO_NOW;
}
/* If there are no unwanted flags, done */
if (!(prot_flags & unwanted_prot_flags))
return EC_SUCCESS;
/*
* If the last reboot was a power-on reset, it should have cleared
* write-protect. If it didn't, then the flash write protect registers
* have been permanently committed and we can't fix that.
*/
if (reset_flags & EC_RESET_FLAG_POWER_ON) {
stuck_locked = 1;
return EC_ERROR_ACCESS_DENIED;
} else {
/*
* Set inconsistent flag, because there is no software
* reset can clear write-protect.
*/
inconsistent_locked = 1;
return EC_ERROR_ACCESS_DENIED;
}
/* That doesn't return, so if we're still here that's an error */
return EC_ERROR_UNKNOWN;
}
|
aacd0f7f7fef06dd9e8b5742f623b6b74cd66814
|
6ac836e1407adf108a31600c7b9b83786f10a473
|
/src/ConEmu/resource.h
|
33109306d7f46eb58ee0bd5205396e1541109933
|
[
"BSD-3-Clause"
] |
permissive
|
Maximus5/ConEmu
|
d618cc620d69a0bdf4fb19d6d5593becf561b5e6
|
740b09c363cb16fbb730d72c53eaca1c530a016e
|
refs/heads/master
| 2023-08-08T12:53:57.054618
| 2023-07-24T00:05:45
| 2023-07-24T00:05:45
| 2,857,373
| 8,870
| 768
|
BSD-3-Clause
| 2023-07-23T13:17:02
| 2011-11-26T19:48:52
|
C++
|
UTF-8
|
C
| false
| false
| 61,103
|
h
|
resource.h
|
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by ConEmu.rc
//
#define IDI_ICON1 1
#define IDI_ICON2 2
#define IDI_ICON3 3
#define IDI_ICON4 4
#define ID_GO 20
#define ID_ATTACH 21
#define IDB_MAIN_TOOLBAR 101
#define IDB_SHIELD 102
#define IDB_RIGHTCLICKING 103
#define IDB_SCROLL 104
#define IDB_SHIELD16 107
#define IDB_SEARCH 108
#define IDB_DONATE 109
#define IDB_FLATTR 110
#define IDC_COPY 120
#define IDC_LINK 121
#define IDC_MOVE 122
#define IDD_RESTART 123
#define IDC_SPLITV 124
#define IDC_SPLITH 125
#define IDC_SPLITV2 126
#define IDD_SETTINGS 150
#define IDD_SPG_FONTS 151
#define IDD_SPG_COLORS 152
#define IDD_SPG_INFO 153
#define IDD_SPG_FEATURES 154
#define IDD_SPG_DEBUG 155
#define IDD_SPG_FEATURE_FAR 156
#define IDD_SPG_TASKS 157
#define IDD_SPG_APPDISTINCT 158
#define IDD_SPG_COMSPEC 159
#define IDD_SPG_STARTUP 160
#define IDD_SPG_STATUSBAR 161
#define IDD_SPG_APPDISTINCT2 162
#define IDD_SPG_CURSOR 163
#define IDD_SPG_INTEGRATION 164
#define IDD_SPG_TRANSPARENT 165
#define IDD_SPG_SIZEPOS 167
#define IDD_SPG_MARKCOPY 168
#define IDD_SPG_TABS 169
#define IDD_SPG_VIEWS 170
#define IDD_SPG_KEYS 171
#define IDD_SPG_UPDATE 172
#define IDD_SPG_APPEAR 174
#define IDD_SPG_TASKBAR 175
#define IDD_SPG_DEFTERM 176
#define IDD_SPG_FARMACRO 177
#define IDD_SPG_HIGHLIGHT 178
#define IDD_SPG_PASTE 179
#define IDD_SPG_CONFIRM 180
#define IDD_SPG_HISTORY 181
#define IDD_SPG_BACKGR 182
#define IDD_SPG_ENVIRONMENT 183
#define IDD_SPG_KEYBOARD 184
#define IDD_SPG_MOUSE 185
#define IDD_SPG_QUAKE 186
#define IDD_SPG_CHILDGUI 187
#define IDD_SPG_ANSI 188
#define IDD_SPG_GENERAL 189
#define IDD_MORE_CONFONT 209
#define IDD_MORE_DOSBOX 210
#define IDD_ATTACHDLG 212
#define IDD_FAST_CONFIG 215
#define IDD_FIND 217
#define IDD_ABOUT 218
#define IDD_RENAMETAB 219
#define IDD_CMDPROMPT 220
#define IDD_HELP 221
#define IDD_ACTION 222
#define IDD_HOTKEY 223
#define IDD_AFFINITY 226
#define c0 1000
#define c1 1001
#define c2 1002
#define c3 1003
#define c4 1004
#define c5 1005
#define c6 1006
#define c7 1007
#define c8 1008
#define c9 1009
#define c10 1010
#define c11 1011
#define c12 1012
#define c13 1013
#define c14 1014
#define c15 1015
#define c32 1032
#define c33 1033
#define c34 1034
#define c35 1035
#define c36 1036
#define c37 1037
#define c38 1038
#define tc0 1100
#define tc1 1101
#define tc2 1102
#define tc3 1103
#define tc4 1104
#define tc5 1105
#define tc6 1106
#define tc7 1107
#define tc8 1108
#define tc9 1109
#define tc10 1110
#define tc11 1111
#define tc12 1112
#define tc13 1113
#define tc14 1114
#define tc15 1115
#define tc32 1132
#define tc33 1133
#define tc34 1134
#define tc35 1135
#define tc36 1136
#define tc37 1137
#define tc38 1138
#define bChooseFont 1201
#define rNoneAA 1202
#define rStandardAA 1203
#define rCTAA 1204
#define cbFullScreen 1205
#define tFont 1206
#define cbFixFarBorders 1207
#define cbCursorColor 1210
#define rNormal 1311
#define rMaximized 1312
#define rFullScreen 1313
#define gbPerformance 1400
#define lbLDragKey 1501
#define cbDropEnabled 1502
#define lbRDragKey 1503
#define cbDragL 1504
#define cbDragR 1505
#define cbMultiCon 1506
#define cbMinToTray 1507
#define tCurCmdLine 1508
#define tsTopPID 1510
#define tFontFace 1511
#define tFontSizeY 1512
#define tFontCharset 1513
#define tFontFace2 1514
#define tCmdLine 1516
#define tRealFontMain 1517
#define tRealFontBorders 1518
#define cbApplyPos 1520
#define cbCursorBlink 1522
#define IDC_RESTART_ICON 1523
#define IDC_START 1524
#define IDC_TERMINATE 1525
#define IDC_RESTART_CMD 1527
#define IDC_CHOOSE 1528
#define gbStartCommand 1529
#define IDC_WARNING 1530
#define cbTabSelf 1531
#define cbTabLazy 1532
#define cbTabRecent 1533
#define cbLongOutput 1534
#define tLongOutputHeight 1535
#define cbRSelectionFix 1536
#define cbMonitorConsoleLang 1537
#define cbSkipFocusEvents 1538
#define cbSkipActivation 1542
#define cbSkipMove 1543
#define gbStandardColors 1544
#define cbVisible 1545
#define cbNewConfirm 1546
#define cbRunAsAdmin 1547
#define cbDragImage 1548
#define cbAutoRegFonts 1550
#define cbDebugSteps 1551
#define cbDragIcons 1553
#define lbDefaultColors 1554
#define lbNtvdmHeight 1559
#define IDC_CONSOLE_STATES 1560
#define cbFARuseASCIIsort 1561
#define cbFixAltOnAltTab 1562
#define cbFarHourglass 1563
#define slTransparent 1564
#define cbHideCaption 1565
#define cbFontAuto 1566
#define cbDragPanel 1568
#define cbHideCaptionAlways 1569
#define cbTryToCenter 1570
#define cbAlwaysOnTop 1572
#define cbUserScreenTransparent 1573
#define cbTransparent 1574
#define tBgImageColors 1575
#define cbExtendFonts 1576
#define lbExtendFontBoldIdx 1577
#define cbTrueColorer 1578
#define cbDropUnlocked 1579
#define cbDropUseBCopy 1580
#define cbFadeInactive 1581
#define tHideCaptionAlwaysFrame 1589
#define tHideCaptionAlwaysDelay 1590
#define tHideCaptionAlwaysDissapear 1591
#define bMultiConHotkeys 1592
#define cbMultiConKeybHooks 1593
#define bTabTemplates 1594
#define bResetSettings 1595
#define bReloadSettings 1596
#define tConSizeChr 1597
#define tConLeftTop 1598
#define tDCSize 1599
#define tPanelLeft 1600
#define tPanelRight 1601
#define IDC_CHOOSE_DIR 1602
#define IDC_STARTUP_DIR 1603
#define bRClick 1607
#define bRealConsoleSettings 1608
#define bDropSettings 1609
#define bSaveSettings 1610
#define cbHandleFarDetach 1619
#define tCursorPos 1622
#define tFadeLow 1624
#define tFadeHigh 1625
#define cbToolbar 1626
#define cbCTSTextSelection 1630
#define lbCTSMBtnAction 1631
#define lbCTSRBtnAction 1632
#define lbCTSBlockSelection 1633
#define lbCTSTextSelection 1634
#define cbCTSBlockSelection 1635
#define lbCTSForeIdx 1636
#define lbCTSBackIdx 1637
#define tTabConsole 1638
#define tTabEditor 1639
#define tTabViewer 1640
#define tTabEditorMod 1641
#define cbHideInactiveConTabs 1642
#define tTabLenMax 1643
#define tTabPanels 1644
#define lbCTSActAlways 1645
#define tAdminSuffix 1647
#define cbUseWinNumber 1648
#define cbInstallKeybHooks 1649
#define cbRunAsRestricted 1650
#define cbRunAsNetOnly 1651
#define tRunAsUser 1652
#define tRunAsPassword 1653
#define cbSafeFarClose 1654
#define cbCursorIgnoreSize 1655
#define rbCurrentUser 1656
#define rbAnotherUser 1657
#define tThumbsFontName 1659
#define tThumbsFontSize 1660
#define tTilesFontName 1661
#define tThumbMaxZoom 1662
#define cbThumbLoadFolders 1663
#define cbThumbLoadFiles 1664
#define tThumbFullSize 1665
#define tTilesFontSize 1666
#define cbThumbPreviewBox 1667
#define cbThumbSelectionBox 1668
#define tThumbLabelHeight 1669
#define rbThumbBackColorIdx 1670
#define rbThumbBackColorRGB 1671
#define lbThumbBackColorIdx 1672
#define rbThumbPreviewBoxColorIdx 1673
#define rbThumbPreviewBoxColorRGB 1674
#define lbThumbPreviewBoxColorIdx 1675
#define rbThumbSelectionBoxColorIdx 1676
#define rbThumbSelectionBoxColorRGB 1677
#define lbThumbSelectionBoxColorIdx 1678
#define tThumbLoadingTimeout 1679
#define cbThumbUsePicView2 1680
#define tTilesImgSize 1681
#define tThumbsImgSize 1682
#define rbThumbCachePluginFolder 1687
#define rbThumbCacheUserFolder 1688
#define rbThumbCacheDisabled 1689
#define rbThumbCacheSpecifiedFolder 1690
#define cbThumbCacheFolder 1691
#define tThumbCacheFolder 1692
#define cbRClick 1696
#define tBgImage 1697
#define tDarker 1698
#define cbBgImage 1699
#define tThumbSupportedExtensions 1700
#define cbTilesPreviewBox 1701
#define cbTilesSelectionBox 1702
#define tThumbsX1 1703
#define tThumbsY1 1704
#define tThumbsX2 1705
#define tThumbsY2 1706
#define tThumbsSpacing 1707
#define tThumbsPadding 1708
#define tTilesX1 1709
#define tTilesY1 1710
#define tTilesX2 1711
#define tTilesY2 1712
#define tTilesSpacing 1713
#define tTilesPadding 1714
#define bApplyViewSettings 1715
#define bConFontOK 1716
#define cbActivityReset 1717
#define cbDisableFarFlashing 1718
#define cbDisableAllFlashing 1719
#define cbThumbRestoreOnStartup 1720
#define cbSleepInBackground 1721
#define cbExtendUCharMap 1722
#define cbAutoSaveSizePos 1723
#define bDosBoxSettings 1724
#define cbShellNoZoneCheck 1725
#define bConFontCancel 1726
#define tConsoleFontFace 1727
#define tConsoleFontSizeY 1728
#define tConsoleFontSizeX 1729
#define bConFontAdd2HKLM 1730
#define tConsoleFontHklmNote 1731
#define tConsoleFontConsoleNote 1732
#define cbBgAllowPlugin 1734
#define cbAlwaysShowTrayIcon 1736
#define cbLogShellActivity 1740
#define cbLogInputActivity 1741
#define lbActivityLog 1742
#define gbActivityLog 1744
#define cbActivitySaveAs 1746
#define rbActivityDisabled 1747
#define rbActivityShell 1748
#define ebActivityApp 1750
#define ebActivityParm 1751
#define cbUseInjects 1752
#define cbDosBox 1753
#define ebDosBoxPath 1754
#define bDosBoxPath 1755
#define ebDosBoxForceConfig 1756
#define bDosBoxForceConfig 1757
#define ebDosBoxDrives 1758
#define ebDosBoxAutoexec 1759
#define tsRConFlags 1760
#define rbActivityInput 1762
#define cbUseWinTab 1764
#define cbFarGotoEditor 1765
#define lbFarGotoEditorVk 1766
#define hkHotKeySelect 1767
#define cbUseWinArrows 1768
#define stHotKeySelect 1769
#define stHotModifierSelect 1770
#define lbConEmuHotKeys 1771
#define IDC_ATTACHLIST 1774
#define IDC_REFRESH 1776
#define cbSendAltTab 1777
#define cbSendAltEsc 1778
#define cbSendAltPrintScrn 1779
#define cbSendPrintScrn 1780
#define cbSendCtrlEsc 1781
#define cbDosBoxForceConfig 1783
#define vkMinimizeRestore 2000
#define vkMultiNew 2001
#define vkMultiNext 2002
#define vkMultiRecreate 2003
#define vkMultiBuffer 2004
#define vkMultiClose 2005
#define vkMultiCmd 2006
#define vkCTSVkBlock 2007
#define vkCTSVkText 2008
#define vkCTSVkAct 2009
#define vkFarGotoEditorVk 2010
#define vkLDragKey 2011
#define vkRDragKey 2012
#define vkWinAltP 2013
#define vkWinAltSpace 2014
#define vkMaximize 2015
#define vkCtrlWinAltSpace 2016
#define vkAltEnter 2017
#define vkSystemMenu 2018
#define vkCtrlUp 2019
#define vkCtrlDown 2020
#define vkCtrlPgUp 2021
#define vkCtrlPgDn 2022
#define vkCtrlTab 2023
#define vkCtrlShiftTab 2024
#define vkCtrlTab_Left 2025
#define vkCtrlTab_Right 2026
#define vkCtrlTab_Up 2027
#define vkCtrlTab_Down 2028
#define vkCtrlWinEnter 2029
#define vkMultiNextShift 2030
#define vkConsole_1 2031
#define vkConsole_2 2032
#define vkConsole_3 2033
#define vkConsole_4 2034
#define vkConsole_5 2035
#define vkConsole_6 2036
#define vkConsole_7 2037
#define vkConsole_8 2038
#define vkConsole_9 2039
#define vkConsole_10 2040
#define vkConsole_11 2041
#define vkConsole_12 2042
#define vkMultiNewConfirm 2043
#define vkWinLeft 2044
#define vkWinRight 2045
#define vkWinUp 2046
#define vkWinDown 2047
#define cbTabsOnTaskBar 2048
#define tvSetupCategories 2049
#define tSetupPagePlace 2050
#define tUpdateVerLocation 2052
#define cbShowFarWindows 2053
#define rbUpdateStableOnly 2054
#define rbUpdatePreview 2055
#define rbUpdateLatestAvailable 2056
#define cbUpdateCheckOnStartup 2058
#define cbUpdateUseProxy 2059
#define tUpdateProxy 2060
#define tUpdateProxyUser 2061
#define tUpdateProxyPassword 2062
#define tUpdateDownloadPath 2063
#define cbUpdateDownloadPath 2064
#define cbUpdateLeavePackages 2065
#define tUpdatePostUpdateCmd 2066
#define cbUpdateCheckHourly 2067
#define cbUpdateConfirmDownload 2068
#define rbActivityComm 2069
#define rbUpdateUseExe 2070
#define rbUpdateUseArc 2071
#define tUpdateArcCmdLine 2072
#define cbUpdateArcCmdLine 2073
#define tUpdateExeCmdLine 2074
#define tRClickMacro 2075
#define cbEnhanceButtons 2076
#define tCloseTabMacro 2078
#define tSaveAllMacro 2079
#define tSafeFarCloseMacro 2080
#define stUpdateProxy 2083
#define stUpdateProxyUser 2084
#define stUpdateProxyPassword 2085
#define cbUseKeyboardHooksFast 2086
#define cbEnableAutoUpdateFast 2087
#define cbDisableConImeFast 2090
#define stEnableAutoUpdateFast 2093
#define stDisableConImeFast1 2094
#define stDisableConImeFast2 2095
#define stDisableConImeFast3 2096
#define gbDisableConImeFast 2097
#define cbInjectConEmuHkFast 2098
#define lbHotKeyList 2101
#define cbDragPanelBothEdges 2102
#define stHomePage 2103
#define cbMultiIterate 2104
#define tGuiMacro 2105
#define tTabFontFace 2106
#define tTabFontHeight 2107
#define tTabFontCharset 2108
#define cbAdminShield 2109
#define cbAdminSuffix 2110
#define vkTabMenu 2111
#define vkCTSVkBlockStart 2112
#define vkCTSVkTextStart 2113
#define cbKeyBarRClick 2114
#define gbCmdTasks 2115
#define lbCmdTasks 2116
#define tCmdGroupName 2117
#define tCmdGroupCommands 2118
#define stCmdTasks 2119
#define stCmdGroupName 2120
#define stCmdGroupCommands 2121
#define cbCmdTasksAdd 2122
#define cbColorSchemeSave 2123
#define cbCmdTasksDel 2124
#define cbColorSchemeDelete 2125
#define cbCmdTasksUp 2126
#define cbCmdTasksDown 2127
#define cbCmdGroupApp 2128
#define cbCmdTasksParm 2129
#define cbCmdTasksSave 2130
#define cbCmdTasksReload 2131
#define cbCmdTaskbarTasks 2132
#define cbCmdTaskbarCommands 2133
#define gbCmdTasks7 2134
#define tAppDistinctName 2135
#define cbAppDistinctAdd 2136
#define cbAppDistinctDel 2137
#define cbAppDistinctUp 2138
#define cbAppDistinctDown 2139
#define cbAppDistinctReload 2140
#define rbAppDistinctElevatedOn 2141
#define rbAppDistinctElevatedOff 2142
#define rbAppDistinctElevatedIgnore 2143
#define cbExtendFontsOverride 2144
#define cbCursorOverride 2145
#define cbColorsOverride 2146
#define lbColorsOverride 2147
#define rbComspecAuto 2148
#define rbComspecEnvVar 2149
#define rbComspecCmd 2150
#define rbComspecExplicit 2151
#define tComspecExplicit 2152
#define cbComspecExplicit 2153
#define gbCmdRun 2154
#define gbComspec 2155
#define gbComspecBits 2156
#define rbComspec_OSbit 2157
#define rbComspec_AppBit 2158
#define rbComspec_x32 2159
#define cbComspecUpdateEnv 2160
#define cbComspecTest 2162
#define gbFeatureMisc 2163
#define gbFeatureAppear 2164
#define gbFeatureCaption 2165
#define gbFeatureClipboard 2166
#define cbClipConfirmEnter 2171
#define cbClipboardOverride 2172
#define tFindText 2173
#define cbFindWholeWords 2174
#define cbFindMatchCase 2175
#define cbFindFreezeConsole 2176
#define cbFindNext 2177
#define cbFindPrev 2178
#define cbCloseConsoleConfirm 2179
#define gbKeyModifiers 2180
#define vkPicViewSlide 2181
#define vkPicViewSlower 2182
#define vkPicViewFaster 2183
#define lbHotKeyMod1 2186
#define lbHotKeyMod2 2187
#define lbHotKeyMod3 2188
#define stGuiMacro 2189
#define vkGuiMacro01 2190
#define vkGuiMacro02 2191
#define vkGuiMacro03 2192
#define vkGuiMacro04 2193
#define vkGuiMacro05 2194
#define vkGuiMacro06 2195
#define vkGuiMacro07 2196
#define vkGuiMacro08 2197
#define vkGuiMacro09 2198
#define vkGuiMacro10 2199
#define vkGuiMacro11 2200
#define vkGuiMacro12 2201
#define vkGuiMacro13 2202
#define vkGuiMacro14 2203
#define vkGuiMacro15 2204
#define vkGuiMacro16 2205
#define vkGuiMacro17 2206
#define vkGuiMacro18 2207
#define vkGuiMacro19 2208
#define vkGuiMacro20 2209
#define vkGuiMacro21 2210
#define vkGuiMacro22 2211
#define vkGuiMacro23 2212
#define vkGuiMacro24 2213
#define vkGuiMacro25 2214
#define vkGuiMacro26 2215
#define vkGuiMacro27 2216
#define vkGuiMacro28 2217
#define vkGuiMacro29 2218
#define vkGuiMacro30 2219
#define vkGuiMacro31 2220
#define vkGuiMacro32 2221
#define vkShowTabsList 2222
#define vkPasteText 2223
#define vkPasteFirstLine 2224
#define cbClipConfirmLimit 2225
#define tClipConfirmLimit 2226
#define stClipConfirmLimit 2227
#define cbFindHighlightAll 2228
#define gbFindText 2229
#define vkFindTextDlg 2230
#define cbFindTransparent 2232
#define rbStartSingleApp 2233
#define rbStartTasksFile 2234
#define rbStartNamedTask 2235
#define rbStartLastTabs 2236
#define cbStartFarRestoreFolders 2237
#define cbStartFarRestoreEditors 2238
#define tStartTasksFile 2239
#define lbStartNamedTask 2240
#define stExtendFontBoldIdx 2241
#define stExtendFontItalicIdx 2242
#define stExtendFontNormalIdx 2243
#define cbCmdLine 2244
#define cbStartTasksFile 2245
#define cbDropUseMenu 2246
#define stConEmuIcon 2247
#define tbAboutTabs 2248
#define tAboutText 2249
#define stConEmuAbout 2250
#define stConEmuUrl 2251
#define vkMultiNewPopup 2252
#define cbProcessAnsi 2253
#define vkMultiAltCon 2254
#define lbGotoEditorCmd 2255
#define stGotoEditorCmd 2256
#define cbCTSFreezeBeforeSelect 2257
#define bGotoEditorCmd 2259
#define vkForceFullScreen 2260
#define vkTerminateApp 2261
#define cbShowStatusBar 2262
#define cbStatusActiveVCon 2263
#define cbStatusWindowPos 2264
#define cbStatusWindowSize 2265
#define cbStatusActiveBuffer 2266
#define cbStatusConsolePos 2267
#define cbStatusConsoleSize 2268
#define cbStatusBufferSize 2269
#define cbStatusCursorX 2270
#define cbStatusCursorY 2271
#define cbStatusCursorSize 2272
#define cbStatusCursorInfo 2273
#define cbStatusServer 2274
#define tStatusFontFace 2275
#define tStatusFontHeight 2276
#define tStatusFontCharset 2277
#define cbBold 2278
#define tFontSizeX 2279
#define cbItalic 2280
#define tWndWidth 2281
#define tWndHeight 2282
#define cbMonospace 2283
#define tFontSizeX2 2284
#define slDarker 2285
#define cbDnDCopy 2287
#define cbTabs 2288
#define cbEnhanceGraphics 2289
#define tFontSizeX3 2290
#define bBgImage 2291
#define tWndX 2295
#define tWndY 2296
#define cbPosFixed 2297
#define lbExtendFontItalicIdx 2300
#define lbExtendFontNormalIdx 2301
#define rCascade 2302
#define rFixed 2303
#define lbProcesses 2304
#define cbStatusWindowClient 2305
#define cbStatusWindowWorkspace 2306
#define cbStatusCapsLock 2307
#define cbStatusTransparency 2308
#define cbStatusNumLock 2309
#define cbStatusScrlLock 2310
#define cbStatusInputLang 2311
#define cbColorKeyTransparent 2312
#define cbEnableMouse 2313
#define vkMultiNewAttach 2314
#define vkScreenshot 2315
#define tTabSkipWords 2316
#define gbAppDistinct 2317
#define lbAppDistinct 2318
#define stAppDistinctName 2319
#define cbCmdTaskbarUpdate 2320
#define cbStatusGuiPID 2321
#define tCmdGroupGuiArg 2322
#define stCmdGroupGuiArg 2323
#define vkWinAltA 2324
#define vkShowStatusBar 2325
#define vkShowTabBar 2326
#define vkAlwaysOnTop 2327
#define vkScreenshotFull 2328
#define vkMultiWndConfirm 2329
#define cbRunInNewWindow 2330
#define cbQuakeStyle 2333
#define cbGuiMacroHelp 2334
#define vkRenameTab 2335
#define stNewTabName 2336
#define tNewTabName 2337
#define stBgPlacement 2338
#define lbBgPlacement 2339
#define cbCTSAutoCopy 2340
#define cbStatusGuiHwnd 2341
#define cbStatusViewHwnd 2342
#define cbStatusRealHwnd 2343
#define cbCTSClickPromptPosition 2344
#define lbCTSClickPromptPosition 2345
#define vkCTSVkPromptClk 2346
#define gbPromptOverride 2347
#define gbCopyingOverride 2348
#define tAppDistinctHolder 2353
#define tScrollAppearDelay 2354
#define tScrollDisappearDelay 2355
#define tPadSize 2356
#define stAppDistinctBottom 2357
#define cbCTSDetectLineEnd 2358
#define cbCTSBashMargin 2359
#define cbCTSTrimTrailing 2365
#define stCTSEOL 2366
#define lbCTSEOL 2367
#define tCursorFixedSize 2368
#define stCursorFixedSize 2369
#define tCursorMinSize 2370
#define stCursorMinSize 2371
#define lbHistoryList 2372
#define tHistoryEdit 2373
#define stHistoryList 2374
#define stHistoryEdit 2375
#define cbHistoryDontClose 2376
#define cbHistoryAutoExecute 2377
#define cbHistoryTopMost 2378
#define slTransparentInactive 2380
#define cbTransparentSeparate 2381
#define stTransparentInactive 2382
#define stOpaqueInactive 2383
#define tInsideIcon 2384
#define tInsideConfig 2385
#define tInsideShell 2386
#define bInsideRegister 2387
#define bInsideUnregister 2388
#define tHereIcon 2389
#define tHereConfig 2390
#define tHereShell 2391
#define bHereRegister 2392
#define bHereUnregister 2393
#define tCmdAutoAttach 2394
#define bCmdAutoRegister 2395
#define bCmdAutoUnregister 2396
#define cbInsideSyncDir 2397
#define lbConClrText 2398
#define lbConClrBack 2399
#define lbConClrPopText 2401
#define lbConClrPopBack 2402
#define cbSnapToDesktopEdges 2403
#define vkWndDragKey 2404
#define IDC_ATTACH_ALT 2405
#define cbInsideName 2406
#define cbHereName 2407
#define cbCmdAutorunNewWnd 2411
#define cbCTSEndOnTyping 2412
#define vkMinimizeRestor2 2413
#define vkMoveTabLeft 2414
#define vkMoveTabRight 2415
#define cbStatusNewVCon 2416
#define cbUseCurrentSizePos 2417
#define cbUseClink 2418
#define cbStatusActiveProcess 2419
#define cbStatusConsoleTitle 2420
#define cbStatusVertSep 2421
#define cbStatusHorzSep 2422
#define cbAddConEmu2Path 2423
#define bCmdAutoClear 2424
#define tDarkerPlugin 2427
#define slDarkerPlugin 2428
#define cbShowWasHiddenMsg 2435
#define cbCTSEndOnKeyPress 2436
#define vkShowCaption 2437
#define stWndWidth 2438
#define stWndHeight 2439
#define gbRecreateSplit 2440
#define rbRecreateSplitNone 2441
#define rbRecreateSplit2Right 2442
#define rbRecreateSplit2Bottom 2443
#define tRecreateSplit 2444
#define stRecreateSplit 2445
#define cbComspecUncPaths 2451
#define cbCmdTasksDir 2452
#define vkFontLarger 2453
#define vkFontSmaller 2454
#define vkShowTabsList2 2455
#define cbClipStartBlockSelection 2458
#define cbClipStartTextSelection 2459
#define lbClipStartBlockSelection 2460
#define lbClipStartTextSelection 2461
#define cbQuakeAutoHide 2466
#define cbFullscreenNoBars 2468
#define cbFullscreenFixedConSize 2469
#define tFullScreenWidth 2470
#define tFullScreenHeight 2471
#define rbTaskbarBtnActive 2472
#define rbTaskbarBtnAll 2473
#define rbTaskbarBtnWin7 2474
#define rbTaskbarBtnHidden 2475
#define rbTabsAlways 2476
#define rbTabsAuto 2477
#define rbTabsNone 2478
#define tInsideSyncDir 2479
#define cbNumberInCaption 2480
#define cbTabsLocationBottom 2481
#define rbTabsLocationTop 2482
#define rbTabsLocationBottom 2483
#define vkGlobalRestore 2484
#define vkPasteFilePath 2485
#define vkPasteDirectory 2486
#define rbScrollbarHide 2487
#define rbScrollbarShow 2488
#define rbScrollbarAuto 2489
#define stHideCaptionAlwaysFrame 2490
#define cbTaskbarOverlay 2491
#define vkPasteCygwin 2492
#define cbCmdTasksActive 2493
#define vkTabMenu2 2494
#define vkSystemMenu2 2495
#define cbStatusSystemColors 2496
#define stStatusColorBack 2497
#define stStatusColorLight 2498
#define stStatusColorDark 2499
#define vkWinAltK 2500
#define vkCloseTab 2501
#define vkCloseConEmu 2502
#define vkDuplicateRoot 2503
#define vkDuplicateRootAs 2504
#define lbStatusAvailable 2505
#define lbStatusSelected 2506
#define cbStatusAddAll 2507
#define cbStatusAddSelected 2508
#define cbStatusDelAll 2509
#define cbStatusDelSelected 2510
#define vkTabPane 2511
#define vkTabPaneShift 2512
#define vkCloseGroup 2513
#define cbHotkeysAssignedOnly 2514
#define cbDefaultTerminal 2515
#define tDefaultTerminal 2516
#define cbCloseEditViewConfirm 2517
#define cbDefaultTerminalNoInjects 2518
#define rbDefaultTerminalConfAuto 2519
#define rbDefaultTerminalConfAlways 2520
#define rbDefaultTerminalConfNever 2521
#define vkDeleteLeftWord 2522
#define cbCTSDeleteLeftWord 2526
#define rCursorH 2530
#define rCursorV 2531
#define rCursorB 2532
#define rCursorR 2533
#define rInactiveCursorH 2534
#define rInactiveCursorV 2535
#define rInactiveCursorB 2536
#define rInactiveCursorR 2537
#define cbInactiveCursorColor 2538
#define cbInactiveCursorIgnoreSize 2539
#define tInactiveCursorFixedSize 2540
#define stInactiveCursorFixedSize 2541
#define stInactiveCursorMinSize 2542
#define tInactiveCursorMinSize 2543
#define cbInactiveCursor 2544
#define cbInactiveCursorBlink 2545
#define vkEscNoConsoles 2546
#define cbDefaultTerminalStartup 2547
#define cbMultiShowButtons 2549
#define cbCTSShiftArrowStartSel 2553
#define vkCTSShiftLeft 2554
#define vkCTSShiftRight 2555
#define vkCTSShiftUp 2556
#define vkCTSShiftDown 2557
#define gbSelectingOverride 2558
#define rbMinByEscAlways 2559
#define rbMinByEscEmpty 2560
#define rbMinByEscNever 2561
#define cbHideChildCaption 2562
#define cbMapShiftEscToEsc 2563
#define tQuakeAnimation 2564
#define stQuakeAnimation 2565
#define vkSetFocusSwitch 2566
#define cbMinimizeOnLoseFocus 2567
#define cbFocusInChildWindows 2568
#define tOptionSearch 2569
#define tStorage 2571
#define cbExportConfig 2572
#define stStorage 2573
#define vkSetFocusGui 2575
#define vkSetFocusChild 2576
#define vkChildSystemMenu 2577
#define cbSingleInstance 2578
#define cbCTSEndCopyBefore 2579
#define IDC_HELP_DESCR 2580
#define vkJumpNextMonitor 2581
#define vkJumpPrevMonitor 2582
#define cbAddConEmuBase2Path 2584
#define cbCloseConEmuOnCrossClicking 2585
#define cbMinimizeOnLastTabClose 2586
#define cbHideOnLastTabClose 2587
#define cbCloseConEmuWithLastTab 2588
#define rbAutoUpdateStableFast 2589
#define rbAutoUpdatePreviewFast 2590
#define rbAutoUpdateDeveloperFast 2591
#define cbShowHelpTooltips 2592
#define tTabBtnDblClickAction 2593
#define cbIntegralSize 2594
#define vkCTSVkCopyAll 2595
#define vkTileToLeft 2596
#define vkTileToRight 2597
#define cbSuppressBells 2598
#define cbOneTabPerGroup 2599
#define tTabBarDblClickAction 2600
#define cbActivateSplitMouseOver 2601
#define tPerfCounters 2602
#define cbCTSIBeam 2603
#define vkSplitNewConV 2604
#define vkSplitNewConH 2605
#define vkSplitSizeVup 2606
#define vkSplitSizeVdown 2607
#define vkSplitSizeHleft 2608
#define vkSplitSizeHright 2609
#define vkSplitFocusUp 2610
#define vkSplitFocusDown 2611
#define vkSplitFocusLeft 2612
#define vkSplitFocusRight 2613
#define cbClinkWebPage 2614
#define cbStatusVertPad 2615
#define cbActionChk1 2616
#define stActionTitle 2617
#define cbActionBtn1 2618
#define cbActionBtn2 2619
#define cbActionBtn3 2620
#define vkCloseGroupPrc 2621
#define cbConsoleExceptionHandler 2622
#define lbStorageLocation 2623
#define vkMultiNewPopup2 2624
#define vkCloseAllCon 2625
#define vkCloseExceptCon 2626
#define cbDefaultTerminalTSA 2627
#define tCmdGroupKey 2628
#define cbCmdGroupKey 2629
#define vkCTSShiftHome 2630
#define vkCTSShiftEnd 2631
#define cbAddDefaults 2632
#define vkCTSCopyHtml0 2633
#define vkCTSCopyHtml1 2634
#define vkCTSCopyHtml2 2635
#define vkMaximizeWidth 2636
#define vkMaximizeHeight 2637
#define cbProcessNewConArg 2640
#define cbHighlightMouseRow 2641
#define cbHighlightMouseCol 2642
#define vkHighlightMouse 2646
#define vkTransparencyInc 2647
#define vkTransparencyDec 2648
#define pLinkDonate 2649
#define pLinkFlattr 2650
#define pIconCtrl 2651
#define cbTaskbarProgress 2656
#define cbCTSIntelligent 2657
#define tCTSIntelligentExceptions 2658
#define stCTSIntelligentExceptions 2659
#define gbDefaultTermConfClose 2660
#define cbDefaultTerminalUseExisting 2661
#define stDefaultTerminalSwitchInfo 2662
#define stDefaultTerminal 2663
#define bImportSettings 2664
#define cbRetardInactivePanes 2665
#define stFontCharset 2666
#define stFontSizeY 2667
#define stFontSizeX 2668
#define stFontSizeX3 2669
#define stFontSizeX2 2670
#define stBgImage 2671
#define stDarker 2672
#define stDarkerPlugin 2673
#define gbBgImage 2674
#define gbFixFarBorders 2675
#define gbExtendFonts 2676
#define gbAntiAliasing 2677
#define gbMainConFont 2678
#define cbAnsiLog 2679
#define tAnsiLogPath 2680
#define stGotoEditorCmdHelp 2681
#define tAboutSearch 2682
#define stConEmuVersion 2683
#define cbDefTermAgressive 2684
#define stSetPgWikiLink 2685
#define gbConfirmActions 2686
#define gbConfirmMisc 2687
#define cbDupConfirm 2688
#define cbConfirmDetach 2689
#define cbConfirmResetTerminal 2690
#define cbFontMonitorDpi 2691
#define cbFontAsDeviceUnits 2692
#define vkAppsPgUp 2693
#define vkAppsPgDn 2694
#define vkAppsHome 2695
#define vkAppsEnd 2696
#define vkAppsBS 2697
#define vkFontOriginal 2698
#define cbHotKeyChord 2699
#define hkHotKeySelect2 2701
#define gbHistorySettings 2704
#define cbSaveCmdHistory 2705
#define tCmdHistoryLocation 2706
#define cbCmdHistoryLocation 2707
#define lbHistoryItems 2709
#define cbHistoryClearAll 2710
#define cbHistoryDelItem 2711
#define stHistoryItems 2712
#define vkCloseZombies 2713
#define stCTSPreview 2714
#define cbMultiShowSearch 2715
#define rbColorRgbDec 2720
#define rbColorRgbHex 2721
#define rbColorBgrHex 2722
#define vkHighlightMouseX 2725
#define vkWinAltT 2726
#define vkMultiPause 2727
#define vkMultiGroup 2728
#define vkMaximizePane 2729
#define stTabFontFace 2730
#define stTabFontCharset 2731
#define stTabBtnDblClickAction 2732
#define stTabBarDblClickAction 2733
#define stTabConsole 2735
#define stTabTemplateGroup 2736
#define stTabTemplateDescr 2737
#define tTabModifiedSuffix 2738
#define tTabFlashCounter 2739
#define cbProcessCmdStart 2740
#define stStorageLocation 2741
#define stSingleInstance 2742
#define stUseKeyboardHooksFast 2743
#define stInjectConEmuHkFast 2744
#define gbFastConfig 2745
#define gbFeatureInConsole 2746
#define gbFeatureDebug 2747
#define gbFeatureRetard 2748
#define cbCmdGrpDefaultNew 2750
#define cbCmdGrpDefaultCmd 2751
#define cbCmdGrpTaskbar 2752
#define cbCmdGrpToolbar 2753
#define gbStartGroupCommands 2754
#define tStartGroupCommands 2755
#define gbConfirmClose 2756
#define cbCloseWindowConfirm 2757
#define cbConfirmCloseRunning 2758
#define gbConfirmCloseFar 2759
#define vkWinAltH 2760
#define vkTermButShell 2761
#define stPriorityBox 2762
#define rbPriorityRealtime 2763
#define rbPriorityHigh 2764
#define rbPriorityAbove 2765
#define rbPriorityNormal 2766
#define rbPriorityBelow 2767
#define rbPriorityIdle 2768
#define stAffinityBox 2769
#define cbAffinity0 2770
#define cbAffinity1 2771
#define cbAffinity2 2772
#define cbAffinity3 2773
#define cbAffinity4 2774
#define cbAffinity5 2775
#define cbAffinity6 2776
#define cbAffinity7 2777
#define cbAffinity8 2778
#define cbAffinity9 2779
#define cbAffinity10 2780
#define cbAffinity11 2781
#define cbAffinity12 2782
#define cbAffinity13 2783
#define cbAffinity14 2784
#define cbAffinity15 2785
#define cbAffinity16 2786
#define cbAffinity17 2787
#define cbAffinity18 2788
#define cbAffinity19 2789
#define cbAffinity20 2790
#define cbAffinity21 2791
#define cbAffinity22 2792
#define cbAffinity23 2793
#define cbAffinity24 2794
#define cbAffinity25 2795
#define cbAffinity26 2796
#define cbAffinity27 2797
#define cbAffinity28 2798
#define cbAffinity29 2799
#define cbAffinity30 2800
#define cbAffinity31 2801
#define cbAffinity32 2802
#define cbAffinity33 2803
#define cbAffinity34 2804
#define cbAffinity35 2805
#define cbAffinity36 2806
#define cbAffinity37 2807
#define cbAffinity38 2808
#define cbAffinity39 2809
#define cbAffinity40 2810
#define cbAffinity41 2811
#define cbAffinity42 2812
#define cbAffinity43 2813
#define cbAffinity44 2814
#define cbAffinity45 2815
#define cbAffinity46 2816
#define cbAffinity47 2817
#define cbAffinity48 2818
#define cbAffinity49 2819
#define cbAffinity50 2820
#define cbAffinity51 2821
#define cbAffinity52 2822
#define cbAffinity53 2823
#define cbAffinity54 2824
#define cbAffinity55 2825
#define cbAffinity56 2826
#define cbAffinity57 2827
#define cbAffinity58 2828
#define cbAffinity59 2829
#define cbAffinity60 2830
#define cbAffinity61 2831
#define cbAffinity62 2832
#define cbAffinity63 2833
#define vkAffinity 2834
#define tUnicodeRanges 2835
#define stExtendFonts 2836
#define stUnicodeRanges 2837
#define cbUnicodeRangesApply 2838
#define vkConDetach 2839
#define vkConUnfasten 2840
#define lbStartupShellFast 2842
#define stStartupShellFast 2843
#define lbColorSchemeFast 2844
#define stColorSchemeFast 2845
#define cbQuakeFast 2846
#define tQuakeKeyFast 2847
#define cbQuakeKeyFast 2848
#define stPalettePreviewFast 2849
#define gbSetAlias 2850
#define tSetCommands 2851
#define stSetCommands 2852
#define vkCdExplorerPath 2853
#define cbShowWasSetOnTopMsg 2854
#define stSetCommands2 2855
#define cbUpdateInetTool 2856
#define tUpdateInetTool 2857
#define cbUpdateInetToolPath 2858
#define stUpdateCommand 2859
#define stUpdatePostCommand 2860
#define stUpdateVerLocation 2861
#define stUpdateReleaseType 2862
#define stUpdateCheck 2863
#define gbUpdate 2864
#define cbApplyDefTerm 2865
#define cbDefaultTerminalDebugLog 2866
#define cbRestore2ActiveMonitor 2867
#define gbStartupOptions 2868
#define gbTaskStartDelay 2869
#define stStartCreateDelay 2870
#define tStartCreateDelay 2871
#define stCopyFormat 2872
#define lbCopyFormat 2873
#define vkDebugProcess 2874
#define vkDumpProcess 2875
#define vkDumpTree 2876
#define cbUpdateCheck 2877
#define cbProcessCtrlZ 2878
#define cbFont2AA 2883
#define stCmdTaskAdd 2884
#define stKeySelect 2885
#define gbWindowSizePos 2889
#define gbWindowPos 2890
#define stWindowPosX 2891
#define stWindowPosY 2892
#define gbWindowSize 2893
#define gbConsoleBuffer 2894
#define gbNtvdm 2895
#define stNtvdmHeight 2896
#define gbVConAlignment 2897
#define stVConPadSize 2898
#define gbShowGeneric 2900
#define gbShowScrollBar 2901
#define stScrollAppear 2902
#define stScrollDisappear 2903
#define stFrameWidth 2904
#define stFrameAppear 2905
#define stFrameDisappear 2906
#define gbQuakeStyle 2907
#define gbTaskBarNotify 2908
#define gbTaskBarButton 2909
#define gbWndCloseAction 2910
#define gbMinimizeAction 2911
#define gbMinimizeOnEsc 2912
#define gbCursorActive 2913
#define gbCursorInactive 2914
#define gbIntgrHere 2915
#define gbIntgrInside 2916
#define stIntgrHereItem 2917
#define stIntgrHereCfg 2918
#define stIntgrHereCmd 2919
#define stIntgrHereIcon 2920
#define stIntgrInsideNote 2921
#define stIntgrInsideItem 2922
#define stIntgrInsideCfg 2923
#define stIntgrInsideCmd 2924
#define stIntgrInsideIcon 2925
#define gbDefTerm 2926
#define gbExtendColors 2927
#define gbColorEnhancement 2928
#define stColorFadeLow 2929
#define stColorFadeHigh 2930
#define stColorSchemes 2931
#define stColorText 2932
#define stColorBack 2933
#define stColorPopupText 2934
#define stColorPopupBack 2935
#define gbAlphaTransparency 2936
#define stTransparentActive 2937
#define stOpaqueActive 2938
#define gbStaticTransparency 2939
#define stFarPID 2940
#define stRConStates 2941
#define gbInfoProcesses 2942
#define gbInfoSizes 2943
#define gbInfoCmdLine 2944
#define stConsoleSizeChars 2945
#define stConsoleLeftTop 2946
#define stDcWndSize 2947
#define stRConCursorInfo 2948
#define stFarPanelLeft 2949
#define stFarPanelRight 2950
#define gbVConFont 2951
#define stVConFontMain 2952
#define stVConFontFix 2953
#define stConsoleBufferChars 2954
#define gbCmdAutoAttach 2955
#define stCmdAutoAttach 2956
#define gbFarDragDrop 2957
#define gbFarOptions 2958
#define gbFarTabTemplates 2959
#define stFarTabTemplates 2960
#define stTabPanels 2961
#define stTabEditor 2962
#define stTabViewer 2963
#define stTabEditorMod 2964
#define gbFarMacros 2965
#define stCloseTabMacro 2966
#define stSaveAllMacro 2967
#define stStartupDir 2968
#define stRunAsUser 2969
#define stRunAsPassword 2970
#define gbRunAsOptions 2971
#define gbHyperlinks 2972
#define gbHighlightRowCol 2973
#define gbAddToPath 2974
#define gbTextSelection 2975
#define gbSelectColorIdx 2976
#define stCTSTextColor 2977
#define stCTSBackColor 2978
#define gbSelectMouse 2979
#define gbSelectKeyboard 2980
#define gbTabs 2981
#define stTabModifiedSuffix 2982
#define stTabFlashCounter 2983
#define stTabSkipWords 2984
#define stTabLenMax 2985
#define gbStatusFontColor 2986
#define stStatusFontFace 2987
#define stStatusFontCharset 2988
#define stStatusLines 2989
#define stStatusAvailCol 2990
#define stStatusSelCol 2991
#define gbFarPanelViews 2992
#define gbFarThumbnails 2993
#define gbFarTiles 2994
#define stThumbsFontName 2995
#define stThumbsImgSize 2996
#define stThumbsSpacing 2997
#define stThumbsPadding 2998
#define stTilesFontName 2999
#define stTilesImgSize 3000
#define stTilesSpacing 3001
#define stTilesPadding 3002
#define stThumbMaxZoom 3003
#define stThumbLoadingTimeout 3004
#define gbFarPreviewBg 3005
#define stMoreConfont1 3006
#define stMoreConfont2 3007
#define stMoreConfont3 3008
#define stMoreConfont4 3009
#define stMoreConfont5 3010
#define stMoreConfont6 3011
#define stConsoleFontSizeY 3012
#define stConsoleFontSizeX 3013
#define gbHotkeys 3014
#define stHotkeys 3015
#define gbCtrlMouse 3016
#define gbCtrlIntercept 3017
#define gbCtrlSeizeKeys 3018
#define gbCtrlMisc 3019
#define gbCtrlPrompt 3020
#define gbCtrlMouseBtns 3021
#define stCTSRBtnAction 3022
#define stCTSMBtnAction 3023
#define stCmdGroupKey 3024
#define stKeySelectMod 3025
#define vkJumpActiveMonitor 3026
#define vkResetTerminal 3027
#define vkAltNumpad 3028
#define cbCTSResetOnRelease 3029
#define cbCTSEraseBeforeReset 3030
#define cbDebugLog 3031
#define tDebugLogDir 3032
#define rPasteM1MultiLine 3033
#define rPasteM1SingleLine 3034
#define rPasteM1FirstLine 3035
#define rPasteM1Nothing 3036
#define rPasteM2MultiLine 3040
#define rPasteM2SingleLine 3041
#define rPasteM2FirstLine 3042
#define rPasteM2Nothing 3043
#define gbPasteM1 3047
#define gbPasteM2 3048
#define gbPasteConfirm 3049
#define stBgReplaceIndexes 3051
#define tHotkeysFilter 3052
#define lbHotKeyFilter 3053
#define stElevatedConsolesGroup 3054
#define gbTabDblClkActions 3055
#define cbVividColors 3056
#define rbActivityProcess 3057
#define gbQuakeFrame 3058
#define gbChildGui 3059
#define cbMouseDragWindow 3060
#define cbUseAltGrayPlus 3061
#define stCTSRMCondition 3062
#define gbAnsiSecureExec 3063
#define stAnsiSecureExec1 3064
#define stAnsiSecureExec2 3065
#define stAnsiSecureExecUrl 3066
#define rbAnsiSecureAny 3067
#define rbAnsiSecureCmd 3068
#define rbAnsiSecureOff 3069
#define tAnsiSecure 3070
#define stAnsiSecureExec3 3071
#define gbAnsiSequences 3072
#define cbJumpListAutoUpdate 3073
#define cbCompressLongStrings 3074
#define cbKillSshAgent 3075
#define vkFindPrevPrompt 3076
#define vkFindNextPrompt 3077
#define IDC_ATTACH_LEAVE_OPEN 3078
#define vkMultiGroupAll 3079
#define vkSplitSwapUp 3080
#define vkSplitSwapDown 3081
#define vkSplitSwapLeft 3082
#define vkSplitSwapRight 3083
#define vkSplitSwap 3084
#define vkMultiGroupKey 3085
#define stRestartCmd 3086
#define cbCmdTasksDup 3087
#define cbPasteM1Posix 3088
#define cbPasteM2Posix 3089
#define cbScrollbarDynamic 3090
#define vkClose2Right 3091
#define vkMultiWnd 3092
#define stInterfaceLanguage 3093
#define lbInterfaceLanguage 3094
#define cbStartupShellFast 3095
#define stQuakeKeyFast 3096
#define gbSettingsGeneral 3097
#define gbRestoreMinimize 3098
#define cbRestoreInactive 3099
#define cbInactiveCursorSubstHidden 3100
#define vkCheckUpdates 3101
#define cbAutoTrimSingleLine 3102
#define vkCTSCtrlShiftLeft 3103
#define vkCTSCtrlShiftRight 3104
#define cbAnsiLogCodes 3105
#define cbAutoReloadEnvironment 3106
#define tConBufferChr 3107
#define vkEditMenu 3108
#define vkEditMenu2 3109
#define stStartupShellGeneral 3110
#define tFarHourglass 3111
#define vkSetFocusParent 3212
#define IDC_STATIC -1
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 248
#define _APS_NEXT_COMMAND_VALUE 40010
#define _APS_NEXT_CONTROL_VALUE 3113
#define _APS_NEXT_SYMED_VALUE 130
#endif
#endif
|
4dafe41a64949fb5deff937ebaa65be7cbb9658a
|
7f6c235b0598353549959c18f69eefd20b766907
|
/examples/sound/psglib/main.c
|
fc6c992bb98bfcc960d8eb805f7f50e680aea5de
|
[
"ClArtistic"
] |
permissive
|
z88dk/z88dk
|
46dfd4905f36d99333173cadd0a660839befc9f0
|
8b07f37cc43c5d9ffe69b563c80763491d8faff7
|
refs/heads/master
| 2023-09-04T19:29:49.254958
| 2023-09-03T20:51:24
| 2023-09-03T20:51:24
| 54,035,569
| 820
| 263
|
NOASSERTION
| 2023-09-05T11:09:04
| 2016-03-16T13:48:16
|
Assembly
|
UTF-8
|
C
| false
| false
| 1,387
|
c
|
main.c
|
#include <stdio.h>
#include <intrinsic.h>
#include <psg/PSGlib.h>
#include <stdlib.h>
#include <games.h>
// zcc +coleco main.c psg.c -create-app
// zcc +sms main.c psg.c -create-app
// Content.
#define MUSIC_PSG music_psg
#define SOUND1_PSG sound1_psg
#define SOUND2_PSG sound2_psg
#define SOUND3_PSG sound3_psg
#include "psg.h"
#define USE_JOYSTICK 1
int readkey() {
#ifdef USE_JOYSTICK
int k = joystick(1);
if ( k & MOVE_UP ) return '0';
if ( k & MOVE_RIGHT ) return '1';
if ( k & MOVE_DOWN ) return '2';
if ( k & MOVE_DOWN ) return '2';
if ( k & MOVE_FIRE1 ) return 's';
if ( k & MOVE_FIRE1 ) return ' ';
#else
return getk();
#endif
}
void main()
{
printf("%cPSGLib example\n",12);
// Start playing the song
PSGPlay(MUSIC_PSG);
// Just loop
while ( 1 ) {
int k = readkey();
switch ( k ) {
case '0':
PSGSFXPlay(SOUND1_PSG, SFX_CHANNEL2);
break;
case '1':
PSGSFXPlay(SOUND2_PSG, SFX_CHANNEL2);
break;
case '2':
PSGSFXPlay(SOUND3_PSG, SFX_CHANNEL2);
break;
case ' ':
PSGSilenceChannels();
break;
case 's':
PSGRestoreVolumes();
break;
}
PSGFrame();
PSGSFXFrame();
msleep(40);
}
}
|
373c9f02db0489aee9837c5a4de043b046eba919
|
564ae40950e6d71e30d3fecfa83ebbeaadfc72bc
|
/firmware/AVRISP-MKII/Lib/spi25.h
|
a9c8341335033e67af2963ed57bfdff352b251ab
|
[
"MIT"
] |
permissive
|
nofeletru/UsbAsp-flash
|
3790dc0abd9b038969ea3bebe0833b4f8e88a184
|
9dc854fe189ca35577d3d39abf2d93eaad3b32fb
|
refs/heads/master
| 2023-07-27T11:04:46.516047
| 2023-07-25T12:32:43
| 2023-07-25T12:34:29
| 38,684,672
| 683
| 164
|
MIT
| 2023-07-24T08:52:40
| 2015-07-07T11:56:44
|
Pascal
|
UTF-8
|
C
| false
| false
| 468
|
h
|
spi25.h
|
#include <LUFA/Drivers/USB/USB.h>
#include "ISP/ISPProtocol.h"
#define CMD_ENTER_PROGMODE_SPI25 0x30
#define CMD_LEAVE_PROGMODE_SPI25 0x31
#define CMD_SPI25_READ 0x32
#define CMD_SPI25_WRITE 0x33
#define CMD_FIRMWARE_VER 0x34
#define FIRMWARE_VER 0xEE
void give_firmware_ver(void);
void SPI_Set_CS(uint8_t line_level);
void SPI_Enter25Mode(void);
void SPI_Leave25Mode(void);
void SPI_25Read(void);
void SPI_25Write(void);
|
4b8b74ba1c3fb7b07cf5c13cb33e0eb9c3e7b753
|
7744859512f027ef0da8b1bde0f8518e631b98eb
|
/soh/assets/objects/object_gi_bracelet/object_gi_bracelet.h
|
32f6f286c98ecfc57595ba8468e0e50c5a115355
|
[] |
no_license
|
HarbourMasters/Shipwright
|
7f70b9470e4f9a117f3fe2d6e4deb776b8742182
|
0e7c6585239c0d7ea2c039b8b8cb7eaedf8928a9
|
refs/heads/develop
| 2023-08-31T20:50:56.253521
| 2023-08-30T17:34:06
| 2023-08-30T17:34:06
| 472,575,717
| 2,104
| 459
| null | 2023-09-14T20:29:01
| 2022-03-22T01:42:52
|
C
|
UTF-8
|
C
| false
| false
| 205
|
h
|
object_gi_bracelet.h
|
#pragma once
#include "align_asset_macro.h"
#define dgGiGoronBraceletDL "__OTR__objects/object_gi_bracelet/gGiGoronBraceletDL"
static const ALIGN_ASSET(2) char gGiGoronBraceletDL[] = dgGiGoronBraceletDL;
|
628c284cc4111d7a8432849419fc6dde5bfd611b
|
15a46f79cc5edfd08ebc63a8416dd02b13a2df33
|
/GLUS/src/GLUS/glus_define.h
|
f01d62485fa5d21739787867f3a327436f9e44b8
|
[
"LGPL-3.0-only",
"Apache-2.0"
] |
permissive
|
McNopper/OpenGL
|
a24a99de305f475205b00d39b4dde42d33645c6f
|
42fa2736e2b37db1df99c2b205279855ec6f2b1d
|
refs/heads/master
| 2022-07-16T06:44:44.845154
| 2022-05-21T11:47:12
| 2022-05-21T11:47:12
| 8,373,358
| 2,270
| 771
|
Apache-2.0
| 2022-05-21T11:51:12
| 2013-02-23T09:26:37
|
C
|
UTF-8
|
C
| false
| false
| 3,114
|
h
|
glus_define.h
|
/*
* GLUS - Modern OpenGL, OpenGL ES and OpenVG Utilities. Copyright (C) since 2010 Norbert Nopper
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
#ifndef GLUS_DEFINE_H_
#define GLUS_DEFINE_H_
#define GLUS_NO_ERROR 0
#define GLUS_OK 0
#define GLUS_TRUE 1
#define GLUS_FALSE 0
#define GLUS_POINTS 0x0000
#define GLUS_LINES 0x0001
#define GLUS_LINE_LOOP 0x0002
#define GLUS_LINE_STRIP 0x0003
#define GLUS_LINES_ADJACENCY 0x000A
#define GLUS_LINE_STRIP_ADJACENCY 0x000B
#define GLUS_TRIANGLES 0x0004
#define GLUS_TRIANGLE_STRIP 0x0005
#define GLUS_TRIANGLE_FAN 0x0006
#define GLUS_TRIANGLES_ADJACENCY 0x000C
#define GLUS_TRIANGLE_STRIP_ADJACENCY 0x000D
#define GLUS_UNPACK_ALIGNMENT 0x0CF5
#define GLUS_PACK_ALIGNMENT 0x0D05
#define GLUS_BYTE 0x1400
#define GLUS_UNSIGNED_BYTE 0x1401
#define GLUS_SHORT 0x1402
#define GLUS_UNSIGNED_SHORT 0x1403
#define GLUS_INT 0x1404
#define GLUS_UNSIGNED_INT 0x1405
#define GLUS_FLOAT 0x1406
#define GLUS_DOUBLE 0x140A
#define GLUS_VERSION 0x1F02
#define GLUS_EXTENSIONS 0x1F03
#define GLUS_COMPILE_STATUS 0x8B81
#define GLUS_LINK_STATUS 0x8B82
#define GLUS_VALIDATE_STATUS 0x8B83
#define GLUS_INFO_LOG_LENGTH 0x8B84
#define GLUS_FRAMEBUFFER 0x8D40
#define GLUS_COMPRESSED_R11_EAC 0x9270
#define GLUS_COMPRESSED_SIGNED_R11_EAC 0x9271
#define GLUS_COMPRESSED_RG11_EAC 0x9272
#define GLUS_COMPRESSED_SIGNED_RG11_EAC 0x9273
#define GLUS_COMPRESSED_RGB8_ETC2 0x9274
#define GLUS_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276
#define GLUS_COMPRESSED_RGBA8_ETC2_EAC 0x9278
#define GLUS_PI 3.1415926535897932384626433832795f
#define GLUS_LOG_NOTHING 0
#define GLUS_LOG_ERROR 1
#define GLUS_LOG_WARNING 2
#define GLUS_LOG_INFO 3
#define GLUS_LOG_DEBUG 4
#define GLUS_LOG_SEVERE 5
#define GLUS_VERTICES_FACTOR 4
#define GLUS_VERTICES_DIVISOR 4
#define GLUS_MAX_STRING 256
#define GLUS_MAX_FILENAME 2048
#ifndef GLUS_BASE_DIRECTORY
#define GLUS_BASE_DIRECTORY ""
#endif
#endif /* GLUS_DEFINE_H_ */
|
b8c04732a1d906c6f3e79e1b0688c75b5a1bd3ca
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/imxrt/libraries/MIMXRT1050/MIMXRT1052/drivers/fsl_aipstz.c
|
d124af4728f30977603b7fcf448b20de3f7d4a42
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 1,813
|
c
|
fsl_aipstz.c
|
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_aipstz.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* Component ID definition, used by tools. */
#ifndef FSL_COMPONENT_ID
#define FSL_COMPONENT_ID "platform.drivers.aipstz"
#endif
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* brief Configure the privilege level for master.
*
* param base AIPSTZ peripheral base pointer
* param master Masters for AIPSTZ.
* param privilegeConfig Configuration is ORed from aipstz_master_privilege_level_t.
*/
void AIPSTZ_SetMasterPriviledgeLevel(AIPSTZ_Type *base, aipstz_master_t master, uint32_t privilegeConfig)
{
uint32_t mask = ((uint32_t)master >> 8) - 1;
uint32_t shift = (uint32_t)master & 0xFF;
base->MPR = (base->MPR & (~(mask << shift))) | (privilegeConfig << shift);
}
/*!
* brief Configure the access for peripheral.
*
* param base AIPSTZ peripheral base pointer
* param master Peripheral for AIPSTZ.
* param accessControl Configuration is ORed from aipstz_peripheral_access_control_t.
*/
void AIPSTZ_SetPeripheralAccessControl(AIPSTZ_Type *base, aipstz_peripheral_t peripheral, uint32_t accessControl)
{
volatile uint32_t *reg = (uint32_t *)((uint32_t)base + ((uint32_t)peripheral >> 16));
uint32_t mask = (((uint32_t)peripheral & 0xFF00U) >> 8) - 1;
uint32_t shift = (uint32_t)peripheral & 0xFF;
*reg = (*reg & (~(mask << shift))) | ((accessControl & mask) << shift);
}
|
fffbaf949c4b641f82a671380a4b5f7ba8311f0b
|
e814383d36a10839104efaa4df277996ab220fa3
|
/ompi/mpi/c/abort.c
|
889fe1738b3014db884a92eeeef588578a9b9536
|
[
"mpich2",
"BSD-3-Clause-Open-MPI"
] |
permissive
|
open-mpi/ompi
|
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
|
1edfdb025c4450f694600083ad871cf06c8d45cd
|
refs/heads/main
| 2023-09-01T01:30:02.040705
| 2023-08-29T17:32:18
| 2023-08-29T17:32:18
| 24,107,001
| 2,008
| 973
|
NOASSERTION
| 2023-09-14T20:59:26
| 2014-09-16T16:08:30
|
C
|
UTF-8
|
C
| false
| false
| 1,962
|
c
|
abort.c
|
/*
* Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2020 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2008 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2007-2008 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2015 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "opal/util/show_help.h"
#include "ompi/mpi/c/bindings.h"
#include "ompi/runtime/params.h"
#include "ompi/errhandler/errhandler.h"
#include "ompi/runtime/mpiruntime.h"
#include "ompi/memchecker.h"
#include "ompi/communicator/communicator.h"
#if OMPI_BUILD_MPI_PROFILING
#if OPAL_HAVE_WEAK_SYMBOLS
#pragma weak MPI_Abort = PMPI_Abort
#endif
#define MPI_Abort PMPI_Abort
#endif
static const char FUNC_NAME[] = "MPI_Abort";
int MPI_Abort(MPI_Comm comm, int errorcode)
{
MEMCHECKER(
memchecker_comm(comm);
);
/* Don't even bother checking comm and errorcode values for
errors */
if (MPI_PARAM_CHECK) {
OMPI_ERR_INIT_FINALIZE(FUNC_NAME);
}
opal_show_help("help-mpi-api.txt", "mpi-abort", true,
ompi_comm_rank(comm),
('\0' != comm->c_name[0]) ? comm->c_name : "<Unknown>",
OMPI_NAME_PRINT(OMPI_PROC_MY_NAME),
errorcode);
return ompi_mpi_abort(comm, errorcode);
}
|
870b9e844e8725f6e912518c22405522506d466d
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/lib/decompress_unlzma.c
|
32adb73a903811c4b05d49fea6f9401c13cf396e
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 16,161
|
c
|
decompress_unlzma.c
|
/* Lzma decompressor for Linux kernel. Shamelessly snarfed
*from busybox 1.1.1
*
*Linux kernel adaptation
*Copyright (C) 2006 Alain < alain@knaff.lu >
*
*Based on small lzma deflate implementation/Small range coder
*implementation for lzma.
*Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
*
*Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
*Copyright (C) 1999-2005 Igor Pavlov
*
*Copyrights of the parts, see headers below.
*
*
*This program is free software; you can redistribute it and/or
*modify it under the terms of the GNU Lesser General Public
*License as published by the Free Software Foundation; either
*version 2.1 of the License, or (at your option) any later version.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
*Lesser General Public License for more details.
*
*You should have received a copy of the GNU Lesser General Public
*License along with this library; if not, write to the Free Software
*Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef STATIC
#define PREBOOT
#else
#include <linux/decompress/unlzma.h>
#endif /* STATIC */
#include <linux/decompress/mm.h>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
static long long INIT read_int(unsigned char *ptr, int size)
{
int i;
long long ret = 0;
for (i = 0; i < size; i++)
ret = (ret << 8) | ptr[size-i-1];
return ret;
}
#define ENDIAN_CONVERT(x) \
x = (typeof(x))read_int((unsigned char *)&x, sizeof(x))
/* Small range coder implementation for lzma.
*Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
*
*Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
*Copyright (c) 1999-2005 Igor Pavlov
*/
#include <linux/compiler.h>
#define LZMA_IOBUF_SIZE 0x10000
struct rc {
int (*fill)(void*, unsigned int);
uint8_t *ptr;
uint8_t *buffer;
uint8_t *buffer_end;
int buffer_size;
uint32_t code;
uint32_t range;
uint32_t bound;
void (*error)(char *);
};
#define RC_TOP_BITS 24
#define RC_MOVE_BITS 5
#define RC_MODEL_TOTAL_BITS 11
static int INIT nofill(void *buffer, unsigned int len)
{
return -1;
}
/* Called twice: once at startup and once in rc_normalize() */
static void INIT rc_read(struct rc *rc)
{
rc->buffer_size = rc->fill((char *)rc->buffer, LZMA_IOBUF_SIZE);
if (rc->buffer_size <= 0)
rc->error("unexpected EOF");
rc->ptr = rc->buffer;
rc->buffer_end = rc->buffer + rc->buffer_size;
}
/* Called once */
static inline void INIT rc_init(struct rc *rc,
int (*fill)(void*, unsigned int),
char *buffer, int buffer_size)
{
if (fill)
rc->fill = fill;
else
rc->fill = nofill;
rc->buffer = (uint8_t *)buffer;
rc->buffer_size = buffer_size;
rc->buffer_end = rc->buffer + rc->buffer_size;
rc->ptr = rc->buffer;
rc->code = 0;
rc->range = 0xFFFFFFFF;
}
static inline void INIT rc_init_code(struct rc *rc)
{
int i;
for (i = 0; i < 5; i++) {
if (rc->ptr >= rc->buffer_end)
rc_read(rc);
rc->code = (rc->code << 8) | *rc->ptr++;
}
}
/* Called twice, but one callsite is in inline'd rc_is_bit_0_helper() */
static void INIT rc_do_normalize(struct rc *rc)
{
if (rc->ptr >= rc->buffer_end)
rc_read(rc);
rc->range <<= 8;
rc->code = (rc->code << 8) | *rc->ptr++;
}
static inline void INIT rc_normalize(struct rc *rc)
{
if (rc->range < (1 << RC_TOP_BITS))
rc_do_normalize(rc);
}
/* Called 9 times */
/* Why rc_is_bit_0_helper exists?
*Because we want to always expose (rc->code < rc->bound) to optimizer
*/
static inline uint32_t INIT rc_is_bit_0_helper(struct rc *rc, uint16_t *p)
{
rc_normalize(rc);
rc->bound = *p * (rc->range >> RC_MODEL_TOTAL_BITS);
return rc->bound;
}
static inline int INIT rc_is_bit_0(struct rc *rc, uint16_t *p)
{
uint32_t t = rc_is_bit_0_helper(rc, p);
return rc->code < t;
}
/* Called ~10 times, but very small, thus inlined */
static inline void INIT rc_update_bit_0(struct rc *rc, uint16_t *p)
{
rc->range = rc->bound;
*p += ((1 << RC_MODEL_TOTAL_BITS) - *p) >> RC_MOVE_BITS;
}
static inline void INIT rc_update_bit_1(struct rc *rc, uint16_t *p)
{
rc->range -= rc->bound;
rc->code -= rc->bound;
*p -= *p >> RC_MOVE_BITS;
}
/* Called 4 times in unlzma loop */
static int INIT rc_get_bit(struct rc *rc, uint16_t *p, int *symbol)
{
if (rc_is_bit_0(rc, p)) {
rc_update_bit_0(rc, p);
*symbol *= 2;
return 0;
} else {
rc_update_bit_1(rc, p);
*symbol = *symbol * 2 + 1;
return 1;
}
}
/* Called once */
static inline int INIT rc_direct_bit(struct rc *rc)
{
rc_normalize(rc);
rc->range >>= 1;
if (rc->code >= rc->range) {
rc->code -= rc->range;
return 1;
}
return 0;
}
/* Called twice */
static inline void INIT
rc_bit_tree_decode(struct rc *rc, uint16_t *p, int num_levels, int *symbol)
{
int i = num_levels;
*symbol = 1;
while (i--)
rc_get_bit(rc, p + *symbol, symbol);
*symbol -= 1 << num_levels;
}
/*
* Small lzma deflate implementation.
* Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
*
* Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
* Copyright (C) 1999-2005 Igor Pavlov
*/
struct lzma_header {
uint8_t pos;
uint32_t dict_size;
uint64_t dst_size;
} __attribute__ ((packed)) ;
#define LZMA_BASE_SIZE 1846
#define LZMA_LIT_SIZE 768
#define LZMA_NUM_POS_BITS_MAX 4
#define LZMA_LEN_NUM_LOW_BITS 3
#define LZMA_LEN_NUM_MID_BITS 3
#define LZMA_LEN_NUM_HIGH_BITS 8
#define LZMA_LEN_CHOICE 0
#define LZMA_LEN_CHOICE_2 (LZMA_LEN_CHOICE + 1)
#define LZMA_LEN_LOW (LZMA_LEN_CHOICE_2 + 1)
#define LZMA_LEN_MID (LZMA_LEN_LOW \
+ (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS)))
#define LZMA_LEN_HIGH (LZMA_LEN_MID \
+(1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS)))
#define LZMA_NUM_LEN_PROBS (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS))
#define LZMA_NUM_STATES 12
#define LZMA_NUM_LIT_STATES 7
#define LZMA_START_POS_MODEL_INDEX 4
#define LZMA_END_POS_MODEL_INDEX 14
#define LZMA_NUM_FULL_DISTANCES (1 << (LZMA_END_POS_MODEL_INDEX >> 1))
#define LZMA_NUM_POS_SLOT_BITS 6
#define LZMA_NUM_LEN_TO_POS_STATES 4
#define LZMA_NUM_ALIGN_BITS 4
#define LZMA_MATCH_MIN_LEN 2
#define LZMA_IS_MATCH 0
#define LZMA_IS_REP (LZMA_IS_MATCH + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
#define LZMA_IS_REP_G0 (LZMA_IS_REP + LZMA_NUM_STATES)
#define LZMA_IS_REP_G1 (LZMA_IS_REP_G0 + LZMA_NUM_STATES)
#define LZMA_IS_REP_G2 (LZMA_IS_REP_G1 + LZMA_NUM_STATES)
#define LZMA_IS_REP_0_LONG (LZMA_IS_REP_G2 + LZMA_NUM_STATES)
#define LZMA_POS_SLOT (LZMA_IS_REP_0_LONG \
+ (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
#define LZMA_SPEC_POS (LZMA_POS_SLOT \
+(LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS))
#define LZMA_ALIGN (LZMA_SPEC_POS \
+ LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX)
#define LZMA_LEN_CODER (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS))
#define LZMA_REP_LEN_CODER (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS)
#define LZMA_LITERAL (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS)
struct writer {
uint8_t *buffer;
uint8_t previous_byte;
size_t buffer_pos;
int bufsize;
size_t global_pos;
int(*flush)(void*, unsigned int);
struct lzma_header *header;
};
struct cstate {
int state;
uint32_t rep0, rep1, rep2, rep3;
};
static inline size_t INIT get_pos(struct writer *wr)
{
return
wr->global_pos + wr->buffer_pos;
}
static inline uint8_t INIT peek_old_byte(struct writer *wr,
uint32_t offs)
{
if (!wr->flush) {
int32_t pos;
while (offs > wr->header->dict_size)
offs -= wr->header->dict_size;
pos = wr->buffer_pos - offs;
return wr->buffer[pos];
} else {
uint32_t pos = wr->buffer_pos - offs;
while (pos >= wr->header->dict_size)
pos += wr->header->dict_size;
return wr->buffer[pos];
}
}
static inline int INIT write_byte(struct writer *wr, uint8_t byte)
{
wr->buffer[wr->buffer_pos++] = wr->previous_byte = byte;
if (wr->flush && wr->buffer_pos == wr->header->dict_size) {
wr->buffer_pos = 0;
wr->global_pos += wr->header->dict_size;
if (wr->flush((char *)wr->buffer, wr->header->dict_size)
!= wr->header->dict_size)
return -1;
}
return 0;
}
static inline int INIT copy_byte(struct writer *wr, uint32_t offs)
{
return write_byte(wr, peek_old_byte(wr, offs));
}
static inline int INIT copy_bytes(struct writer *wr,
uint32_t rep0, int len)
{
do {
if (copy_byte(wr, rep0))
return -1;
len--;
} while (len != 0 && wr->buffer_pos < wr->header->dst_size);
return len;
}
static inline int INIT process_bit0(struct writer *wr, struct rc *rc,
struct cstate *cst, uint16_t *p,
int pos_state, uint16_t *prob,
int lc, uint32_t literal_pos_mask) {
int mi = 1;
rc_update_bit_0(rc, prob);
prob = (p + LZMA_LITERAL +
(LZMA_LIT_SIZE
* (((get_pos(wr) & literal_pos_mask) << lc)
+ (wr->previous_byte >> (8 - lc))))
);
if (cst->state >= LZMA_NUM_LIT_STATES) {
int match_byte = peek_old_byte(wr, cst->rep0);
do {
int bit;
uint16_t *prob_lit;
match_byte <<= 1;
bit = match_byte & 0x100;
prob_lit = prob + 0x100 + bit + mi;
if (rc_get_bit(rc, prob_lit, &mi)) {
if (!bit)
break;
} else {
if (bit)
break;
}
} while (mi < 0x100);
}
while (mi < 0x100) {
uint16_t *prob_lit = prob + mi;
rc_get_bit(rc, prob_lit, &mi);
}
if (cst->state < 4)
cst->state = 0;
else if (cst->state < 10)
cst->state -= 3;
else
cst->state -= 6;
return write_byte(wr, mi);
}
static inline int INIT process_bit1(struct writer *wr, struct rc *rc,
struct cstate *cst, uint16_t *p,
int pos_state, uint16_t *prob) {
int offset;
uint16_t *prob_len;
int num_bits;
int len;
rc_update_bit_1(rc, prob);
prob = p + LZMA_IS_REP + cst->state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
cst->rep3 = cst->rep2;
cst->rep2 = cst->rep1;
cst->rep1 = cst->rep0;
cst->state = cst->state < LZMA_NUM_LIT_STATES ? 0 : 3;
prob = p + LZMA_LEN_CODER;
} else {
rc_update_bit_1(rc, prob);
prob = p + LZMA_IS_REP_G0 + cst->state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
prob = (p + LZMA_IS_REP_0_LONG
+ (cst->state <<
LZMA_NUM_POS_BITS_MAX) +
pos_state);
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
cst->state = cst->state < LZMA_NUM_LIT_STATES ?
9 : 11;
return copy_byte(wr, cst->rep0);
} else {
rc_update_bit_1(rc, prob);
}
} else {
uint32_t distance;
rc_update_bit_1(rc, prob);
prob = p + LZMA_IS_REP_G1 + cst->state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
distance = cst->rep1;
} else {
rc_update_bit_1(rc, prob);
prob = p + LZMA_IS_REP_G2 + cst->state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
distance = cst->rep2;
} else {
rc_update_bit_1(rc, prob);
distance = cst->rep3;
cst->rep3 = cst->rep2;
}
cst->rep2 = cst->rep1;
}
cst->rep1 = cst->rep0;
cst->rep0 = distance;
}
cst->state = cst->state < LZMA_NUM_LIT_STATES ? 8 : 11;
prob = p + LZMA_REP_LEN_CODER;
}
prob_len = prob + LZMA_LEN_CHOICE;
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
prob_len = (prob + LZMA_LEN_LOW
+ (pos_state <<
LZMA_LEN_NUM_LOW_BITS));
offset = 0;
num_bits = LZMA_LEN_NUM_LOW_BITS;
} else {
rc_update_bit_1(rc, prob_len);
prob_len = prob + LZMA_LEN_CHOICE_2;
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
prob_len = (prob + LZMA_LEN_MID
+ (pos_state <<
LZMA_LEN_NUM_MID_BITS));
offset = 1 << LZMA_LEN_NUM_LOW_BITS;
num_bits = LZMA_LEN_NUM_MID_BITS;
} else {
rc_update_bit_1(rc, prob_len);
prob_len = prob + LZMA_LEN_HIGH;
offset = ((1 << LZMA_LEN_NUM_LOW_BITS)
+ (1 << LZMA_LEN_NUM_MID_BITS));
num_bits = LZMA_LEN_NUM_HIGH_BITS;
}
}
rc_bit_tree_decode(rc, prob_len, num_bits, &len);
len += offset;
if (cst->state < 4) {
int pos_slot;
cst->state += LZMA_NUM_LIT_STATES;
prob =
p + LZMA_POS_SLOT +
((len <
LZMA_NUM_LEN_TO_POS_STATES ? len :
LZMA_NUM_LEN_TO_POS_STATES - 1)
<< LZMA_NUM_POS_SLOT_BITS);
rc_bit_tree_decode(rc, prob,
LZMA_NUM_POS_SLOT_BITS,
&pos_slot);
if (pos_slot >= LZMA_START_POS_MODEL_INDEX) {
int i, mi;
num_bits = (pos_slot >> 1) - 1;
cst->rep0 = 2 | (pos_slot & 1);
if (pos_slot < LZMA_END_POS_MODEL_INDEX) {
cst->rep0 <<= num_bits;
prob = p + LZMA_SPEC_POS +
cst->rep0 - pos_slot - 1;
} else {
num_bits -= LZMA_NUM_ALIGN_BITS;
while (num_bits--)
cst->rep0 = (cst->rep0 << 1) |
rc_direct_bit(rc);
prob = p + LZMA_ALIGN;
cst->rep0 <<= LZMA_NUM_ALIGN_BITS;
num_bits = LZMA_NUM_ALIGN_BITS;
}
i = 1;
mi = 1;
while (num_bits--) {
if (rc_get_bit(rc, prob + mi, &mi))
cst->rep0 |= i;
i <<= 1;
}
} else
cst->rep0 = pos_slot;
if (++(cst->rep0) == 0)
return 0;
if (cst->rep0 > wr->header->dict_size
|| cst->rep0 > get_pos(wr))
return -1;
}
len += LZMA_MATCH_MIN_LEN;
return copy_bytes(wr, cst->rep0, len);
}
STATIC inline int INIT unlzma(unsigned char *buf, int in_len,
int(*fill)(void*, unsigned int),
int(*flush)(void*, unsigned int),
unsigned char *output,
int *posp,
void(*error)(char *x)
)
{
struct lzma_header header;
int lc, pb, lp;
uint32_t pos_state_mask;
uint32_t literal_pos_mask;
uint16_t *p;
int num_probs;
struct rc rc;
int i, mi;
struct writer wr;
struct cstate cst;
unsigned char *inbuf;
int ret = -1;
rc.error = error;
if (buf)
inbuf = buf;
else
inbuf = malloc(LZMA_IOBUF_SIZE);
if (!inbuf) {
error("Could not allocate input buffer");
goto exit_0;
}
cst.state = 0;
cst.rep0 = cst.rep1 = cst.rep2 = cst.rep3 = 1;
wr.header = &header;
wr.flush = flush;
wr.global_pos = 0;
wr.previous_byte = 0;
wr.buffer_pos = 0;
rc_init(&rc, fill, inbuf, in_len);
for (i = 0; i < sizeof(header); i++) {
if (rc.ptr >= rc.buffer_end)
rc_read(&rc);
((unsigned char *)&header)[i] = *rc.ptr++;
}
if (header.pos >= (9 * 5 * 5)) {
error("bad header");
goto exit_1;
}
mi = 0;
lc = header.pos;
while (lc >= 9) {
mi++;
lc -= 9;
}
pb = 0;
lp = mi;
while (lp >= 5) {
pb++;
lp -= 5;
}
pos_state_mask = (1 << pb) - 1;
literal_pos_mask = (1 << lp) - 1;
ENDIAN_CONVERT(header.dict_size);
ENDIAN_CONVERT(header.dst_size);
if (header.dict_size == 0)
header.dict_size = 1;
if (output)
wr.buffer = output;
else {
wr.bufsize = MIN(header.dst_size, header.dict_size);
wr.buffer = large_malloc(wr.bufsize);
}
if (wr.buffer == NULL)
goto exit_1;
num_probs = LZMA_BASE_SIZE + (LZMA_LIT_SIZE << (lc + lp));
p = (uint16_t *) large_malloc(num_probs * sizeof(*p));
if (p == 0)
goto exit_2;
num_probs = LZMA_LITERAL + (LZMA_LIT_SIZE << (lc + lp));
for (i = 0; i < num_probs; i++)
p[i] = (1 << RC_MODEL_TOTAL_BITS) >> 1;
rc_init_code(&rc);
while (get_pos(&wr) < header.dst_size) {
int pos_state = get_pos(&wr) & pos_state_mask;
uint16_t *prob = p + LZMA_IS_MATCH +
(cst.state << LZMA_NUM_POS_BITS_MAX) + pos_state;
if (rc_is_bit_0(&rc, prob)) {
if (process_bit0(&wr, &rc, &cst, p, pos_state, prob,
lc, literal_pos_mask)) {
error("LZMA data is corrupt");
goto exit_3;
}
} else {
if (process_bit1(&wr, &rc, &cst, p, pos_state, prob)) {
error("LZMA data is corrupt");
goto exit_3;
}
if (cst.rep0 == 0)
break;
}
if (rc.buffer_size <= 0)
goto exit_3;
}
if (posp)
*posp = rc.ptr-rc.buffer;
if (!wr.flush || wr.flush(wr.buffer, wr.buffer_pos) == wr.buffer_pos)
ret = 0;
exit_3:
large_free(p);
exit_2:
if (!output)
large_free(wr.buffer);
exit_1:
if (!buf)
free(inbuf);
exit_0:
return ret;
}
#ifdef PREBOOT
STATIC int INIT decompress(unsigned char *buf, int in_len,
int(*fill)(void*, unsigned int),
int(*flush)(void*, unsigned int),
unsigned char *output,
int *posp,
void(*error)(char *x)
)
{
return unlzma(buf, in_len - 4, fill, flush, output, posp, error);
}
#endif
|
bedd24341c62bc30cf9f8b63733526c39c778ddb
|
6186edb27443f74139dd22d5e3ea42f5a99bf568
|
/MemoryModule/LoaderPrivate.h
|
1741ca36d9232fe05c6d9665b5f09ffee8ddcc6f
|
[
"MIT"
] |
permissive
|
bb107/MemoryModulePP
|
a129d46775ebac8b8ff5ca4d1773dee05078a451
|
5fb7f591d271fda24f11753ca2c555c6d0c8d5f6
|
refs/heads/master
| 2023-05-11T18:16:17.904532
| 2023-05-03T02:52:22
| 2023-05-03T02:52:22
| 237,896,459
| 269
| 85
|
MIT
| 2022-10-07T01:16:04
| 2020-02-03T06:03:41
|
C++
|
UTF-8
|
C
| false
| false
| 207
|
h
|
LoaderPrivate.h
|
#pragma once
NTSTATUS NTAPI LdrMapDllMemory(
_In_ HMEMORYMODULE ViewBase,
_In_ DWORD dwFlags,
_In_opt_ PCWSTR DllName,
_In_opt_ PCWSTR lpFullDllName,
_Out_opt_ PLDR_DATA_TABLE_ENTRY* DataTableEntry
);
|
c4f13e2cefdda10c1752e4e62baf924d12c3a3ae
|
7664f318ed04bd0680f3d82321c18896e3ef6ad5
|
/src/overlays/actors/ovl_Boss_Fd2/z_boss_fd2.c
|
727d00ef1627890070fec5f97430bd9d51ead50b
|
[] |
no_license
|
zeldaret/oot
|
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
|
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
|
refs/heads/master
| 2023-08-29T05:29:31.356427
| 2023-08-28T22:48:52
| 2023-08-28T22:48:52
| 247,875,738
| 4,401
| 802
| null | 2023-09-14T13:34:38
| 2020-03-17T04:02:19
|
C
|
UTF-8
|
C
| false
| false
| 48,209
|
c
|
z_boss_fd2.c
|
/*
* File: z_boss_fd2.c
* Overlay: ovl_Boss_Fd2
* Description: Volvagia, hole form
*/
#include "z_boss_fd2.h"
#include "assets/objects/object_fd2/object_fd2.h"
#include "overlays/actors/ovl_Boss_Fd/z_boss_fd.h"
#include "overlays/actors/ovl_Door_Warp1/z_door_warp1.h"
#include "terminal.h"
#define FLAGS (ACTOR_FLAG_0 | ACTOR_FLAG_2 | ACTOR_FLAG_4 | ACTOR_FLAG_5)
typedef enum {
/* 0 */ DEATH_START,
/* 1 */ DEATH_RETREAT,
/* 2 */ DEATH_HANDOFF,
/* 3 */ DEATH_FD_BODY,
/* 4 */ DEATH_FD_SKULL,
/* 5 */ DEATH_FINISH
} BossFd2CutsceneState;
typedef enum {
/* 0 */ EYE_OPEN,
/* 1 */ EYE_HALF,
/* 2 */ EYE_CLOSED
} BossFd2EyeState;
void BossFd2_Init(Actor* thisx, PlayState* play);
void BossFd2_Destroy(Actor* thisx, PlayState* play);
void BossFd2_Update(Actor* thisx, PlayState* play2);
void BossFd2_Draw(Actor* thisx, PlayState* play);
void BossFd2_SetupEmerge(BossFd2* this, PlayState* play);
void BossFd2_Emerge(BossFd2* this, PlayState* play);
void BossFd2_SetupIdle(BossFd2* this, PlayState* play);
void BossFd2_Idle(BossFd2* this, PlayState* play);
void BossFd2_Burrow(BossFd2* this, PlayState* play);
void BossFd2_SetupBreatheFire(BossFd2* this, PlayState* play);
void BossFd2_BreatheFire(BossFd2* this, PlayState* play);
void BossFd2_SetupClawSwipe(BossFd2* this, PlayState* play);
void BossFd2_ClawSwipe(BossFd2* this, PlayState* play);
void BossFd2_Vulnerable(BossFd2* this, PlayState* play);
void BossFd2_Damaged(BossFd2* this, PlayState* play);
void BossFd2_Death(BossFd2* this, PlayState* play);
void BossFd2_Wait(BossFd2* this, PlayState* play);
ActorInit Boss_Fd2_InitVars = {
ACTOR_BOSS_FD2,
ACTORCAT_BOSS,
FLAGS,
OBJECT_FD2,
sizeof(BossFd2),
(ActorFunc)BossFd2_Init,
(ActorFunc)BossFd2_Destroy,
(ActorFunc)BossFd2_Update,
(ActorFunc)BossFd2_Draw,
};
#include "z_boss_fd2_colchk.inc.c"
static Vec3f sHoleLocations[] = {
{ 0.0f, 90.0f, -243.0f }, { 0.0f, 90.0f, 0.0f }, { 0.0f, 90.0f, 243.0f },
{ -243.0f, 90.0f, -243.0f }, { -243.0f, 90.0f, 0.0f }, { -243.0f, 90.0f, 243.0f },
{ 243.0f, 90.0f, -243.0f }, { 243.0f, 90.0f, 0.0f }, { 243.0f, 90.0f, 243.0f },
};
static InitChainEntry sInitChain[] = {
ICHAIN_U8(targetMode, 5, ICHAIN_CONTINUE),
ICHAIN_S8(naviEnemyId, NAVI_ENEMY_VOLVAGIA, ICHAIN_CONTINUE),
ICHAIN_F32_DIV1000(gravity, 0, ICHAIN_CONTINUE),
ICHAIN_F32(targetArrowOffset, 0, ICHAIN_STOP),
};
void BossFd2_SpawnDebris(PlayState* play, BossFdEffect* effect, Vec3f* position, Vec3f* velocity, Vec3f* acceleration,
f32 scale) {
s16 i;
for (i = 0; i < 180; i++, effect++) {
if (effect->type == BFD_FX_NONE) {
effect->type = BFD_FX_DEBRIS;
effect->pos = *position;
effect->velocity = *velocity;
effect->accel = *acceleration;
effect->scale = scale / 1000.0f;
effect->vFdFxRotX = Rand_ZeroFloat(100.0f);
effect->vFdFxRotY = Rand_ZeroFloat(100.0f);
break;
}
}
}
void BossFd2_SpawnFireBreath(PlayState* play, BossFdEffect* effect, Vec3f* position, Vec3f* velocity,
Vec3f* acceleration, f32 scale, s16 alpha, s16 kbAngle) {
s16 i;
for (i = 0; i < 180; i++, effect++) {
if (effect->type == BFD_FX_NONE) {
effect->type = BFD_FX_FIRE_BREATH;
effect->timer1 = 0;
effect->pos = *position;
effect->velocity = *velocity;
effect->accel = *acceleration;
effect->pos.x -= effect->velocity.x;
effect->pos.y -= effect->velocity.y;
effect->pos.z -= effect->velocity.z;
effect->vFdFxScaleMod = 0.0f;
effect->alpha = alpha;
effect->vFdFxYStop = Rand_ZeroFloat(10.0f);
effect->timer2 = 0;
effect->scale = scale / 400.0f;
effect->kbAngle = kbAngle;
break;
}
}
}
void BossFd2_SpawnEmber(PlayState* play, BossFdEffect* effect, Vec3f* position, Vec3f* velocity, Vec3f* acceleration,
f32 scale) {
s16 i;
for (i = 0; i < 180; i++, effect++) {
if (effect->type == 0) {
effect->type = BFD_FX_EMBER;
effect->pos = *position;
effect->velocity = *velocity;
effect->accel = *acceleration;
effect->scale = scale / 1000.0f;
effect->alpha = 255;
effect->timer1 = (s16)Rand_ZeroFloat(10.0f);
break;
}
}
}
void BossFd2_SpawnSkullPiece(PlayState* play, BossFdEffect* effect, Vec3f* position, Vec3f* velocity,
Vec3f* acceleration, f32 scale) {
s16 i;
for (i = 0; i < 180; i++, effect++) {
if (effect->type == BFD_FX_NONE) {
effect->type = BFD_FX_SKULL_PIECE;
effect->pos = *position;
effect->velocity = *velocity;
effect->accel = *acceleration;
effect->scale = scale / 1000.0f;
effect->vFdFxRotX = Rand_ZeroFloat(100.0f);
effect->vFdFxRotY = Rand_ZeroFloat(100.0f);
break;
}
}
}
void BossFd2_SpawnDust(BossFdEffect* effect, Vec3f* position, Vec3f* velocity, Vec3f* acceleration, f32 scale) {
s16 i;
for (i = 0; i < 180; i++, effect++) {
if (effect->type == BFD_FX_NONE) {
effect->type = BFD_FX_DUST;
effect->pos = *position;
effect->velocity = *velocity;
effect->accel = *acceleration;
effect->timer2 = 0;
effect->scale = scale / 400.0f;
break;
}
}
}
void BossFd2_Init(Actor* thisx, PlayState* play) {
s32 pad;
BossFd2* this = (BossFd2*)thisx;
Actor_ProcessInitChain(&this->actor, sInitChain);
Actor_SetScale(&this->actor, 0.0069999993f);
this->actor.world.pos.y = -850.0f;
ActorShape_Init(&this->actor.shape, -580.0f / this->actor.scale.y, NULL, 0.0f);
SkelAnime_InitFlex(play, &this->skelAnime, &gHoleVolvagiaSkel, &gHoleVolvagiaIdleAnim, NULL, NULL, 0);
if (this->actor.params == BFD_CS_NONE) {
BossFd2_SetupEmerge(this, play);
} else {
this->actionFunc = BossFd2_Wait;
}
Collider_InitJntSph(play, &this->collider);
Collider_SetJntSph(play, &this->collider, &this->actor, &sJntSphInit, this->elements);
}
void BossFd2_Destroy(Actor* thisx, PlayState* play) {
s32 pad;
BossFd2* this = (BossFd2*)thisx;
SkelAnime_Free(&this->skelAnime, play);
Collider_DestroyJntSph(play, &this->collider);
}
void BossFd2_SetupEmerge(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
s16 temp_rand;
s8 health;
osSyncPrintf("UP INIT 1\n");
Animation_PlayOnce(&this->skelAnime, &gHoleVolvagiaEmergeAnim);
this->actionFunc = BossFd2_Emerge;
this->skelAnime.playSpeed = 0.0f;
temp_rand = Rand_ZeroFloat(8.9f);
this->actor.world.pos.x = sHoleLocations[temp_rand].x;
this->actor.world.pos.z = sHoleLocations[temp_rand].z;
this->work[FD2_ACTION_STATE] = 0;
osSyncPrintf("UP INIT 2\n");
this->timers[0] = 10;
if (bossFd != NULL) {
health = bossFd->actor.colChkInfo.health;
if (health >= 18) {
this->work[FD2_FAKEOUT_COUNT] = 0;
} else if (health >= 12) {
this->work[FD2_FAKEOUT_COUNT] = 1;
} else if (health >= 6) {
this->work[FD2_FAKEOUT_COUNT] = 2;
} else {
this->work[FD2_FAKEOUT_COUNT] = 3;
}
}
}
void BossFd2_Emerge(BossFd2* this, PlayState* play) {
s8 health;
BossFd* bossFd = (BossFd*)this->actor.parent;
Player* player = GET_PLAYER(play);
s16 i;
s16 holeTime;
osSyncPrintf("UP 1 mode %d\n", this->work[FD2_ACTION_STATE]);
SkelAnime_Update(&this->skelAnime);
osSyncPrintf("UP 1.5 \n");
switch (this->work[FD2_ACTION_STATE]) {
case 0:
osSyncPrintf("UP time %d \n", this->timers[0]);
osSyncPrintf("PL time %x \n", player);
osSyncPrintf("MT time %x \n", bossFd);
if ((this->timers[0] == 0) && (player->actor.world.pos.y > 70.0f)) {
osSyncPrintf("UP 1.6 \n");
bossFd->faceExposed = 0;
bossFd->holePosition.x = this->actor.world.pos.x;
bossFd->holePosition.z = this->actor.world.pos.z;
Actor_RequestQuakeWithSpeed(play, 1, 50, 0x5000);
this->work[FD2_ACTION_STATE] = 1;
this->work[FD2_HOLE_COUNTER]++;
this->actor.world.pos.y = -200.0f;
health = bossFd->actor.colChkInfo.health;
if (health == 24) {
holeTime = 30;
} else if (health >= 18) {
holeTime = 25;
} else if (health >= 12) {
holeTime = 20;
} else if (health >= 6) {
holeTime = 10;
} else {
holeTime = 5;
}
this->timers[0] = holeTime;
bossFd->timers[4] = this->timers[0] + 10;
osSyncPrintf("UP 1.7 \n");
}
break;
case 1:
if (this->timers[0] == 0) {
if (this->work[FD2_FAKEOUT_COUNT] != 0) {
this->work[FD2_FAKEOUT_COUNT]--;
i = Rand_ZeroFloat(8.9f);
this->actor.world.pos.x = sHoleLocations[i].x;
this->actor.world.pos.z = sHoleLocations[i].z;
this->work[FD2_ACTION_STATE] = 0;
this->timers[0] = 10;
} else {
this->skelAnime.playSpeed = 1.0f;
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaEmergeAnim);
this->work[FD2_ACTION_STATE] = 2;
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_ROAR);
this->actor.shape.rot.y = this->actor.yawTowardsPlayer;
this->timers[0] = 15;
this->actor.world.pos.y = 150.0f;
for (i = 0; i < 10; i++) {
this->rightMane.pos[i].x += Rand_CenteredFloat(100.0f);
this->rightMane.pos[i].z += Rand_CenteredFloat(100.0f);
this->leftMane.pos[i].x += Rand_CenteredFloat(100.0f);
this->leftMane.pos[i].z += Rand_CenteredFloat(100.0f);
}
bossFd->work[BFD_SPLASH_TIMER] = 5;
}
}
break;
case 2:
Math_ApproachS(&this->actor.shape.rot.y, this->actor.yawTowardsPlayer, 3, 0x7D0);
if ((this->timers[0] == 1) && (this->actor.xzDistToPlayer < 120.0f)) {
func_8002F6D4(play, &this->actor, 3.0f, this->actor.yawTowardsPlayer, 2.0f, 0x20);
Actor_PlaySfx(&player->actor, NA_SE_PL_BODY_HIT);
}
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
BossFd2_SetupIdle(this, play);
}
break;
}
osSyncPrintf("UP 2\n");
}
void BossFd2_SetupIdle(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
s8 health;
s16 idleTime;
osSyncPrintf("UP INIT 1\n");
Animation_PlayLoop(&this->skelAnime, &gHoleVolvagiaTurnAnim);
this->actionFunc = BossFd2_Idle;
health = bossFd->actor.colChkInfo.health;
if (health == 24) {
idleTime = 50;
} else if (health >= 18) {
idleTime = 40;
} else if (health >= 12) {
idleTime = 40;
} else if (health >= 6) {
idleTime = 30;
} else {
idleTime = 20;
}
this->timers[0] = idleTime;
}
void BossFd2_Idle(BossFd2* this, PlayState* play) {
s16 prevToLink;
SkelAnime_Update(&this->skelAnime);
prevToLink = this->work[FD2_TURN_TO_LINK];
this->work[FD2_TURN_TO_LINK] =
Math_SmoothStepToS(&this->actor.shape.rot.y, this->actor.yawTowardsPlayer, 3, 0x7D0, 0);
osSyncPrintf("SW1 = %d\n", prevToLink);
osSyncPrintf("SW2 = %d\n", this->work[FD2_TURN_TO_LINK]);
if ((fabsf(prevToLink) <= 1000.0f) && (1000.0f < fabsf(this->work[FD2_TURN_TO_LINK]))) {
Animation_MorphToLoop(&this->skelAnime, &gHoleVolvagiaTurnAnim, -5.0f);
}
if ((1000.0f < fabsf(prevToLink)) && (fabsf(this->work[FD2_TURN_TO_LINK]) <= 1000.0f)) {
Animation_MorphToLoop(&this->skelAnime, &gHoleVolvagiaIdleAnim, -5.0f);
}
if (this->timers[0] == 0) {
if (this->actor.xzDistToPlayer < 200.0f) {
BossFd2_SetupClawSwipe(this, play);
} else {
BossFd2_SetupBreatheFire(this, play);
}
}
}
void BossFd2_SetupBurrow(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
Animation_MorphToPlayOnce(&this->skelAnime, &gHoleVolvagiaBurrowAnim, -5.0f);
this->actionFunc = BossFd2_Burrow;
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaBurrowAnim);
bossFd->timers[4] = 30;
this->work[FD2_ACTION_STATE] = 0;
}
void BossFd2_Burrow(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
if (this->work[FD2_ACTION_STATE] == 0) {
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
this->work[FD2_ACTION_STATE] = 1;
this->timers[0] = 25;
}
} else {
Math_ApproachF(&this->actor.world.pos.y, -100.0f, 1.0f, 10.0f);
if (this->timers[0] == 0) {
if ((this->work[FD2_HOLE_COUNTER] >= 3) && ((s8)bossFd->actor.colChkInfo.health < 24)) {
this->work[FD2_HOLE_COUNTER] = 0;
this->actionFunc = BossFd2_Wait;
bossFd->handoffSignal = FD2_SIGNAL_FLY;
} else {
BossFd2_SetupEmerge(this, play);
}
}
}
}
void BossFd2_SetupBreatheFire(BossFd2* this, PlayState* play) {
Animation_MorphToPlayOnce(&this->skelAnime, &gHoleVolvagiaBreatheFireAnim, -5.0f);
this->actionFunc = BossFd2_BreatheFire;
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaBreatheFireAnim);
this->work[FD2_ACTION_STATE] = 0;
}
static Vec3f sUnkVec = { 0.0f, 0.0f, 50.0f }; // Unused? BossFd uses a similar array for its fire breath sfx.
void BossFd2_BreatheFire(BossFd2* this, PlayState* play) {
s16 i;
Vec3f toLink;
s16 angleX;
s16 angleY;
s16 breathOpacity = 0;
BossFd* bossFd = (BossFd*)this->actor.parent;
Player* player = GET_PLAYER(play);
f32 tempX;
f32 tempY;
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
BossFd2_SetupBurrow(this, play);
}
if ((25.0f <= this->skelAnime.curFrame) && (this->skelAnime.curFrame < 70.0f)) {
if (this->skelAnime.curFrame == 25.0f) {
play->envCtx.lightBlend = 0.0f;
}
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_FIRE - SFX_FLAG);
if (this->skelAnime.curFrame > 50) {
breathOpacity = (70.0f - this->skelAnime.curFrame) * 12.0f;
} else {
breathOpacity = 255;
}
toLink.x = player->actor.world.pos.x - this->headPos.x;
toLink.y = player->actor.world.pos.y - this->headPos.y;
toLink.z = player->actor.world.pos.z - this->headPos.z;
angleY = Math_Atan2S(toLink.z, toLink.x);
angleX = -Math_Atan2S(sqrtf(SQ(toLink.x) + SQ(toLink.z)), toLink.y);
angleY -= this->actor.shape.rot.y;
if (angleY > 0x1F40) {
angleY = 0x1F40;
}
if (angleY < -0x1F40) {
angleY = -0x1F40;
}
angleX += (-0x1B58);
if (angleX > 0x3E8) {
angleX = 0x3E8;
}
if (angleX < -0xFA0) {
angleX = -0xFA0;
}
Math_ApproachS(&this->headRot.y, angleY, 5, 0x7D0);
Math_ApproachS(&this->headRot.x, angleX, 5, 0x7D0);
} else {
Math_ApproachS(&this->headRot.y, 0, 5, 0x7D0);
Math_ApproachS(&this->headRot.x, 0, 5, 0x7D0);
}
if (breathOpacity != 0) {
f32 breathScale;
Vec3f spawnSpeed = { 0.0f, 0.0f, 0.0f };
Vec3f spawnVel;
Vec3f spawnAccel = { 0.0f, 0.0f, 0.0f };
Vec3f spawnPos;
bossFd->fogMode = 2;
spawnSpeed.z = 30.0f;
spawnPos = this->headPos;
tempY = BINANG_TO_RAD_ALT(this->actor.shape.rot.y + this->headRot.y);
tempX = BINANG_TO_RAD_ALT(this->headRot.x) + 1.0f / 2;
Matrix_RotateY(tempY, MTXMODE_NEW);
Matrix_RotateX(tempX, MTXMODE_APPLY);
Matrix_MultVec3f(&spawnSpeed, &spawnVel);
breathScale = 300.0f + 50.0f * Math_SinS(this->work[FD2_VAR_TIMER] * 0x2000);
BossFd2_SpawnFireBreath(play, bossFd->effects, &spawnPos, &spawnVel, &spawnAccel, breathScale, breathOpacity,
this->actor.shape.rot.y + this->headRot.y);
spawnPos.x += spawnVel.x * 0.5f;
spawnPos.y += spawnVel.y * 0.5f;
spawnPos.z += spawnVel.z * 0.5f;
breathScale = 300.0f + 50.0f * Math_SinS(this->work[FD2_VAR_TIMER] * 0x2000);
BossFd2_SpawnFireBreath(play, bossFd->effects, &spawnPos, &spawnVel, &spawnAccel, breathScale, breathOpacity,
this->actor.shape.rot.y + this->headRot.y);
spawnSpeed.x = 0.0f;
spawnSpeed.y = 17.0f;
spawnSpeed.z = 0.0f;
for (i = 0; i < 6; i++) {
tempY = Rand_ZeroFloat(2.0f * M_PI);
tempX = Rand_ZeroFloat(2.0f * M_PI);
Matrix_RotateY(tempY, MTXMODE_NEW);
Matrix_RotateX(tempX, MTXMODE_APPLY);
Matrix_MultVec3f(&spawnSpeed, &spawnVel);
spawnAccel.x = (spawnVel.x * -10.0f) / 100.0f;
spawnAccel.y = (spawnVel.y * -10.0f) / 100.0f;
spawnAccel.z = (spawnVel.z * -10.0f) / 100.0f;
BossFd2_SpawnEmber(play, bossFd->effects, &this->headPos, &spawnVel, &spawnAccel,
(s16)Rand_ZeroFloat(2.0f) + 8);
}
}
}
void BossFd2_SetupClawSwipe(BossFd2* this, PlayState* play) {
Animation_MorphToPlayOnce(&this->skelAnime, &gHoleVolvagiaClawSwipeAnim, -5.0f);
this->actionFunc = BossFd2_ClawSwipe;
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaClawSwipeAnim);
}
void BossFd2_ClawSwipe(BossFd2* this, PlayState* play) {
SkelAnime_Update(&this->skelAnime);
if (Animation_OnFrame(&this->skelAnime, 5.0f)) {
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_ROAR);
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_SW_NAIL);
}
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
BossFd2_SetupBurrow(this, play);
}
}
void BossFd2_SetupVulnerable(BossFd2* this, PlayState* play) {
Animation_PlayOnce(&this->skelAnime, &gHoleVolvagiaKnockoutAnim);
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaKnockoutAnim);
this->actionFunc = BossFd2_Vulnerable;
this->work[FD2_ACTION_STATE] = 0;
}
void BossFd2_Vulnerable(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
s16 i;
this->disableAT = true;
this->actor.flags |= ACTOR_FLAG_10;
SkelAnime_Update(&this->skelAnime);
switch (this->work[FD2_ACTION_STATE]) {
case 0:
if (Animation_OnFrame(&this->skelAnime, 13.0f)) {
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_MAHI2);
}
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME] - 3.0f)) {
for (i = 0; i < 25; i++) {
Vec3f spawnVel;
Vec3f spawnAccel = { 0.0f, 0.0f, 0.0f };
Vec3f spawnPos;
spawnVel.x = Rand_CenteredFloat(8.0f);
spawnVel.y = Rand_ZeroFloat(1.0f);
spawnVel.z = Rand_CenteredFloat(8.0f);
spawnAccel.y = 0.5f;
spawnPos.x = Rand_CenteredFloat(10.0f) + this->actor.focus.pos.x;
spawnPos.y = Rand_CenteredFloat(10.0f) + this->actor.focus.pos.y;
spawnPos.z = Rand_CenteredFloat(10.0f) + this->actor.focus.pos.z;
BossFd2_SpawnDust(bossFd->effects, &spawnPos, &spawnVel, &spawnAccel,
Rand_ZeroFloat(100.0f) + 300.0f);
}
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_LAND);
}
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
Animation_MorphToLoop(&this->skelAnime, &gHoleVolvagiaVulnerableAnim, -5.0f);
this->work[FD2_ACTION_STATE] = 1;
this->timers[0] = 60;
}
break;
case 1:
if ((this->work[FD2_VAR_TIMER] & 0xF) == 0xF) {
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_KNOCKOUT);
}
if (this->timers[0] == 0) {
BossFd2_SetupBurrow(this, play);
}
break;
}
}
void BossFd2_SetupDamaged(BossFd2* this, PlayState* play) {
Animation_PlayOnce(&this->skelAnime, &gHoleVolvagiaHitAnim);
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaHitAnim);
this->actionFunc = BossFd2_Damaged;
this->work[FD2_ACTION_STATE] = 0;
}
void BossFd2_Damaged(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
SkelAnime_Update(&this->skelAnime);
this->disableAT = true;
if (this->work[FD2_ACTION_STATE] == 0) {
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
Animation_PlayOnce(&this->skelAnime, &gHoleVolvagiaDamagedAnim);
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaDamagedAnim);
this->work[FD2_ACTION_STATE] = 1;
}
} else if (this->work[FD2_ACTION_STATE] == 1) {
if (Animation_OnFrame(&this->skelAnime, 6.0f)) {
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_DAMAGE2);
}
if (Animation_OnFrame(&this->skelAnime, 20.0f)) {
bossFd->timers[4] = 30;
}
if (Animation_OnFrame(&this->skelAnime, this->fwork[FD2_END_FRAME])) {
this->work[FD2_ACTION_STATE] = 2;
this->timers[0] = 25;
}
} else {
Math_ApproachF(&this->actor.world.pos.y, -100.0f, 1.0f, 10.0f);
if (this->timers[0] == 0) {
this->actionFunc = BossFd2_Wait;
bossFd->handoffSignal = FD2_SIGNAL_FLY;
}
}
}
void BossFd2_SetupDeath(BossFd2* this, PlayState* play) {
this->fwork[FD2_END_FRAME] = Animation_GetLastFrame(&gHoleVolvagiaDamagedAnim);
Animation_Change(&this->skelAnime, &gHoleVolvagiaDamagedAnim, 1.0f, 0.0f, this->fwork[FD2_END_FRAME],
ANIMMODE_ONCE_INTERP, -3.0f);
this->actionFunc = BossFd2_Death;
this->actor.flags &= ~ACTOR_FLAG_0;
this->deathState = DEATH_START;
}
void BossFd2_UpdateCamera(BossFd2* this, PlayState* play) {
if (this->subCamId != SUB_CAM_ID_DONE) {
Math_ApproachF(&this->subCamEye.x, this->subCamEyeNext.x, this->subCamEyeMaxVelFrac.x,
this->subCamEyeVel.x * this->subCamVelFactor);
Math_ApproachF(&this->subCamEye.y, this->subCamEyeNext.y, this->subCamEyeMaxVelFrac.y,
this->subCamEyeVel.y * this->subCamVelFactor);
Math_ApproachF(&this->subCamEye.z, this->subCamEyeNext.z, this->subCamEyeMaxVelFrac.z,
this->subCamEyeVel.z * this->subCamVelFactor);
Math_ApproachF(&this->subCamAt.x, this->subCamAtNext.x, this->subCamAtMaxVelFrac.x,
this->subCamAtVel.x * this->subCamVelFactor);
Math_ApproachF(&this->subCamAt.y, this->subCamAtNext.y, this->subCamAtMaxVelFrac.y,
this->subCamAtVel.y * this->subCamVelFactor);
Math_ApproachF(&this->subCamAt.z, this->subCamAtNext.z, this->subCamAtMaxVelFrac.z,
this->subCamAtVel.z * this->subCamVelFactor);
Math_ApproachF(&this->subCamVelFactor, 1.0f, 1.0f, this->subCamAccel);
this->subCamAt.y += this->subCamAtYOffset;
Play_SetCameraAtEye(play, this->subCamId, &this->subCamAt, &this->subCamEye);
Math_ApproachF(&this->subCamAtYOffset, 0.0f, 1.0f, 0.1f);
}
}
void BossFd2_Death(BossFd2* this, PlayState* play) {
f32 retreatSpeed;
Vec3f sp70;
Vec3f sp64;
BossFd* bossFd = (BossFd*)this->actor.parent;
Camera* mainCam = Play_GetCamera(play, CAM_ID_MAIN);
f32 pad3;
f32 pad2;
f32 pad1;
f32 cameraShake;
SkelAnime* skelAnime = &this->skelAnime;
SkelAnime_Update(skelAnime);
switch (this->deathState) {
case DEATH_START:
this->deathState = DEATH_RETREAT;
Cutscene_StartManual(play, &play->csCtx);
func_8002DF54(play, &this->actor, PLAYER_CSMODE_1);
this->subCamId = Play_CreateSubCamera(play);
Play_ChangeCameraStatus(play, CAM_ID_MAIN, CAM_STAT_WAIT);
Play_ChangeCameraStatus(play, this->subCamId, CAM_STAT_ACTIVE);
this->subCamEye = mainCam->eye;
this->subCamAt = mainCam->at;
this->subCamEyeVel.x = 100.0f;
this->subCamEyeVel.y = 100.0f;
this->subCamEyeVel.z = 100.0f;
this->subCamAtVel.x = 100.0f;
this->subCamAtVel.y = 100.0f;
this->subCamAtVel.z = 100.0f;
this->subCamAccel = 0.02f;
this->timers[0] = 0;
this->work[FD2_HOLE_COUNTER] = 0;
this->subCamEyeMaxVelFrac.x = 0.1f;
this->subCamEyeMaxVelFrac.y = 0.1f;
this->subCamEyeMaxVelFrac.z = 0.1f;
this->subCamAtMaxVelFrac.x = 0.1f;
this->subCamAtMaxVelFrac.y = 0.1f;
this->subCamAtMaxVelFrac.z = 0.1f;
FALLTHROUGH;
case DEATH_RETREAT:
this->work[FD2_HOLE_COUNTER]++;
if (this->work[FD2_HOLE_COUNTER] < 15) {
retreatSpeed = 1.0f;
} else if (this->work[FD2_HOLE_COUNTER] < 20) {
retreatSpeed = 0.5f;
} else {
retreatSpeed = 0.25f;
}
if ((this->work[FD2_HOLE_COUNTER] == 1) || (this->work[FD2_HOLE_COUNTER] == 40)) {
this->work[FD2_SCREAM_TIMER] = 20;
if (this->work[FD2_HOLE_COUNTER] == 40) {
Audio_StopSfxById(NA_SE_EN_VALVAISA_DEAD);
}
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_DAMAGE2);
}
Math_ApproachF(&this->skelAnime.playSpeed, retreatSpeed, 1.0f, 1.0f);
Matrix_RotateY(BINANG_TO_RAD_ALT(this->actor.yawTowardsPlayer) + 0.2f, MTXMODE_NEW);
sp70.x = 0.0f;
sp70.y = 0.0f;
sp70.z = 250.0f;
Matrix_MultVec3f(&sp70, &sp64);
this->subCamEyeNext.x = this->actor.world.pos.x + sp64.x;
this->subCamEyeNext.y = 140.0f;
this->subCamEyeNext.z = this->actor.world.pos.z + sp64.z;
if (this->actor.focus.pos.y >= 90.0f) {
this->subCamAtNext.y = this->actor.focus.pos.y;
this->subCamAtNext.x = this->actor.focus.pos.x;
this->subCamAtNext.z = this->actor.focus.pos.z;
}
if (this->timers[0] == 0) {
if (Animation_OnFrame(skelAnime, 20.0f)) {
bossFd->timers[4] = 60;
}
if (this->work[FD2_HOLE_COUNTER] >= 100) {
this->deathState = DEATH_HANDOFF;
this->timers[0] = 50;
}
} else if (Animation_OnFrame(skelAnime, 15.0f)) {
Animation_MorphToPlayOnce(skelAnime, &gHoleVolvagiaDamagedAnim, -10.0f);
}
break;
case DEATH_HANDOFF:
if (this->timers[0] == 0) {
this->actor.draw = NULL;
this->deathState = DEATH_FD_BODY;
bossFd->handoffSignal = FD2_SIGNAL_DEATH;
this->work[FD2_ACTION_STATE] = 0;
this->subCamVelFactor = 0.0f;
} else {
Math_ApproachF(&this->actor.world.pos.y, -100.0f, 1.0f, 5.0f);
}
break;
case DEATH_FD_BODY:
if (bossFd->actor.world.pos.y < 80.0f) {
if (bossFd->actor.world.rot.x > 0x3000) {
this->subCamAtNext = bossFd->actor.world.pos;
this->subCamAtNext.y = 80.0f;
this->subCamEyeNext.x = bossFd->actor.world.pos.x;
this->subCamEyeNext.y = 150.0f;
this->subCamEyeNext.z = bossFd->actor.world.pos.z + 300.0f;
}
} else {
this->subCamAtNext = bossFd->actor.world.pos;
this->subCamEyeNext.x = this->actor.world.pos.x;
Math_ApproachF(&this->subCamEyeNext.y, 200.0f, 1.0f, 2.0f);
Math_ApproachF(&this->subCamEyeNext.z, bossFd->actor.world.pos.z + 200.0f, 1.0f, 3.0f);
if (this->work[FD2_ACTION_STATE] == 0) {
this->work[FD2_ACTION_STATE]++;
this->subCamVelFactor = 0.0f;
this->subCamAccel = 0.02f;
func_8002DF54(play, &bossFd->actor, PLAYER_CSMODE_1);
}
}
if ((bossFd->work[BFD_ACTION_STATE] == BOSSFD_BONES_FALL) && (bossFd->timers[0] == 5)) {
this->deathState = DEATH_FD_SKULL;
this->subCamVelFactor = 0.0f;
this->subCamAccel = 0.02f;
this->subCamEyeNext.y = 150.0f;
this->subCamEyeNext.z = bossFd->actor.world.pos.z + 300.0f;
}
break;
case DEATH_FD_SKULL:
Math_ApproachF(&this->subCamAtNext.y, 100.0, 1.0f, 100.0f);
this->subCamAtNext.x = 0.0f;
this->subCamAtNext.z = 0.0f;
this->subCamEyeNext.x = 0.0f;
this->subCamEyeNext.y = 140.0f;
Math_ApproachF(&this->subCamEyeNext.z, 220.0f, 0.5f, 1.15f);
if (bossFd->work[BFD_CAM_SHAKE_TIMER] != 0) {
bossFd->work[BFD_CAM_SHAKE_TIMER]--;
cameraShake = bossFd->work[BFD_CAM_SHAKE_TIMER] / 0.5f;
if (cameraShake >= 20.0f) {
cameraShake = 20.0f;
}
this->subCamAtYOffset = (bossFd->work[BFD_CAM_SHAKE_TIMER] & 1) ? cameraShake : -cameraShake;
}
if (bossFd->work[BFD_ACTION_STATE] == BOSSFD_SKULL_BURN) {
this->deathState = DEATH_FINISH;
mainCam->eye = this->subCamEye;
mainCam->eyeNext = this->subCamEye;
mainCam->at = this->subCamAt;
Play_ReturnToMainCam(play, this->subCamId, 0);
this->subCamId = SUB_CAM_ID_DONE;
Cutscene_StopManual(play, &play->csCtx);
func_8002DF54(play, &this->actor, PLAYER_CSMODE_7);
Actor_SpawnAsChild(&play->actorCtx, &this->actor, play, ACTOR_DOOR_WARP1, 0.0f, 100.0f, 0.0f, 0, 0, 0,
WARP_DUNGEON_ADULT);
Flags_SetClear(play, play->roomCtx.curRoom.num);
}
break;
case DEATH_FINISH:
break;
}
BossFd2_UpdateCamera(this, play);
}
void BossFd2_Wait(BossFd2* this, PlayState* play) {
BossFd* bossFd = (BossFd*)this->actor.parent;
if (bossFd->handoffSignal == FD2_SIGNAL_GROUND) {
bossFd->handoffSignal = FD2_SIGNAL_NONE;
BossFd2_SetupEmerge(this, play);
this->timers[0] = 20;
this->work[FD2_HOLE_COUNTER] = 0;
}
}
void BossFd2_CollisionCheck(BossFd2* this, PlayState* play) {
s16 i;
ColliderInfo* hurtbox;
BossFd* bossFd = (BossFd*)this->actor.parent;
if (this->actionFunc == BossFd2_ClawSwipe) {
Player* player = GET_PLAYER(play);
for (i = 0; i < ARRAY_COUNT(this->elements); i++) {
if (this->collider.elements[i].info.toucherFlags & TOUCH_HIT) {
this->collider.elements[i].info.toucherFlags &= ~TOUCH_HIT;
Actor_PlaySfx(&player->actor, NA_SE_PL_BODY_HIT);
}
}
}
if (!bossFd->faceExposed) {
this->collider.elements[0].info.elemType = ELEMTYPE_UNK2;
this->collider.base.colType = COLTYPE_METAL;
} else {
this->collider.elements[0].info.elemType = ELEMTYPE_UNK3;
this->collider.base.colType = COLTYPE_HIT3;
}
if (this->collider.elements[0].info.bumperFlags & BUMP_HIT) {
this->collider.elements[0].info.bumperFlags &= ~BUMP_HIT;
hurtbox = this->collider.elements[0].info.acHitInfo;
if (!bossFd->faceExposed) {
if (hurtbox->toucher.dmgFlags & DMG_HAMMER) {
bossFd->actor.colChkInfo.health -= 2;
if ((s8)bossFd->actor.colChkInfo.health <= 2) {
bossFd->actor.colChkInfo.health = 1;
}
bossFd->faceExposed = true;
BossFd2_SetupVulnerable(this, play);
this->work[FD2_INVINC_TIMER] = 30;
this->work[FD2_DAMAGE_FLASH_TIMER] = 5;
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_MAHI1);
for (i = 0; i < 30; i++) {
Vec3f debrisVel = { 0.0f, 0.0f, 0.0f };
Vec3f debrisAccel = { 0.0f, -1.0f, 0.0f };
Vec3f debrisPos;
debrisVel.x = Rand_CenteredFloat(10.0f);
debrisVel.y = Rand_ZeroFloat(5.0f) + 8.0f;
debrisVel.z = Rand_CenteredFloat(10.0f);
debrisPos.x = this->actor.focus.pos.x;
debrisPos.y = this->actor.focus.pos.y;
debrisPos.z = this->actor.focus.pos.z;
BossFd2_SpawnDebris(play, bossFd->effects, &debrisPos, &debrisVel, &debrisAccel,
(s16)Rand_ZeroFloat(10.0) + 10);
}
}
} else {
u8 canKill = false;
u8 damage;
if ((damage = CollisionCheck_GetSwordDamage(hurtbox->toucher.dmgFlags)) == 0) {
damage = (hurtbox->toucher.dmgFlags & DMG_ARROW_ICE) ? 4 : 2;
} else {
canKill = true;
}
if (hurtbox->toucher.dmgFlags & DMG_HOOKSHOT) {
damage = 0;
}
if (((s8)bossFd->actor.colChkInfo.health > 2) || canKill) {
bossFd->actor.colChkInfo.health -= damage;
osSyncPrintf(VT_FGCOL(GREEN));
osSyncPrintf("damage %d\n", damage);
}
osSyncPrintf(VT_RST);
osSyncPrintf("hp %d\n", bossFd->actor.colChkInfo.health);
if ((s8)bossFd->actor.colChkInfo.health <= 0) {
bossFd->actor.colChkInfo.health = 0;
BossFd2_SetupDeath(this, play);
this->work[FD2_DAMAGE_FLASH_TIMER] = 10;
this->work[FD2_INVINC_TIMER] = 30000;
SEQCMD_STOP_SEQUENCE(SEQ_PLAYER_BGM_MAIN, 1);
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_DEAD);
Enemy_StartFinishingBlow(play, &this->actor);
} else if (damage) {
BossFd2_SetupDamaged(this, play);
this->work[FD2_DAMAGE_FLASH_TIMER] = 10;
this->work[FD2_INVINC_TIMER] = 100;
Actor_PlaySfx(&this->actor, NA_SE_EN_VALVAISA_DAMAGE1);
}
if (damage) {
for (i = 0; i < 30; i++) {
Vec3f pieceVel = { 0.0f, 0.0f, 0.0f };
Vec3f pieceAccel = { 0.0f, -1.0f, 0.0f };
Vec3f piecePos;
pieceVel.x = Rand_CenteredFloat(6.0f);
pieceVel.y = Rand_ZeroFloat(4.0f) + 6.0f;
pieceVel.z = Rand_CenteredFloat(6.0f);
piecePos.x = this->actor.focus.pos.x;
piecePos.y = this->actor.focus.pos.y;
piecePos.z = this->actor.focus.pos.z;
BossFd2_SpawnSkullPiece(play, bossFd->effects, &piecePos, &pieceVel, &pieceAccel,
(s16)Rand_ZeroFloat(6.0f) + 10);
}
}
}
}
}
void BossFd2_UpdateFace(BossFd2* this, PlayState* play) {
f32 maxOpen;
f32 openRate;
s16 eyeStates[5] = { EYE_OPEN, EYE_HALF, EYE_CLOSED, EYE_CLOSED, EYE_HALF };
if (((this->work[FD2_VAR_TIMER] % 8) == 0) && (Rand_ZeroOne() < 0.3f)) {
this->work[FD2_BLINK_TIMER] = 4;
}
if ((this->actionFunc == BossFd2_Vulnerable) || (this->actionFunc == BossFd2_Damaged)) {
if (this->work[FD2_VAR_TIMER] & 0x10) {
this->eyeState = EYE_HALF;
} else {
this->eyeState = EYE_CLOSED;
}
} else {
this->eyeState = eyeStates[this->work[FD2_BLINK_TIMER]];
}
if (this->work[FD2_BLINK_TIMER] != 0) {
this->work[FD2_BLINK_TIMER]--;
}
if (this->work[FD2_SCREAM_TIMER] != 0) {
maxOpen = 6000.0f;
openRate = 1300.0f;
} else {
maxOpen = (this->work[FD2_VAR_TIMER] & 0x10) ? 1000.0f : 0.0f;
openRate = 700.0f;
}
Math_ApproachF(&this->jawOpening, maxOpen, 0.3f, openRate);
if (this->work[FD2_SCREAM_TIMER] != 0) {
this->work[FD2_SCREAM_TIMER]--;
}
}
void BossFd2_Update(Actor* thisx, PlayState* play2) {
PlayState* play = play2;
BossFd2* this = (BossFd2*)thisx;
s16 i;
osSyncPrintf("FD2 move start \n");
this->disableAT = false;
this->actor.flags &= ~ACTOR_FLAG_10;
this->work[FD2_VAR_TIMER]++;
this->work[FD2_UNK_TIMER]++;
this->actionFunc(this, play);
for (i = 0; i < ARRAY_COUNT(this->timers); i++) {
if (this->timers[i] != 0) {
this->timers[i]--;
}
}
if (this->work[FD2_DAMAGE_FLASH_TIMER] != 0) {
this->work[FD2_DAMAGE_FLASH_TIMER]--;
}
if (this->work[FD2_INVINC_TIMER] != 0) {
this->work[FD2_INVINC_TIMER]--;
}
if (this->deathState == DEATH_START) {
if (this->work[FD2_INVINC_TIMER] == 0) {
BossFd2_CollisionCheck(this, play);
}
CollisionCheck_SetAC(play, &play->colChkCtx, &this->collider.base);
CollisionCheck_SetOC(play, &play->colChkCtx, &this->collider.base);
if (!this->disableAT) {
CollisionCheck_SetAT(play, &play->colChkCtx, &this->collider.base);
}
}
BossFd2_UpdateFace(this, play);
this->fwork[FD2_TEX1_SCROLL_X] += 4.0f;
this->fwork[FD2_TEX1_SCROLL_Y] = 120.0f;
this->fwork[FD2_TEX2_SCROLL_X] += 3.0f;
this->fwork[FD2_TEX2_SCROLL_Y] -= 2.0f;
if (this->actor.focus.pos.y < 90.0f) {
this->actor.flags &= ~ACTOR_FLAG_0;
} else {
this->actor.flags |= ACTOR_FLAG_0;
}
}
s32 BossFd2_OverrideLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* thisx) {
BossFd2* this = (BossFd2*)thisx;
BossFd* bossFd = (BossFd*)this->actor.parent;
if (limbIndex == 31) {
rot->y -= (f32)this->headRot.y;
rot->z += (f32)this->headRot.x;
}
switch (limbIndex) {
case 35:
case 36:
rot->z -= this->jawOpening * 0.1f;
break;
case 32:
rot->z += this->jawOpening;
break;
}
if ((bossFd->faceExposed == 1) && (limbIndex == 35)) {
*dList = gHoleVolvagiaBrokenFaceDL;
}
if ((limbIndex == 32) || (limbIndex == 35) || (limbIndex == 36)) {
OPEN_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2165);
gDPPipeSync(POLY_OPA_DISP++);
gDPSetEnvColor(POLY_OPA_DISP++, 255, 255, 255, (s8)bossFd->fwork[BFD_HEAD_TEX2_ALPHA]);
CLOSE_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2172);
} else {
OPEN_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2174);
gDPPipeSync(POLY_OPA_DISP++);
gDPSetEnvColor(POLY_OPA_DISP++, 255, 255, 255, (s8)bossFd->fwork[BFD_BODY_TEX2_ALPHA]);
CLOSE_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2181);
}
if ((0 < limbIndex) && (limbIndex < 16)) {
*dList = NULL;
}
return false;
}
void BossFd2_PostLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3s* rot, void* thisx) {
static Vec3f targetMod = { 4500.0f, 0.0f, 0.0f };
static Vec3f headMod = { 4000.0f, 0.0f, 0.0f };
static Vec3f centerManeMod = { 4000.0f, -2900.0, 2000.0f };
static Vec3f rightManeMod = { 4000.0f, -1600.0, 0.0f };
static Vec3f leftManeMod = { 4000.0f, -1600.0, -2000.0f };
BossFd2* this = (BossFd2*)thisx;
if (limbIndex == 35) {
Matrix_MultVec3f(&targetMod, &this->actor.focus.pos);
Matrix_MultVec3f(&headMod, &this->headPos);
Matrix_MultVec3f(¢erManeMod, &this->centerMane.head);
Matrix_MultVec3f(&rightManeMod, &this->rightMane.head);
Matrix_MultVec3f(&leftManeMod, &this->leftMane.head);
}
Collider_UpdateSpheres(limbIndex, &this->collider);
}
void BossFd2_UpdateMane(BossFd2* this, PlayState* play, Vec3f* head, Vec3f* pos, Vec3f* rot, Vec3f* pull, f32* scale) {
f32 sp138[10] = { 0.0f, 100.0f, 50.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
f32 sp110[10] = { 0.0f, 5.0f, -10.0f, 500.0f, 500.0f, 500.0f, 500.0f, 500.0f, 500.0f, 500.0f };
f32 spE8[10] = { 0.4f, 0.6f, 0.8f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f };
s16 i;
Vec3f temp_vec;
f32 temp_f2;
f32 phi_f0;
f32 temp_angleX;
f32 temp_angleY;
Vec3f spBC;
Vec3f spB0;
f32 xyScale;
OPEN_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2389);
Matrix_Push();
gDPPipeSync(POLY_OPA_DISP++);
for (i = 0; i < 10; i++) {
if (i == 0) {
(pos + i)->x = head->x;
(pos + i)->y = head->y;
(pos + i)->z = head->z;
} else {
Math_ApproachF(&(pull + i)->x, 0.0f, 1.0f, 1.0f);
Math_ApproachF(&(pull + i)->y, 0.0f, 1.0f, 1.0f);
Math_ApproachF(&(pull + i)->z, 0.0f, 1.0f, 1.0f);
}
}
for (i = 1; i < 10; i++) {
temp_vec.x = (pos + i)->x + (pull + i)->x - (pos + i - 1)->x;
phi_f0 = (pos + i)->y + (pull + i)->y - 2.0f + sp138[i];
temp_f2 = (pos + i - 1)->y + sp110[i];
if (phi_f0 > temp_f2) {
phi_f0 = temp_f2;
}
if ((head->y >= -910.0f) && (phi_f0 < 110.0f)) {
phi_f0 = 110.0f;
}
temp_vec.y = phi_f0 - (pos + i - 1)->y;
temp_vec.z = (pos + i)->z + (pull + i)->z - (pos + i - 1)->z;
temp_angleY = Math_Atan2F(temp_vec.z, temp_vec.x);
temp_angleX = -Math_Atan2F(sqrtf(SQ(temp_vec.x) + SQ(temp_vec.z)), temp_vec.y);
(rot + i - 1)->y = temp_angleY;
(rot + i - 1)->x = temp_angleX;
spBC.x = 0.0f;
spBC.y = 0.0f;
spBC.z = spE8[i] * 25.0f;
Matrix_RotateY(temp_angleY, MTXMODE_NEW);
Matrix_RotateX(temp_angleX, MTXMODE_APPLY);
Matrix_MultVec3f(&spBC, &spB0);
temp_vec.x = (pos + i)->x;
temp_vec.y = (pos + i)->y;
temp_vec.z = (pos + i)->z;
(pos + i)->x = (pos + i - 1)->x + spB0.x;
(pos + i)->y = (pos + i - 1)->y + spB0.y;
(pos + i)->z = (pos + i - 1)->z + spB0.z;
(pull + i)->x = (((pos + i)->x - temp_vec.x) * 88.0f) / 100.0f;
(pull + i)->y = (((pos + i)->y - temp_vec.y) * 88.0f) / 100.0f;
(pull + i)->z = (((pos + i)->z - temp_vec.z) * 88.0f) / 100.0f;
if ((pull + i)->x > 30.0f) {
(pull + i)->x = 30.0f;
}
if ((pull + i)->x < -30.0f) {
(pull + i)->x = -30.0f;
}
if ((pull + i)->y > 30.0f) {
(pull + i)->y = 30.0f;
}
if ((pull + i)->y < -30.0f) {
(pull + i)->y = -30.0f;
}
if ((pull + i)->z > 30.0f) {
(pull + i)->z = 30.0f;
}
if ((pull + i)->z < -30.0f) {
(pull + i)->z = -30.0f;
}
}
for (i = 0; i < 9; i++) {
Matrix_Translate((pos + i)->x, (pos + i)->y, (pos + i)->z, MTXMODE_NEW);
Matrix_RotateY((rot + i)->y, MTXMODE_APPLY);
Matrix_RotateX((rot + i)->x, MTXMODE_APPLY);
xyScale = (0.01f - (i * 0.0009f)) * spE8[i] * scale[i];
Matrix_Scale(xyScale, xyScale, 0.01f * spE8[i], MTXMODE_APPLY);
Matrix_RotateX(M_PI / 2.0f, MTXMODE_APPLY);
gSPMatrix(POLY_XLU_DISP++, Matrix_NewMtx(play->state.gfxCtx, "../z_boss_fd2.c", 2498),
G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW);
gSPDisplayList(POLY_XLU_DISP++, gHoleVolvagiaManeModelDL);
}
Matrix_Pop();
CLOSE_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2503);
}
void BossFd2_DrawMane(BossFd2* this, PlayState* play) {
s32 pad;
BossFd* bossFd = (BossFd*)this->actor.parent;
s16 i;
OPEN_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2515);
if (1) {}
for (i = 0; i < 10; i++) {
this->centerMane.scale[i] = 1.5f + 0.3f * Math_SinS(5596.0f * this->work[FD2_VAR_TIMER] + i * 0x3200);
this->rightMane.scale[i] = 1.5f + 0.3f * Math_SinS(5496.0f * this->work[FD2_VAR_TIMER] + i * 0x3200);
this->leftMane.scale[i] = 1.5f + 0.3f * Math_CosS(5696.0f * this->work[FD2_VAR_TIMER] + i * 0x3200);
}
Gfx_SetupDL_25Xlu(play->state.gfxCtx);
gSPDisplayList(POLY_XLU_DISP++, gHoleVolvagiaManeMaterialDL);
gDPSetPrimColor(POLY_XLU_DISP++, 0, 0, 255, bossFd->fwork[BFD_MANE_COLOR_CENTER], 0, 255);
BossFd2_UpdateMane(this, play, &this->centerMane.head, this->centerMane.pos, this->centerMane.rot,
this->centerMane.pull, this->centerMane.scale);
gDPSetPrimColor(POLY_XLU_DISP++, 0, 0, 255, bossFd->fwork[BFD_MANE_COLOR_RIGHT], 0, 255);
BossFd2_UpdateMane(this, play, &this->rightMane.head, this->rightMane.pos, this->rightMane.rot,
this->rightMane.pull, this->rightMane.scale);
gDPSetPrimColor(POLY_XLU_DISP++, 0, 0, 255, bossFd->fwork[BFD_MANE_COLOR_LEFT], 0, 255);
BossFd2_UpdateMane(this, play, &this->leftMane.head, this->leftMane.pos, this->leftMane.rot, this->leftMane.pull,
this->leftMane.scale);
CLOSE_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2601);
}
void BossFd2_Draw(Actor* thisx, PlayState* play) {
static void* eyeTextures[] = { gHoleVolvagiaEyeOpenTex, gHoleVolvagiaEyeHalfTex, gHoleVolvagiaEyeClosedTex };
s32 pad;
BossFd2* this = (BossFd2*)thisx;
OPEN_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2617);
osSyncPrintf("FD2 draw start \n");
if (this->actionFunc != BossFd2_Wait) {
Gfx_SetupDL_25Opa(play->state.gfxCtx);
if (this->work[FD2_DAMAGE_FLASH_TIMER] & 2) {
POLY_OPA_DISP = Gfx_SetFog(POLY_OPA_DISP, 255, 255, 255, 0, 900, 1099);
}
gSPSegment(POLY_OPA_DISP++, 0x09, SEGMENTED_TO_VIRTUAL(eyeTextures[this->eyeState]));
gSPSegment(POLY_OPA_DISP++, 0x08,
Gfx_TwoTexScroll(play->state.gfxCtx, G_TX_RENDERTILE, (s16)this->fwork[FD2_TEX1_SCROLL_X],
(s16)this->fwork[FD2_TEX1_SCROLL_Y], 0x20, 0x20, 1,
(s16)this->fwork[FD2_TEX2_SCROLL_X], (s16)this->fwork[FD2_TEX2_SCROLL_Y], 0x20,
0x20));
gDPSetPrimColor(POLY_OPA_DISP++, 0, 0, 255, 255, 255, 255);
gDPSetEnvColor(POLY_OPA_DISP++, 255, 255, 255, 128);
SkelAnime_DrawFlexOpa(play, this->skelAnime.skeleton, this->skelAnime.jointTable, this->skelAnime.dListCount,
BossFd2_OverrideLimbDraw, BossFd2_PostLimbDraw, &this->actor);
BossFd2_DrawMane(this, play);
POLY_OPA_DISP = Play_SetFog(play, POLY_OPA_DISP);
}
CLOSE_DISPS(play->state.gfxCtx, "../z_boss_fd2.c", 2688);
}
|
403c973afd5550a61f8ac0c4c93111c010f5deb7
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/drivers/seclink/seclink_drv_auth.c
|
2bfbb6e0e2d332fffccf6f5c31913f0dfe2160ba
|
[
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 3,420
|
c
|
seclink_drv_auth.c
|
/****************************************************************************
*
* Copyright 2019 Samsung Electronics All Rights Reserved.
*
* 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 <tinyara/config.h>
#include <stdio.h>
#include <errno.h>
#include <tinyara/seclink.h>
#include <tinyara/seclink_drv.h>
#include "seclink_drv_req.h"
#include "seclink_drv_utils.h"
/* Debugging */
#ifdef SLDRV_TAG
#undef SLDRV_TAG
#endif
#define SLDRV_TAG "[SECLINK_DRV_AUTH]"
int hd_handle_auth_request(int cmd, unsigned long arg, void *lower)
{
SLDRV_ENTER;
int res = 0;
struct seclink_req *req = (struct seclink_req *)arg;
if (!req) {
return -EINVAL;
}
struct seclink_auth_info *info = req->req_type.auth;
if (!info) {
return -EINVAL;
}
struct sec_lowerhalf_s *se = (struct sec_lowerhalf_s *)lower;
if (!se || !(se->ops)) {
return -EINVAL;
}
switch (cmd) {
case SECLINKIOC_GENERATERANDOM:
SLDRV_CALL(res, req->res, generate_random, (info->auth_type.random_len, info->data));
break;
case SECLINKIOC_GETHASH:
SLDRV_CALL(res, req->res, get_hash, (info->auth_type.hash_type, info->data, info->auth_data.data));
break;
case SECLINKIOC_GETHMAC:
SLDRV_CALL(res, req->res, get_hmac, (info->auth_type.hmac_type, info->data, info->key_idx, info->auth_data.data));
break;
case SECLINKIOC_RSASIGNMD:
SLDRV_CALL(res, req->res, rsa_sign_md, (info->auth_type.rsa_type, info->data, info->key_idx, info->auth_data.data));
break;
case SECLINKIOC_RSAVERIFYMD:
SLDRV_CALL(res, req->res, rsa_verify_md, (info->auth_type.rsa_type, info->data, info->auth_data.data, info->key_idx));
break;
case SECLINKIOC_ECDSASIGNMD:
SLDRV_CALL(res, req->res, ecdsa_sign_md, (info->auth_type.ecdsa_type, info->data, info->key_idx, info->auth_data.data));
break;
case SECLINKIOC_ECDSAVERIFYMD:
SLDRV_CALL(res, req->res, ecdsa_verify_md, (info->auth_type.ecdsa_type, info->data, info->auth_data.data, info->key_idx));
break;
case SECLINKIOC_DHGENERATEPARAM:
SLDRV_CALL(res, req->res, dh_generate_param, (info->key_idx, info->auth_data.dh_param));
break;
case SECLINKIOC_DHCOMPUTESHAREDSECRET:
SLDRV_CALL(res, req->res, dh_compute_shared_secret, (info->auth_data.dh_param, info->key_idx, info->data));
break;
case SECLINKIOC_ECDHCOMPUTESHAREDSECRET:
SLDRV_CALL(res, req->res, ecdh_compute_shared_secret, (info->auth_data.ecdh_param, info->key_idx, info->data));
break;
case SECLINKIOC_SETCERTIFICATE:
SLDRV_CALL(res, req->res, set_certificate, (info->key_idx, info->data));
break;
case SECLINKIOC_GETCERTIFICATE:
SLDRV_CALL(res, req->res, get_certificate, (info->key_idx, info->data));
break;
case SECLINKIOC_REMOVECERTIFICATE:
SLDRV_CALL(res, req->res, remove_certificate, (info->key_idx));
break;
default:
SLDRV_LOG("Invalid command error\n");
res = -ENOSYS;
}
return res;
}
|
cd05912d377f09c91574923afb11993938f2e9f0
|
ec6a71b57ebe88538269197fd16bede6bc2062ae
|
/erts/emulator/beam/erl_io_queue.c
|
c931e5ffdba9c32dbff385c31a20ea5d8825e06c
|
[
"Apache-2.0"
] |
permissive
|
erlang/otp
|
7c6e88ca955bd6a3ede1530154c80e8ce449a370
|
334589af62a8db25a81afba2ecc50f33ff69ddb8
|
refs/heads/master
| 2023-08-30T23:37:28.061328
| 2023-08-30T04:20:48
| 2023-08-30T04:20:48
| 374,927
| 9,920
| 3,018
|
Apache-2.0
| 2023-09-14T10:37:26
| 2009-11-16T17:17:57
|
Erlang
|
UTF-8
|
C
| false
| false
| 32,814
|
c
|
erl_io_queue.c
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2017-2021. All Rights Reserved.
*
* 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.
*
* %CopyrightEnd%
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "sys.h"
#include "global.h"
#include "bif.h"
#include "erl_bits.h"
#include "erl_io_queue.h"
#define IOL2V_SMALL_BIN_LIMIT (ERL_ONHEAP_BIN_LIMIT * 4)
static void free_binary(ErtsIOQBinary *b, int driver);
static ErtsIOQBinary *alloc_binary(Uint size, char *source, void **iov_base, int driver);
void erts_ioq_init(ErtsIOQueue *q, ErtsAlcType_t alct, int driver)
{
ERTS_CT_ASSERT(offsetof(ErlNifIOVec,flags) == sizeof(ErtsIOVecCommon));
ERTS_CT_ASSERT(sizeof(ErlIOVec) == sizeof(ErtsIOVecCommon));
ERTS_CT_ASSERT(sizeof(size_t) == sizeof(ErlDrvSizeT));
ERTS_CT_ASSERT(sizeof(size_t) == sizeof(Uint));
q->alct = alct;
q->driver = driver;
q->size = 0;
q->v_head = q->v_tail = q->v_start = q->v_small;
q->v_end = q->v_small + ERTS_SMALL_IO_QUEUE;
q->b_head = q->b_tail = q->b_start = q->b_small;
q->b_end = q->b_small + ERTS_SMALL_IO_QUEUE;
}
void erts_ioq_clear(ErtsIOQueue *q)
{
ErtsIOQBinary** binp = q->b_head;
int driver = q->driver;
if (q->v_start != q->v_small)
erts_free(q->alct, (void *) q->v_start);
while(binp < q->b_tail) {
if (*binp != NULL)
free_binary(*binp, driver);
binp++;
}
if (q->b_start != q->b_small)
erts_free(q->alct, (void *) q->b_start);
q->v_start = q->v_end = q->v_head = q->v_tail = NULL;
q->b_start = q->b_end = q->b_head = q->b_tail = NULL;
q->size = 0;
}
static void free_binary(ErtsIOQBinary *b, int driver)
{
if (driver)
driver_free_binary(&b->driver);
else if (erts_refc_dectest(&b->nif.intern.refc, 0) == 0)
erts_bin_free(&b->nif);
}
static ErtsIOQBinary *alloc_binary(Uint size, char *source, void **iov_base, int driver)
{
if (driver) {
ErlDrvBinary *bin = driver_alloc_binary(size);
if (!bin) return NULL;
sys_memcpy(bin->orig_bytes, source, size);
*iov_base = bin->orig_bytes;
return (ErtsIOQBinary *)bin;
} else {
/* This clause can be triggered in enif_ioq_enq_binary is used */
Binary *bin = erts_bin_nrml_alloc(size);
if (!bin) return NULL;
erts_refc_init(&bin->intern.refc, 1);
sys_memcpy(bin->orig_bytes, source, size);
*iov_base = bin->orig_bytes;
return (ErtsIOQBinary *)bin;
}
}
Uint erts_ioq_size(ErtsIOQueue *q)
{
return q->size;
}
/* expand queue to hold n elements in tail or head */
static int expandq(ErtsIOQueue* q, int n, int tail)
/* tail: 0 if make room in head, make room in tail otherwise */
{
int h_sz; /* room before header */
int t_sz; /* room after tail */
int q_sz; /* occupied */
int nvsz;
SysIOVec* niov;
ErtsIOQBinary** nbinv;
h_sz = q->v_head - q->v_start;
t_sz = q->v_end - q->v_tail;
q_sz = q->v_tail - q->v_head;
if (tail && (n <= t_sz)) /* do we need to expand tail? */
return 0;
else if (!tail && (n <= h_sz)) /* do we need to expand head? */
return 0;
else if (n > (h_sz + t_sz)) { /* need to allocate */
/* we may get little extra but it ok */
nvsz = (q->v_end - q->v_start) + n;
niov = erts_alloc_fnf(q->alct, nvsz * sizeof(SysIOVec));
if (!niov)
return -1;
nbinv = erts_alloc_fnf(q->alct, nvsz * sizeof(ErtsIOQBinary**));
if (!nbinv) {
erts_free(q->alct, (void *) niov);
return -1;
}
if (tail) {
sys_memcpy(niov, q->v_head, q_sz*sizeof(SysIOVec));
if (q->v_start != q->v_small)
erts_free(q->alct, (void *) q->v_start);
q->v_start = niov;
q->v_end = niov + nvsz;
q->v_head = q->v_start;
q->v_tail = q->v_head + q_sz;
sys_memcpy(nbinv, q->b_head, q_sz*sizeof(ErtsIOQBinary*));
if (q->b_start != q->b_small)
erts_free(q->alct, (void *) q->b_start);
q->b_start = nbinv;
q->b_end = nbinv + nvsz;
q->b_head = q->b_start;
q->b_tail = q->b_head + q_sz;
}
else {
sys_memcpy(niov+nvsz-q_sz, q->v_head, q_sz*sizeof(SysIOVec));
if (q->v_start != q->v_small)
erts_free(q->alct, (void *) q->v_start);
q->v_start = niov;
q->v_end = niov + nvsz;
q->v_tail = q->v_end;
q->v_head = q->v_tail - q_sz;
sys_memcpy(nbinv+nvsz-q_sz, q->b_head, q_sz*sizeof(ErtsIOQBinary*));
if (q->b_start != q->b_small)
erts_free(q->alct, (void *) q->b_start);
q->b_start = nbinv;
q->b_end = nbinv + nvsz;
q->b_tail = q->b_end;
q->b_head = q->b_tail - q_sz;
}
}
else if (tail) { /* move to beginning to make room in tail */
sys_memmove(q->v_start, q->v_head, q_sz*sizeof(SysIOVec));
q->v_head = q->v_start;
q->v_tail = q->v_head + q_sz;
sys_memmove(q->b_start, q->b_head, q_sz*sizeof(ErtsIOQBinary*));
q->b_head = q->b_start;
q->b_tail = q->b_head + q_sz;
}
else { /* move to end to make room */
sys_memmove(q->v_end-q_sz, q->v_head, q_sz*sizeof(SysIOVec));
q->v_tail = q->v_end;
q->v_head = q->v_tail-q_sz;
sys_memmove(q->b_end-q_sz, q->b_head, q_sz*sizeof(ErtsIOQBinary*));
q->b_tail = q->b_end;
q->b_head = q->b_tail-q_sz;
}
return 0;
}
static
int skip(ErtsIOVec* vec, Uint skipbytes,
SysIOVec **iovp, ErtsIOQBinary ***binvp,
Uint *lenp)
{
int n;
Uint len;
SysIOVec* iov;
ErtsIOQBinary** binv;
if (vec->common.size <= skipbytes)
return -1;
iov = vec->common.iov;
binv = vec->common.binv;
n = vec->common.vsize;
/* we use do here to strip iov_len=0 from beginning */
do {
len = iov->iov_len;
if (len <= skipbytes) {
skipbytes -= len;
iov++;
binv++;
n--;
}
else {
iov->iov_base = ((char *)(iov->iov_base)) + skipbytes;
iov->iov_len -= skipbytes;
skipbytes = 0;
}
} while(skipbytes > 0);
*binvp = binv;
*iovp = iov;
*lenp = len;
return n;
}
/* Put elements from vec at q tail */
int erts_ioq_enqv(ErtsIOQueue *q, ErtsIOVec *eiov, Uint skipbytes)
{
int n;
Uint len;
Uint size = eiov->common.size - skipbytes;
SysIOVec *iov;
ErtsIOQBinary** binv;
ErtsIOQBinary* b;
if (q == NULL)
return -1;
ASSERT(eiov->common.size >= skipbytes);
if (eiov->common.size <= skipbytes)
return 0;
n = skip(eiov, skipbytes, &iov, &binv, &len);
if (n < 0)
return n;
if (q->v_tail + n >= q->v_end)
if (expandq(q, n, 1))
return -1;
/* Queue and reference all binaries (remove zero length items) */
while(n--) {
if ((len = iov->iov_len) > 0) {
if ((b = *binv) == NULL) { /* special case create binary ! */
b = alloc_binary(len, iov->iov_base, (void**)&q->v_tail->iov_base,
q->driver);
if (!b) return -1;
*q->b_tail++ = b;
q->v_tail->iov_len = len;
q->v_tail++;
}
else {
if (q->driver)
driver_binary_inc_refc(&b->driver);
else
erts_refc_inc(&b->nif.intern.refc, 1);
*q->b_tail++ = b;
*q->v_tail++ = *iov;
}
}
iov++;
binv++;
}
q->size += size; /* update total size in queue */
return 0;
}
/* Put elements from vec at q head */
int erts_ioq_pushqv(ErtsIOQueue *q, ErtsIOVec* vec, Uint skipbytes)
{
int n;
Uint len;
Uint size = vec->common.size - skipbytes;
SysIOVec* iov;
ErtsIOQBinary** binv;
ErtsIOQBinary* b;
if (q == NULL)
return -1;
ASSERT(vec->common.size >= skipbytes);
if (vec->common.size <= skipbytes)
return 0;
n = skip(vec, skipbytes, &iov, &binv, &len);
if (n < 0)
return n;
if (q->v_head - n < q->v_start)
if (expandq(q, n, 0))
return -1;
/* Queue and reference all binaries (remove zero length items) */
iov += (n-1); /* move to end */
binv += (n-1); /* move to end */
while(n--) {
if ((len = iov->iov_len) > 0) {
if ((b = *binv) == NULL) { /* special case create binary ! */
if (q->driver) {
ErlDrvBinary *bin = driver_alloc_binary(len);
if (!bin) return -1;
sys_memcpy(bin->orig_bytes, iov->iov_base, len);
b = (ErtsIOQBinary *)bin;
q->v_head->iov_base = bin->orig_bytes;
}
*--q->b_head = b;
q->v_head--;
q->v_head->iov_len = len;
}
else {
if (q->driver)
driver_binary_inc_refc(&b->driver);
else
erts_refc_inc(&b->nif.intern.refc, 1);
*--q->b_head = b;
*--q->v_head = *iov;
}
}
iov--;
binv--;
}
q->size += size; /* update total size in queue */
return 0;
}
/*
** Remove size bytes from queue head
** Return number of bytes that remain in queue
*/
int erts_ioq_deq(ErtsIOQueue *q, Uint size)
{
Uint len;
if ((q == NULL) || (q->size < size))
return -1;
q->size -= size;
while (size > 0) {
ASSERT(q->v_head != q->v_tail);
len = q->v_head->iov_len;
if (len <= size) {
size -= len;
free_binary(*q->b_head, q->driver);
*q->b_head++ = NULL;
q->v_head++;
}
else {
q->v_head->iov_base = ((char *)(q->v_head->iov_base)) + size;
q->v_head->iov_len -= size;
size = 0;
}
}
/* restart pointers (optimised for enq) */
if (q->v_head == q->v_tail) {
q->v_head = q->v_tail = q->v_start;
q->b_head = q->b_tail = q->b_start;
}
return 0;
}
Uint erts_ioq_peekqv(ErtsIOQueue *q, ErtsIOVec *ev) {
ASSERT(ev);
if (! q) {
return (Uint) -1;
} else {
if ((ev->common.vsize = q->v_tail - q->v_head) == 0) {
ev->common.size = 0;
ev->common.iov = NULL;
ev->common.binv = NULL;
} else {
ev->common.size = q->size;
ev->common.iov = q->v_head;
ev->common.binv = q->b_head;
}
return q->size;
}
}
SysIOVec* erts_ioq_peekq(ErtsIOQueue *q, int* vlenp) /* length of io-vector */
{
if (q == NULL) {
*vlenp = -1;
return NULL;
}
if ((*vlenp = (q->v_tail - q->v_head)) == 0)
return NULL;
return q->v_head;
}
/* Fills a possibly deep list of chars and binaries into vec
** Small characters are first stored in the buffer buf of length ln
** binaries found are copied and linked into msoh
** Return vector length on success,
** -1 on overflow
** -2 on type error
*/
static ERTS_INLINE void
io_list_to_vec_set_vec(SysIOVec **iov, ErtsIOQBinary ***binv,
ErtsIOQBinary *bin, byte *ptr, Uint len,
int *vlen)
{
while (len > MAX_SYSIOVEC_IOVLEN) {
(*iov)->iov_base = ptr;
(*iov)->iov_len = MAX_SYSIOVEC_IOVLEN;
ptr += MAX_SYSIOVEC_IOVLEN;
len -= MAX_SYSIOVEC_IOVLEN;
(*iov)++;
(*vlen)++;
*(*binv)++ = bin;
}
(*iov)->iov_base = ptr;
(*iov)->iov_len = len;
*(*binv)++ = bin;
(*iov)++;
(*vlen)++;
}
int
erts_ioq_iolist_to_vec(Eterm obj, /* io-list */
SysIOVec* iov, /* io vector */
ErtsIOQBinary** binv, /* binary reference vector */
ErtsIOQBinary* cbin, /* binary to store characters */
Uint bin_limit, /* small binaries limit */
int driver)
{
DECLARE_ESTACK(s);
Eterm* objp;
byte *buf = NULL;
Uint len = 0;
Uint csize = 0;
int vlen = 0;
byte* cptr;
if (cbin) {
if (driver) {
buf = (byte*)cbin->driver.orig_bytes;
len = cbin->driver.orig_size;
} else {
buf = (byte*)cbin->nif.orig_bytes;
len = cbin->nif.orig_size;
}
}
cptr = buf;
goto L_jump_start; /* avoid push */
while (!ESTACK_ISEMPTY(s)) {
obj = ESTACK_POP(s);
L_jump_start:
if (is_list(obj)) {
L_iter_list:
objp = list_val(obj);
obj = CAR(objp);
if (is_byte(obj)) {
if (len == 0)
goto L_overflow;
*buf++ = unsigned_val(obj);
csize++;
len--;
} else if (is_binary(obj)) {
ESTACK_PUSH(s, CDR(objp));
goto handle_binary;
} else if (is_list(obj)) {
ESTACK_PUSH(s, CDR(objp));
goto L_iter_list; /* on head */
} else if (!is_nil(obj)) {
goto L_type_error;
}
obj = CDR(objp);
if (is_list(obj))
goto L_iter_list; /* on tail */
else if (is_binary(obj)) {
goto handle_binary;
} else if (!is_nil(obj)) {
goto L_type_error;
}
} else if (is_binary(obj)) {
Eterm real_bin;
Uint offset;
Eterm* bptr;
Uint size;
int bitoffs;
int bitsize;
handle_binary:
size = binary_size(obj);
ERTS_GET_REAL_BIN(obj, real_bin, offset, bitoffs, bitsize);
ASSERT(bitsize == 0);
bptr = binary_val(real_bin);
if (*bptr == HEADER_PROC_BIN) {
ProcBin* pb = (ProcBin *) bptr;
if (bitoffs != 0) {
if (len < size) {
goto L_overflow;
}
erts_copy_bits(pb->bytes+offset, bitoffs, 1,
(byte *) buf, 0, 1, size*8);
csize += size;
buf += size;
len -= size;
} else if (bin_limit && size < bin_limit) {
if (len < size) {
goto L_overflow;
}
sys_memcpy(buf, pb->bytes+offset, size);
csize += size;
buf += size;
len -= size;
} else {
ErtsIOQBinary *qbin;
if (csize != 0) {
io_list_to_vec_set_vec(&iov, &binv, cbin,
cptr, csize, &vlen);
cptr = buf;
csize = 0;
}
if (pb->flags) {
erts_emasculate_writable_binary(pb);
}
if (driver)
qbin = (ErtsIOQBinary*)Binary2ErlDrvBinary(pb->val);
else
qbin = (ErtsIOQBinary*)pb->val;
io_list_to_vec_set_vec(
&iov, &binv, qbin,
pb->bytes+offset, size, &vlen);
}
} else {
ErlHeapBin* hb = (ErlHeapBin *) bptr;
if (len < size) {
goto L_overflow;
}
copy_binary_to_buffer(buf, 0,
((byte *) hb->data)+offset, bitoffs,
8*size);
csize += size;
buf += size;
len -= size;
}
} else if (!is_nil(obj)) {
goto L_type_error;
}
}
if (csize != 0) {
io_list_to_vec_set_vec(&iov, &binv, cbin, cptr, csize, &vlen);
}
DESTROY_ESTACK(s);
return vlen;
L_type_error:
DESTROY_ESTACK(s);
return -2;
L_overflow:
DESTROY_ESTACK(s);
return -1;
}
static ERTS_INLINE int
io_list_vec_count(Eterm obj, Uint *v_size,
Uint *c_size, Uint *b_size, Uint *in_clist,
Uint *p_v_size, Uint *p_c_size, Uint *p_in_clist,
Uint blimit)
{
Uint size = binary_size(obj);
Eterm real;
ERTS_DECLARE_DUMMY(Uint offset);
int bitoffs;
int bitsize;
ERTS_GET_REAL_BIN(obj, real, offset, bitoffs, bitsize);
if (bitsize != 0) return 1;
if (thing_subtag(*binary_val(real)) == REFC_BINARY_SUBTAG &&
bitoffs == 0) {
*b_size += size;
if (*b_size < size) return 2;
*in_clist = 0;
++*v_size;
/* If iov_len is smaller then Uint we split the binary into*/
/* multiple smaller (2GB) elements in the iolist.*/
*v_size += size / MAX_SYSIOVEC_IOVLEN;
if (size >= blimit) {
*p_in_clist = 0;
++*p_v_size;
} else {
*p_c_size += size;
if (!*p_in_clist) {
*p_in_clist = 1;
++*p_v_size;
}
}
} else {
*c_size += size;
if (*c_size < size) return 2;
if (!*in_clist) {
*in_clist = 1;
++*v_size;
}
*p_c_size += size;
if (!*p_in_clist) {
*p_in_clist = 1;
++*p_v_size;
}
}
return 0;
}
#define IO_LIST_VEC_COUNT(obj) \
do { \
switch (io_list_vec_count(obj, &v_size, &c_size, \
&b_size, &in_clist, \
&p_v_size, &p_c_size, &p_in_clist, \
blimit)) { \
case 1: goto L_type_error; \
case 2: goto L_overflow_error; \
default: break; \
} \
} while(0)
/*
* Returns 0 if successful and a non-zero value otherwise.
*
* Return values through pointers:
* *vsize - SysIOVec size needed for a writev
* *csize - Number of bytes not in binary (in the common binary)
* *pvsize - SysIOVec size needed if packing small binaries
* *pcsize - Number of bytes in the common binary if packing
* *total_size - Total size of iolist in bytes
*/
int
erts_ioq_iolist_vec_len(Eterm obj, int* vsize, Uint* csize,
Uint* pvsize, Uint* pcsize,
size_t* total_size, Uint blimit)
{
DECLARE_ESTACK(s);
Eterm* objp;
Uint v_size = 0;
Uint c_size = 0;
Uint b_size = 0;
Uint in_clist = 0;
Uint p_v_size = 0;
Uint p_c_size = 0;
Uint p_in_clist = 0;
size_t total;
goto L_jump_start; /* avoid a push */
while (!ESTACK_ISEMPTY(s)) {
obj = ESTACK_POP(s);
L_jump_start:
if (is_list(obj)) {
L_iter_list:
objp = list_val(obj);
obj = CAR(objp);
if (is_byte(obj)) {
c_size++;
if (c_size == 0) {
goto L_overflow_error;
}
if (!in_clist) {
in_clist = 1;
v_size++;
}
p_c_size++;
if (!p_in_clist) {
p_in_clist = 1;
p_v_size++;
}
}
else if (is_binary(obj)) {
IO_LIST_VEC_COUNT(obj);
}
else if (is_list(obj)) {
ESTACK_PUSH(s, CDR(objp));
goto L_iter_list; /* on head */
}
else if (!is_nil(obj)) {
goto L_type_error;
}
obj = CDR(objp);
if (is_list(obj))
goto L_iter_list; /* on tail */
else if (is_binary(obj)) { /* binary tail is OK */
IO_LIST_VEC_COUNT(obj);
}
else if (!is_nil(obj)) {
goto L_type_error;
}
}
else if (is_binary(obj)) {
IO_LIST_VEC_COUNT(obj);
}
else if (!is_nil(obj)) {
goto L_type_error;
}
}
total = c_size + b_size;
if (total < c_size) {
goto L_overflow_error;
}
*total_size = total;
DESTROY_ESTACK(s);
*vsize = v_size;
*csize = c_size;
*pvsize = p_v_size;
*pcsize = p_c_size;
return 0;
L_type_error:
L_overflow_error:
DESTROY_ESTACK(s);
return 1;
}
typedef struct {
Eterm result_head;
Eterm result_tail;
Eterm input_list;
UWord acc_size;
Binary *acc;
/* We yield after copying this many bytes into the accumulator (Minus
* eating a few on consing etc). Large binaries will only count to the
* extent their split (if any) resulted in a copy op. */
UWord bytereds_available;
UWord bytereds_spent;
Process *process;
ErtsEStack estack;
Eterm magic_reference;
} iol2v_state_t;
static int iol2v_state_destructor(Binary *data) {
iol2v_state_t *state = ERTS_MAGIC_BIN_UNALIGNED_DATA(data);
DESTROY_SAVED_ESTACK(&state->estack);
if (state->acc != NULL) {
erts_bin_free(state->acc);
}
return 1;
}
static void iol2v_init(iol2v_state_t *state, Process *process, Eterm input) {
state->process = process;
state->result_head = NIL;
state->result_tail = NIL;
state->input_list = input;
state->magic_reference = NIL;
state->acc_size = 0;
state->acc = NULL;
CLEAR_SAVED_ESTACK(&state->estack);
}
static Eterm iol2v_make_sub_bin(iol2v_state_t *state, Eterm bin_term,
UWord offset, UWord size) {
Uint byte_offset, bit_offset, bit_size;
ErlSubBin *sb;
Eterm orig_pb_term;
sb = (ErlSubBin*)HAlloc(state->process, ERL_SUB_BIN_SIZE);
ERTS_GET_REAL_BIN(bin_term, orig_pb_term,
byte_offset, bit_offset, bit_size);
ASSERT(bit_size == 0);
sb->thing_word = HEADER_SUB_BIN;
sb->bitoffs = bit_offset;
sb->bitsize = 0;
sb->orig = orig_pb_term;
sb->is_writable = 0;
sb->offs = byte_offset + offset;
sb->size = size;
return make_binary(sb);
}
static Eterm iol2v_promote_acc(iol2v_state_t *state) {
Eterm bin;
bin = erts_build_proc_bin(&MSO(state->process),
HAlloc(state->process, PROC_BIN_SIZE),
erts_bin_realloc(state->acc, state->acc_size));
state->acc_size = 0;
state->acc = NULL;
return bin;
}
/* Destructively enqueues a term to the result list, saving us the hassle of
* having to reverse it later. This is safe since GC is disabled and we never
* leak the unfinished term to the outside. */
static void iol2v_enqueue_result(iol2v_state_t *state, Eterm term) {
Eterm prev_tail;
Eterm *hp;
prev_tail = state->result_tail;
hp = HAlloc(state->process, 2);
state->result_tail = CONS(hp, term, NIL);
if(prev_tail != NIL) {
Eterm *prev_cell = list_val(prev_tail);
CDR(prev_cell) = state->result_tail;
} else {
state->result_head = state->result_tail;
}
state->bytereds_spent += 1;
}
#ifndef DEBUG
#define ACC_REALLOCATION_LIMIT (IOL2V_SMALL_BIN_LIMIT * 32)
#else
#define ACC_REALLOCATION_LIMIT (IOL2V_SMALL_BIN_LIMIT * 4)
#endif
static void iol2v_expand_acc(iol2v_state_t *state, UWord extra) {
UWord required_bytes, acc_alloc_size;
ERTS_CT_ASSERT(ERTS_UWORD_MAX > ACC_REALLOCATION_LIMIT / 2);
ASSERT(extra >= 1);
acc_alloc_size = state->acc != NULL ? (state->acc)->orig_size : 0;
required_bytes = state->acc_size + extra;
if (state->acc == NULL) {
UWord new_size = MAX(required_bytes, IOL2V_SMALL_BIN_LIMIT);
state->acc = erts_bin_nrml_alloc(new_size);
} else if (required_bytes > acc_alloc_size) {
Binary *prev_acc;
UWord new_size;
if (acc_alloc_size >= ACC_REALLOCATION_LIMIT) {
/* We skip reallocating once we hit a certain point; it often
* results in extra copying and we're very likely to overallocate
* on anything other than absurdly long byte/heapbin sequences. */
iol2v_enqueue_result(state, iol2v_promote_acc(state));
iol2v_expand_acc(state, extra);
return;
}
new_size = MAX(required_bytes, acc_alloc_size * 2);
prev_acc = state->acc;
state->acc = erts_bin_realloc(prev_acc, new_size);
if (prev_acc != state->acc) {
state->bytereds_spent += state->acc_size;
}
}
state->bytereds_spent += extra;
}
static int iol2v_append_byte_seq(iol2v_state_t *state, Eterm seq_start, Eterm *seq_end) {
Eterm lookahead, iterator;
Uint observed_bits;
SWord seq_length;
char *acc_data;
lookahead = seq_start;
seq_length = 0;
ASSERT(state->bytereds_available > state->bytereds_spent);
while (is_list(lookahead)) {
Eterm *cell = list_val(lookahead);
if (!is_small(CAR(cell))) {
break;
}
if (seq_length * 2 >= (state->bytereds_available - state->bytereds_spent)) {
break;
}
lookahead = CDR(cell);
seq_length += 1;
}
ASSERT(seq_length >= 1);
iol2v_expand_acc(state, seq_length);
/* Bump a few extra reductions to account for list traversal. */
state->bytereds_spent += seq_length;
acc_data = &(state->acc)->orig_bytes[state->acc_size];
state->acc_size += seq_length;
iterator = seq_start;
observed_bits = 0;
while (iterator != lookahead) {
Eterm *cell;
Uint byte;
cell = list_val(iterator);
iterator = CDR(cell);
byte = unsigned_val(CAR(cell));
observed_bits |= byte;
ASSERT(acc_data < &(state->acc)->orig_bytes[state->acc_size]);
*(acc_data++) = byte;
}
if (observed_bits > UCHAR_MAX) {
return 0;
}
ASSERT(acc_data == &(state->acc)->orig_bytes[state->acc_size]);
*seq_end = iterator;
return 1;
}
static int iol2v_append_binary(iol2v_state_t *state, Eterm bin_term) {
int is_acc_small, is_bin_small;
UWord combined_size;
UWord binary_size;
Uint byte_offset, bit_offset, bit_size;
byte *binary_data;
Eterm *parent_header;
Eterm parent_binary;
ASSERT(state->bytereds_available > state->bytereds_spent);
ERTS_GET_REAL_BIN(bin_term, parent_binary, byte_offset, bit_offset, bit_size);
parent_header = binary_val(parent_binary);
binary_size = binary_size(bin_term);
if (bit_size != 0) {
return 0;
} else if (binary_size == 0) {
state->bytereds_spent += 1;
return 1;
}
is_acc_small = state->acc_size < IOL2V_SMALL_BIN_LIMIT;
is_bin_small = binary_size < IOL2V_SMALL_BIN_LIMIT;
combined_size = binary_size + state->acc_size;
if (thing_subtag(*parent_header) == REFC_BINARY_SUBTAG) {
ProcBin *pb = (ProcBin*)parent_header;
if (pb->flags) {
erts_emasculate_writable_binary(pb);
}
binary_data = &((byte*)pb->bytes)[byte_offset];
} else {
ErlHeapBin *hb = (ErlHeapBin*)parent_header;
ASSERT(thing_subtag(*parent_header) == HEAP_BINARY_SUBTAG);
ASSERT(is_bin_small);
binary_data = &((byte*)&hb->data)[byte_offset];
}
if (!is_bin_small && (state->acc_size == 0 || !is_acc_small)) {
/* Avoid combining if we encounter an acceptably large binary while the
* accumulator is either empty or large enough to be returned on its
* own. */
if (state->acc_size != 0) {
iol2v_enqueue_result(state, iol2v_promote_acc(state));
}
iol2v_enqueue_result(state, bin_term);
} else if (is_bin_small || combined_size < (IOL2V_SMALL_BIN_LIMIT * 2)) {
/* If the candidate is small or we can't split the combination in two,
* then just copy it into the accumulator. */
iol2v_expand_acc(state, binary_size);
if (ERTS_LIKELY(bit_offset == 0)) {
sys_memcpy(&(state->acc)->orig_bytes[state->acc_size],
binary_data, binary_size);
} else {
ASSERT(binary_size <= ERTS_UWORD_MAX / 8);
erts_copy_bits(binary_data, bit_offset, 1,
(byte*)&(state->acc)->orig_bytes[state->acc_size], 0, 1,
binary_size * 8);
}
state->acc_size += binary_size;
} else {
/* Otherwise, append enough data for the accumulator to be valid, and
* then return the rest as a sub-binary. */
UWord spill = IOL2V_SMALL_BIN_LIMIT - state->acc_size;
Eterm binary_tail;
iol2v_expand_acc(state, spill);
if (ERTS_LIKELY(bit_offset == 0)) {
sys_memcpy(&(state->acc)->orig_bytes[state->acc_size],
binary_data, spill);
} else {
ASSERT(binary_size <= ERTS_UWORD_MAX / 8);
erts_copy_bits(binary_data, bit_offset, 1,
(byte*)&(state->acc)->orig_bytes[state->acc_size], 0, 1,
spill * 8);
}
state->acc_size += spill;
binary_tail = iol2v_make_sub_bin(state, bin_term, spill,
binary_size - spill);
iol2v_enqueue_result(state, iol2v_promote_acc(state));
iol2v_enqueue_result(state, binary_tail);
}
return 1;
}
static BIF_RETTYPE iol2v_yield(iol2v_state_t *state) {
if (is_nil(state->magic_reference)) {
iol2v_state_t *boxed_state;
Binary *magic_binary;
Eterm *hp;
magic_binary = erts_create_magic_binary_x(sizeof(*state),
&iol2v_state_destructor, ERTS_ALC_T_BINARY, 1);
boxed_state = ERTS_MAGIC_BIN_UNALIGNED_DATA(magic_binary);
sys_memcpy(boxed_state, state, sizeof(*state));
hp = HAlloc(boxed_state->process, ERTS_MAGIC_REF_THING_SIZE);
boxed_state->magic_reference =
erts_mk_magic_ref(&hp, &MSO(boxed_state->process), magic_binary);
state = boxed_state;
}
ERTS_BIF_YIELD1(BIF_TRAP_EXPORT(BIF_iolist_to_iovec_1),
state->process, state->magic_reference);
}
static BIF_RETTYPE iol2v_continue(iol2v_state_t *state) {
Eterm iterator;
DECLARE_ESTACK(s);
ESTACK_CHANGE_ALLOCATOR(s, ERTS_ALC_T_SAVED_ESTACK);
state->bytereds_available =
ERTS_BIF_REDS_LEFT(state->process) * IOL2V_SMALL_BIN_LIMIT;
state->bytereds_spent = 0;
if (state->estack.start) {
ESTACK_RESTORE(s, &state->estack);
}
iterator = state->input_list;
for(;;) {
if (state->bytereds_spent >= state->bytereds_available) {
ESTACK_SAVE(s, &state->estack);
state->input_list = iterator;
return iol2v_yield(state);
}
while (is_list(iterator)) {
Eterm *cell;
Eterm head;
cell = list_val(iterator);
head = CAR(cell);
if (is_binary(head)) {
if (!iol2v_append_binary(state, head)) {
goto l_badarg;
}
iterator = CDR(cell);
} else if (is_small(head)) {
Eterm seq_end;
if (!iol2v_append_byte_seq(state, iterator, &seq_end)) {
goto l_badarg;
}
iterator = seq_end;
} else if (is_list(head) || is_nil(head)) {
Eterm tail = CDR(cell);
if (!is_nil(tail)) {
ESTACK_PUSH(s, tail);
}
state->bytereds_spent += 1;
iterator = head;
} else {
goto l_badarg;
}
if (state->bytereds_spent >= state->bytereds_available) {
ESTACK_SAVE(s, &state->estack);
state->input_list = iterator;
return iol2v_yield(state);
}
}
if (is_binary(iterator)) {
if (!iol2v_append_binary(state, iterator)) {
goto l_badarg;
}
} else if (!is_nil(iterator)) {
goto l_badarg;
}
if(ESTACK_ISEMPTY(s)) {
break;
}
iterator = ESTACK_POP(s);
}
if (state->acc_size != 0) {
iol2v_enqueue_result(state, iol2v_promote_acc(state));
}
BUMP_REDS(state->process, state->bytereds_spent / IOL2V_SMALL_BIN_LIMIT);
CLEAR_SAVED_ESTACK(&state->estack);
DESTROY_ESTACK(s);
BIF_RET(state->result_head);
l_badarg:
CLEAR_SAVED_ESTACK(&state->estack);
DESTROY_ESTACK(s);
if (state->acc != NULL) {
erts_bin_free(state->acc);
state->acc = NULL;
}
BIF_ERROR(state->process, BADARG);
}
BIF_RETTYPE iolist_to_iovec_1(BIF_ALIST_1) {
BIF_RETTYPE result;
if (is_nil(BIF_ARG_1)) {
BIF_RET(NIL);
} else if (is_binary(BIF_ARG_1)) {
if (binary_bitsize(BIF_ARG_1) != 0) {
ASSERT(!(BIF_P->flags & F_DISABLE_GC));
BIF_ERROR(BIF_P, BADARG);
} else if (binary_size(BIF_ARG_1) != 0) {
Eterm *hp = HAlloc(BIF_P, 2);
BIF_RET(CONS(hp, BIF_ARG_1, NIL));
} else {
BIF_RET(NIL);
}
} else if (is_internal_magic_ref(BIF_ARG_1)) {
iol2v_state_t *state;
Binary *magic;
magic = erts_magic_ref2bin(BIF_ARG_1);
if (ERTS_MAGIC_BIN_DESTRUCTOR(magic) != &iol2v_state_destructor) {
ASSERT(!(BIF_P->flags & F_DISABLE_GC));
BIF_ERROR(BIF_P, BADARG);
}
ASSERT(BIF_P->flags & F_DISABLE_GC);
state = ERTS_MAGIC_BIN_UNALIGNED_DATA(magic);
result = iol2v_continue(state);
} else if (!is_list(BIF_ARG_1)) {
ASSERT(!(BIF_P->flags & F_DISABLE_GC));
BIF_ERROR(BIF_P, BADARG);
} else {
iol2v_state_t state;
iol2v_init(&state, BIF_P, BIF_ARG_1);
erts_set_gc_state(BIF_P, 0);
result = iol2v_continue(&state);
}
if (result != THE_NON_VALUE || BIF_P->freason != TRAP) {
erts_set_gc_state(BIF_P, 1);
}
BIF_RET(result);
}
|
b4ded41719c7e4063036ce9f9ca7aaa175935371
|
9c8044df21f177ad57a6c5235b5187b8a9cca55f
|
/Estruturas de Dados/Exemplos/Pilha Sequencial Estatica/filaComPilhasSimples.c
|
6e3c5ace6cfb021e6c88fae6faf0d96ef34d1378
|
[] |
no_license
|
AlexGalhardo/ICMC-USP
|
48f268fe60f917d5a24921c103c8a88c790634d7
|
f43efb6afea7d92b6aaa0b48516fb89705b46f24
|
refs/heads/master
| 2018-10-08T15:45:22.434741
| 2018-10-02T17:49:25
| 2018-10-02T17:49:25
| 162,185,299
| 168
| 51
| null | null | null | null |
UTF-8
|
C
| false
| false
| 1,202
|
c
|
filaComPilhasSimples.c
|
#include <stdio.h>
#include <stdlib.h>
#define tamPilha 5
typedef struct{
int topo;
int dados[tamPilha];
}PILHA;
void cria(PILHA *p){
p->topo = -1;
}
int cheio(PILHA *p){
if(p->topo == tamPilha-1)
return 1;
else return 0;
}
int vazio(PILHA *p){
if(p->topo==-1)
return 1;
else return 0;
}
int push(PILHA *p, int *dado){
if(!cheio(p)){
p->topo++;
p->dados[p->topo] = *dado;
return 0;
}
return 1;
}
int pop(PILHA *p, int *dado){
if(!vazio(p)){
*dado = p->dados[p->topo];
p->topo--;
return 0;
} else return 1;
}
int main(){
PILHA entrada;
PILHA saida;
cria(&entrada);
cria(&saida);
printf(" Vamos fazer uma fila com pilhas! \n\nEntra na pilha de entrada e sai na pilha de saida!\n\n\n");
int entra, sai, i;
for(i=0; i<5; i++){
printf("Digite o %d elemento da fila: ", i+1);
scanf("%d", &entra);
push(&entrada, &entra);
}
printf("\n\n...Tirando TODOS os dados da pilha de entrada para a pilha de saida...\n\n");
int k;
for(k=0; k < 5; k++){
pop(&entrada, &sai);
push(&saida, &sai);
}
printf("\n...Mostrando os dados em forma de fila...\n\n");
int j;
for(j=0; j < 5; j++){
pop(&saida, &sai);
printf("%d->", sai);
}
return 0;
}
|
b0f425ba72d42bc151c77412f47ecea4be9663d3
|
07bbe7a0a829cfbc9789831d981aedf36e4e94d9
|
/source/lexbor/dom/interfaces/processing_instruction.c
|
2c9143381f2cce88391a7b78e47943c621686c09
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lexbor/lexbor
|
0bf3a22898d8e295fa20cc1391e31a68502c458a
|
31e3d9d7f9032cd475d5afa788999de2d4b891dd
|
refs/heads/master
| 2023-08-31T23:25:49.903737
| 2023-08-30T08:25:12
| 2023-08-30T08:25:12
| 122,375,902
| 758
| 95
|
Apache-2.0
| 2023-08-30T08:25:13
| 2018-02-21T18:28:52
|
C
|
UTF-8
|
C
| false
| false
| 2,674
|
c
|
processing_instruction.c
|
/*
* Copyright (C) 2018-2021 Alexander Borisov
*
* Author: Alexander Borisov <borisov@lexbor.com>
*/
#include "lexbor/dom/interfaces/processing_instruction.h"
#include "lexbor/dom/interfaces/document.h"
lxb_dom_processing_instruction_t *
lxb_dom_processing_instruction_interface_create(lxb_dom_document_t *document)
{
lxb_dom_processing_instruction_t *element;
element = lexbor_mraw_calloc(document->mraw,
sizeof(lxb_dom_processing_instruction_t));
if (element == NULL) {
return NULL;
}
lxb_dom_node_t *node = lxb_dom_interface_node(element);
node->owner_document = lxb_dom_document_owner(document);
node->type = LXB_DOM_NODE_TYPE_PROCESSING_INSTRUCTION;
return element;
}
lxb_dom_processing_instruction_t *
lxb_dom_processing_instruction_interface_clone(lxb_dom_document_t *document,
const lxb_dom_processing_instruction_t *pinstr)
{
lxb_status_t status;
lxb_dom_processing_instruction_t *new;
new = lxb_dom_processing_instruction_interface_create(document);
if (new == NULL) {
return NULL;
}
status = lxb_dom_processing_instruction_copy(new, pinstr);
if (status != LXB_STATUS_OK) {
return lxb_dom_processing_instruction_interface_destroy(new);
}
return new;
}
lxb_dom_processing_instruction_t *
lxb_dom_processing_instruction_interface_destroy(lxb_dom_processing_instruction_t *processing_instruction)
{
lexbor_mraw_t *text;
lexbor_str_t target;
text = lxb_dom_interface_node(processing_instruction)->owner_document->text;
target = processing_instruction->target;
(void) lxb_dom_character_data_interface_destroy(
lxb_dom_interface_character_data(processing_instruction));
(void) lexbor_str_destroy(&target, text, false);
return NULL;
}
lxb_status_t
lxb_dom_processing_instruction_copy(lxb_dom_processing_instruction_t *dst,
const lxb_dom_processing_instruction_t *src)
{
dst->target.length = 0;
if (lexbor_str_copy(&dst->target, &src->target,
lxb_dom_interface_node(dst)->owner_document->text) == NULL)
{
return LXB_STATUS_ERROR_MEMORY_ALLOCATION;
}
return lxb_dom_character_data_interface_copy(&dst->char_data,
&src->char_data);
}
/*
* No inline functions for ABI.
*/
const lxb_char_t *
lxb_dom_processing_instruction_target_noi(lxb_dom_processing_instruction_t *pi,
size_t *len)
{
return lxb_dom_processing_instruction_target(pi, len);
}
|
41e2531aa8ecf73c44bd08f3d426cc724e362d06
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/common/enemy/Paragoomba.h
|
067bb75d4382af40d1110dfdd95c5033d4f10b4a
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 994
|
h
|
Paragoomba.h
|
#include "common.h"
#include "sprite/npc/Paragoomba.h"
#define PARAGOOMBA_DROPS \
{ \
.dropFlags = NPC_DROP_FLAG_80, \
.itemDropChance = 5, \
.itemDrops = { \
{ ITEM_MUSHROOM, 10, 0 }, \
}, \
.heartDrops = STANDARD_HEART_DROPS(2), \
.flowerDrops = STANDARD_FLOWER_DROPS(2), \
.minCoinBonus = 0, \
.maxCoinBonus = 1, \
}
#define PARAGOOMBA_ANIMS \
{ \
.idle = ANIM_Paragoomba_Idle, \
.walk = ANIM_Paragoomba_Walk, \
.run = ANIM_Paragoomba_Run, \
.chase = ANIM_Paragoomba_Run, \
.anim_4 = ANIM_Paragoomba_Idle, \
.anim_5 = ANIM_Paragoomba_Idle, \
.death = ANIM_Paragoomba_Hurt, \
.hit = ANIM_Paragoomba_Hurt, \
.anim_8 = ANIM_Paragoomba_Run, \
.anim_9 = ANIM_Paragoomba_Run, \
.anim_A = ANIM_Paragoomba_Run, \
.anim_B = ANIM_Paragoomba_Run, \
.anim_C = ANIM_Paragoomba_Run, \
.anim_D = ANIM_Paragoomba_Run, \
.anim_E = ANIM_Paragoomba_Run, \
.anim_F = ANIM_Paragoomba_Run, \
}
|
4f05be3720ec9a4ebafda19dbc42133ac07e178c
|
1db673907c7946c2ea857cc9aa8b6f7f4060e36a
|
/Module/HangulEngine/HangulEngine/Table2x1x2.c
|
625d42f26aa5bfc498bf0c31c0d2d467dfb2843d
|
[
"BSD-3-Clause"
] |
permissive
|
pdpdds/SkyOS
|
a973cd9f1b4e541ae4ac26d19df29aa3f4110db3
|
db2ce044c581fc2dfe068723fb0be2336c7f18d9
|
refs/heads/master
| 2023-07-21T15:24:46.457637
| 2023-07-17T16:32:04
| 2023-07-17T16:32:04
| 97,029,119
| 160
| 49
| null | 2023-04-30T15:33:47
| 2017-07-12T16:23:01
|
C
|
UHC
|
C
| false
| false
| 3,308
|
c
|
Table2x1x2.c
|
//-----------------------------------------------------------------------------
#include "hanlib.h"
//-----------------------------------------------------------------------------
// ①초성의 벌수 결정 : [중성종류][종성유무] */
//-----------------------------------------------------------------------------
static byte _F1_by_F2F3[22][2] = { /* 벌수는 0 ~ 7까지 8벌 */
{0, 0}, /* [ 0] */
{0, 0}, /* [ 1] ㅏ */
{0, 0}, /* [ 2] ㅐ */
{0, 0}, /* [ 3] ㅑ */
{0, 0}, /* [ 4] ㅒ */
{0, 0}, /* [ 5] ㅓ */
{0, 0}, /* [ 6] ㅔ */
{0, 0}, /* [ 7] ㅕ */
{0, 0}, /* [ 8] ㅖ */
{1, 1}, /* [ 9] ㅗ */
{0, 0}, /* [10] ㅘ */
{0, 0}, /* [11] ㅙ */
{0, 0}, /* [12] ㅚ */
{1, 1}, /* [13] ㅛ */
{1, 1}, /* [14] ㅜ */
{0, 0}, /* [15] ㅝ */
{0, 0}, /* [16] ㅞ */
{0, 0}, /* [17] ㅟ */
{1, 1}, /* [18] ㅠ */
{1, 1}, /* [19] ㅡ */
{0, 0}, /* [20] ㅢ */
{0, 0} /* [21] ㅣ */
};
//-----------------------------------------------------------------------------
// ②중성의 벌수 결정 : [초성종류][종성유뮤] */
//-----------------------------------------------------------------------------
static byte _F2_by_F1F3[20][2] = { /* 벌수는 0 ~ 3까지 4벌 */
{0, 0}, /* [ 0] */
{0, 0}, /* [ 1] ㄱ*/
{0, 0}, /* [ 2] ㄲ*/
{0, 0}, /* [ 3] ㄴ*/
{0, 0}, /* [ 4] ㄷ*/
{0, 0}, /* [ 5] ㄸ*/
{0, 0}, /* [ 6] ㄹ*/
{0, 0}, /* [ 7] ㅁ*/
{0, 0}, /* [ 8] ㅂ*/
{0, 0}, /* [ 9] ㅃ*/
{0, 0}, /* [10] ㅅ*/
{0, 0}, /* [11] ㅆ*/
{0, 0}, /* [12] ㅇ*/
{0, 0}, /* [13] ㅈ*/
{0, 0}, /* [14] ㅉ*/
{0, 0}, /* [15] ㅊ*/
{0, 0}, /* [16] ㅋ*/
{0, 0}, /* [17] ㅌ*/
{0, 0}, /* [18] ㅍ*/
{0, 0} /* [19] ㅎ*/
};
//-----------------------------------------------------------------------------
// ③종성의 벌수 결정 : [중성종류] */
//-----------------------------------------------------------------------------
static byte _F3_by_F2[22] = { /* 벌수는 0 ~ 3까지 4벌 */
0, /* [ 0] */
1, /* [ 1] ㅏ */
1, /* [ 2] ㅐ */
1, /* [ 3] ㅑ */
1, /* [ 4] ㅒ */
1, /* [ 5] ㅓ */
1, /* [ 6] ㅔ */
1, /* [ 7] ㅕ */
1, /* [ 8] ㅖ */
1, /* [ 9] ㅗ */
0, /* [10] ㅘ */
1, /* [11] ㅙ */
1, /* [12] ㅚ */
0, /* [13] ㅛ */
0, /* [14] ㅜ */
1, /* [15] ㅝ */
1, /* [16] ㅞ */
1, /* [17] ㅟ */
0, /* [18] ㅠ */
0, /* [19] ㅡ */
1, /* [20] ㅢ */
1 /* [21] ㅣ */
};
//-----------------------------------------------------------------------------
/* ①초성의 벌수 결정 : [중성종류][종성유무] */
/* ②중성의 벌수 결정 : [초성종류][종성유뮤] */
/* ③종성의 벌수 결정 : [중성종류] */
byte *_F1B_2x1x2 = &_F1_by_F2F3[0][false];
byte *_F2B_2x1x2 = &_F2_by_F1F3[0][false];
byte *_F3B_2x1x2 = &_F3_by_F2[0];
//-----------------------------------------------------------------------------
|
d6fd51888e9e62c3f294f1b954fc7f283def564b
|
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
|
/deps/abc/src/map/if/ifLibBox.c
|
443dbd3f42ed4ec3f498a0db1892ca3880f19d75
|
[
"MIT-Modern-Variant",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
emsec/hal
|
70ad2921739967d914dd458984bd7d6d497d3b0a
|
e4fae37bec9168a61100eacfda37a1f291b4d0be
|
refs/heads/master
| 2023-09-02T20:27:32.909426
| 2023-09-01T13:03:24
| 2023-09-01T13:03:24
| 169,076,171
| 510
| 72
|
MIT
| 2023-09-01T13:03:26
| 2019-02-04T12:37:20
|
C++
|
UTF-8
|
C
| false
| false
| 11,284
|
c
|
ifLibBox.c
|
/**CFile****************************************************************
FileName [ifLibBox.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [FPGA mapping based on priority cuts.]
Synopsis [Box library.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - November 21, 2006.]
Revision [$Id: ifLibBox.c,v 1.00 2006/11/21 00:00:00 alanmi Exp $]
***********************************************************************/
#include "if.h"
#include "misc/extra/extra.h"
#include "base/main/main.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
#define If_LibBoxForEachBox( p, pBox, i ) \
Vec_PtrForEachEntry( If_Box_t *, p->vBoxes, pBox, i ) if ( pBox == NULL ) {} else
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
If_Box_t * If_BoxStart( char * pName, int Id, int nPis, int nPos, int fSeq, int fBlack, int fOuter )
{
If_Box_t * p;
p = ABC_CALLOC( If_Box_t, 1 );
p->pName = pName; // consumes memory
p->Id = Id;
p->fSeq = (char)fSeq;
p->fBlack = (char)fBlack;
p->fOuter = (char)fOuter;
p->nPis = nPis;
p->nPos = nPos;
p->pDelays = ABC_CALLOC( int, nPis * nPos );
return p;
}
If_Box_t * If_BoxDup( If_Box_t * p )
{
If_Box_t * pNew = NULL;
return pNew;
}
void If_BoxFree( If_Box_t * p )
{
ABC_FREE( p->pDelays );
ABC_FREE( p->pName );
ABC_FREE( p );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
If_LibBox_t * If_LibBoxStart()
{
If_LibBox_t * p;
p = ABC_CALLOC( If_LibBox_t, 1 );
p->vBoxes = Vec_PtrAlloc( 100 );
return p;
}
If_LibBox_t * If_LibBoxDup( If_Box_t * p )
{
If_LibBox_t * pNew = NULL;
return pNew;
}
void If_LibBoxFree( If_LibBox_t * p )
{
If_Box_t * pBox;
int i;
if ( p == NULL )
return;
If_LibBoxForEachBox( p, pBox, i )
If_BoxFree( pBox );
Vec_PtrFree( p->vBoxes );
ABC_FREE( p );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
If_Box_t * If_LibBoxReadBox( If_LibBox_t * p, int Id )
{
return (If_Box_t *)Vec_PtrEntry( p->vBoxes, Id );
}
If_Box_t * If_LibBoxFindBox( If_LibBox_t * p, char * pName )
{
If_Box_t * pBox;
int i;
if ( p == NULL )
return NULL;
If_LibBoxForEachBox( p, pBox, i )
if ( !strcmp(pBox->pName, pName) )
return pBox;
return NULL;
}
void If_LibBoxAdd( If_LibBox_t * p, If_Box_t * pBox )
{
if ( pBox->Id >= Vec_PtrSize(p->vBoxes) )
Vec_PtrFillExtra( p->vBoxes, 2 * pBox->Id + 10, NULL );
assert( Vec_PtrEntry( p->vBoxes, pBox->Id ) == NULL );
Vec_PtrWriteEntry( p->vBoxes, pBox->Id, pBox );
p->nBoxes++;
}
int If_LibBoxNum( If_LibBox_t * p )
{
return p->nBoxes;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
If_LibBox_t * If_LibBoxRead2( char * pFileName )
{
int nSize = 100000;
char * pBuffer;
FILE * pFile;
If_LibBox_t * p = NULL;
If_Box_t * pBox = NULL;
char * pToken, * pName;
int fSeq, fBlack, fOuter;
int i, Id, nPis, nPos;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Cannot open file \"%s\".\n", pFileName );
return NULL;
}
// read lines
nPis = nPos = 0;
pBuffer = ABC_ALLOC( char, nSize );
while ( fgets( pBuffer, nSize, pFile ) )
{
pToken = strtok( pBuffer, " \n\r\t" );
if ( pToken == NULL )
continue;
if ( pToken[0] == '.' )
{
if ( !strcmp(pToken, ".box") )
{
// save ID
pToken = strtok( NULL, " \n\r\t" );
Id = atoi( pToken );
// save name
pToken = strtok( NULL, " \n\r\t" );
pName = Abc_UtilStrsav(pToken);
// save PIs
pToken = strtok( NULL, " \n\r\t" );
nPis = atoi( pToken );
// save POs
pToken = strtok( NULL, " \n\r\t" );
nPos = atoi( pToken );
// save attributes
fSeq = fBlack = fOuter = 0;
pToken = strtok( NULL, " \n\r\t" );
while ( pToken )
{
if ( !strcmp(pToken, "seq") )
fSeq = 1;
else if ( !strcmp(pToken, "black") )
fBlack = 1;
else if ( !strcmp(pToken, "outer") )
fOuter = 1;
else assert( !strcmp(pToken, "comb") || !strcmp(pToken, "white") || !strcmp(pToken, "inner") );
pToken = strtok( NULL, " \n\r\t" );
}
// create library
if ( p == NULL )
p = If_LibBoxStart();
// create box
pBox = If_BoxStart( pName, Id, nPis, nPos, fSeq, fBlack, fOuter );
If_LibBoxAdd( p, pBox );
}
continue;
}
// read the table
assert( nPis > 0 && nPos > 0 );
for ( i = 0; i < nPis * nPos; i++ )
{
while ( pToken == NULL )
{
if ( fgets( pBuffer, nSize, pFile ) == NULL )
{ printf( "The table does not have enough entries.\n" ); fflush(stdout); assert( 0 ); }
pToken = strtok( pBuffer, " \n\r\t" );
}
pBox->pDelays[i] = (pToken[0] == '-') ? -1 : atoi(pToken);
pToken = strtok( NULL, " \n\r\t" );
}
pBox = NULL;
}
ABC_FREE( pBuffer );
fclose( pFile );
return p;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * If_LibBoxGetToken( FILE * pFile )
{
static char pBuffer[1000];
int c; char * pTemp = pBuffer;
while ( (c = fgetc(pFile)) != EOF )
{
if ( c == '#' )
{
while ( (c = fgetc(pFile)) != EOF )
if ( c == '\n' )
break;
}
if ( c == ' ' || c == '\t' || c == '\n' || c == '\r' )
{
if ( pTemp > pBuffer )
break;
continue;
}
*pTemp++ = c;
}
*pTemp = 0;
return pTemp > pBuffer ? pBuffer : NULL;
}
If_LibBox_t * If_LibBoxRead( char * pFileName )
{
FILE * pFile;
If_LibBox_t * p;
If_Box_t * pBox;
char * pToken, * pName;
int i, Id, fBlack, nPis, nPos;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Cannot open file \"%s\".\n", pFileName );
return NULL;
}
// get the library name
pToken = If_LibBoxGetToken( pFile );
if ( pToken == NULL )
{
fclose( pFile );
printf( "Cannot read library name from file \"%s\".\n", pFileName );
return NULL;
}
if ( pToken[0] == '.' )
{
fclose( pFile );
printf( "Wrong box format. Please try \"read_box -e\".\n" );
return NULL;
}
// create library
p = If_LibBoxStart();
while ( pToken )
{
// save name
pName = Abc_UtilStrsav(pToken);
// save ID
pToken = If_LibBoxGetToken( pFile );
Id = atoi( pToken );
// save white/black
pToken = If_LibBoxGetToken( pFile );
fBlack = !atoi( pToken );
// save PIs
pToken = If_LibBoxGetToken( pFile );
nPis = atoi( pToken );
// save POs
pToken = If_LibBoxGetToken( pFile );
nPos = atoi( pToken );
// create box
pBox = If_BoxStart( pName, Id, nPis, nPos, 0, fBlack, 0 );
If_LibBoxAdd( p, pBox );
// read the table
for ( i = 0; i < nPis * nPos; i++ )
{
pToken = If_LibBoxGetToken( pFile );
pBox->pDelays[i] = (pToken[0] == '-') ? -ABC_INFINITY : atoi(pToken);
}
// extract next name
pToken = If_LibBoxGetToken( pFile );
}
fclose( pFile );
return p;
}
void If_LibBoxPrint( FILE * pFile, If_LibBox_t * p )
{
If_Box_t * pBox;
int i, j, k;
fprintf( pFile, "# Box library written by ABC on %s.\n", Extra_TimeStamp() );
fprintf( pFile, "# <Name> <ID> <Type> <I> <O>\n" );
If_LibBoxForEachBox( p, pBox, i )
{
fprintf( pFile, "%s %d %d %d %d\n", pBox->pName, pBox->Id, !pBox->fBlack, pBox->nPis, pBox->nPos );
for ( j = 0; j < pBox->nPos; j++, printf("\n") )
for ( k = 0; k < pBox->nPis; k++ )
if ( pBox->pDelays[j * pBox->nPis + k] == -ABC_INFINITY )
fprintf( pFile, " - " );
else
fprintf( pFile, "%5d ", pBox->pDelays[j * pBox->nPis + k] );
}
}
void If_LibBoxWrite( char * pFileName, If_LibBox_t * p )
{
FILE * pFile;
pFile = fopen( pFileName, "wb" );
if ( pFile == NULL )
{
printf( "Cannot open file \"%s\".\n", pFileName );
return;
}
If_LibBoxPrint( pFile, p );
fclose( pFile );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int If_LibBoxLoad( char * pFileName )
{
FILE * pFile;
If_LibBox_t * pLib;
char * pFileNameOther;
// check if library can be read
pFileNameOther = Extra_FileNameGenericAppend( pFileName, ".cdl" );
pFile = fopen( pFileNameOther, "r" );
if ( pFile == NULL )
return 0;
fclose( pFile );
// read library
pLib = If_LibBoxRead2( pFileNameOther );
// replace the current library
If_LibBoxFree( (If_LibBox_t *)Abc_FrameReadLibBox() );
Abc_FrameSetLibBox( pLib );
return 1;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
64cb4dff6de258a52af364aa3bdad74c75bb56a6
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/sound/isa/es1688/es1688.c
|
102874a703d4cc8c53e98db88728215ef60cbec6
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 10,359
|
c
|
es1688.c
|
/*
* Driver for generic ESS AudioDrive ESx688 soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/isapnp.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/module.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/es1688.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#define CRD_NAME "Generic ESS ES1688/ES688 AudioDrive"
#define DEV_NAME "es1688"
MODULE_DESCRIPTION(CRD_NAME);
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ESS,ES688 PnP AudioDrive,pnp:ESS0100},"
"{ESS,ES1688 PnP AudioDrive,pnp:ESS0102},"
"{ESS,ES688 AudioDrive,pnp:ESS6881},"
"{ESS,ES1688 AudioDrive,pnp:ESS1681}}");
MODULE_ALIAS("snd_es968");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
#ifdef CONFIG_PNP
static bool isapnp[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP;
#endif
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* Usually 0x388 */
static long mpu_port[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = -1};
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int dma8[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard.");
module_param_array(enable, bool, NULL, 0444);
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard.");
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for " CRD_NAME " driver.");
module_param_array(irq, int, NULL, 0444);
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for ES1688 driver.");
MODULE_PARM_DESC(irq, "IRQ # for " CRD_NAME " driver.");
module_param_array(mpu_irq, int, NULL, 0444);
MODULE_PARM_DESC(mpu_irq, "MPU-401 IRQ # for " CRD_NAME " driver.");
module_param_array(dma8, int, NULL, 0444);
MODULE_PARM_DESC(dma8, "8-bit DMA # for " CRD_NAME " driver.");
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static int snd_es1688_match(struct device *dev, unsigned int n)
{
return enable[n] && !is_isapnp_selected(n);
}
static int snd_es1688_legacy_create(struct snd_card *card,
struct device *dev, unsigned int n)
{
struct snd_es1688 *chip = card->private_data;
static long possible_ports[] = {0x220, 0x240, 0x260};
static int possible_irqs[] = {5, 9, 10, 7, -1};
static int possible_dmas[] = {1, 3, 0, -1};
int i, error;
if (irq[n] == SNDRV_AUTO_IRQ) {
irq[n] = snd_legacy_find_free_irq(possible_irqs);
if (irq[n] < 0) {
dev_err(dev, "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma8[n] == SNDRV_AUTO_DMA) {
dma8[n] = snd_legacy_find_free_dma(possible_dmas);
if (dma8[n] < 0) {
dev_err(dev, "unable to find a free DMA\n");
return -EBUSY;
}
}
if (port[n] != SNDRV_AUTO_PORT)
return snd_es1688_create(card, chip, port[n], mpu_port[n],
irq[n], mpu_irq[n], dma8[n], ES1688_HW_AUTO);
i = 0;
do {
port[n] = possible_ports[i];
error = snd_es1688_create(card, chip, port[n], mpu_port[n],
irq[n], mpu_irq[n], dma8[n], ES1688_HW_AUTO);
} while (error < 0 && ++i < ARRAY_SIZE(possible_ports));
return error;
}
static int snd_es1688_probe(struct snd_card *card, unsigned int n)
{
struct snd_es1688 *chip = card->private_data;
struct snd_opl3 *opl3;
struct snd_pcm *pcm;
int error;
error = snd_es1688_pcm(card, chip, 0, &pcm);
if (error < 0)
return error;
error = snd_es1688_mixer(card, chip);
if (error < 0)
return error;
strlcpy(card->driver, "ES1688", sizeof(card->driver));
strlcpy(card->shortname, pcm->name, sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s at 0x%lx, irq %i, dma %i", pcm->name, chip->port,
chip->irq, chip->dma8);
if (fm_port[n] == SNDRV_AUTO_PORT)
fm_port[n] = port[n]; /* share the same port */
if (fm_port[n] > 0) {
if (snd_opl3_create(card, fm_port[n], fm_port[n] + 2,
OPL3_HW_OPL3, 0, &opl3) < 0)
dev_warn(card->dev,
"opl3 not detected at 0x%lx\n", fm_port[n]);
else {
error = snd_opl3_hwdep_new(opl3, 0, 1, NULL);
if (error < 0)
return error;
}
}
if (mpu_irq[n] >= 0 && mpu_irq[n] != SNDRV_AUTO_IRQ &&
chip->mpu_port > 0) {
error = snd_mpu401_uart_new(card, 0, MPU401_HW_ES1688,
chip->mpu_port, 0,
mpu_irq[n], NULL);
if (error < 0)
return error;
}
return snd_card_register(card);
}
static int snd_es1688_isa_probe(struct device *dev, unsigned int n)
{
struct snd_card *card;
int error;
error = snd_card_create(index[n], id[n], THIS_MODULE,
sizeof(struct snd_es1688), &card);
if (error < 0)
return error;
error = snd_es1688_legacy_create(card, dev, n);
if (error < 0)
goto out;
snd_card_set_dev(card, dev);
error = snd_es1688_probe(card, n);
if (error < 0)
goto out;
dev_set_drvdata(dev, card);
return 0;
out:
snd_card_free(card);
return error;
}
static int snd_es1688_isa_remove(struct device *dev, unsigned int n)
{
snd_card_free(dev_get_drvdata(dev));
dev_set_drvdata(dev, NULL);
return 0;
}
static struct isa_driver snd_es1688_driver = {
.match = snd_es1688_match,
.probe = snd_es1688_isa_probe,
.remove = snd_es1688_isa_remove,
#if 0 /* FIXME */
.suspend = snd_es1688_suspend,
.resume = snd_es1688_resume,
#endif
.driver = {
.name = DEV_NAME
}
};
static int snd_es968_pnp_is_probed;
#ifdef CONFIG_PNP
static int snd_card_es968_pnp(struct snd_card *card, unsigned int n,
struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
struct snd_es1688 *chip = card->private_data;
struct pnp_dev *pdev;
int error;
pdev = pnp_request_card_device(pcard, pid->devs[0].id, NULL);
if (pdev == NULL)
return -ENODEV;
error = pnp_activate_dev(pdev);
if (error < 0) {
snd_printk(KERN_ERR "ES968 pnp configure failure\n");
return error;
}
port[n] = pnp_port_start(pdev, 0);
dma8[n] = pnp_dma(pdev, 0);
irq[n] = pnp_irq(pdev, 0);
return snd_es1688_create(card, chip, port[n], mpu_port[n], irq[n],
mpu_irq[n], dma8[n], ES1688_HW_AUTO);
}
static int snd_es968_pnp_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
struct snd_card *card;
static unsigned int dev;
int error;
struct snd_es1688 *chip;
if (snd_es968_pnp_is_probed)
return -EBUSY;
for ( ; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev == SNDRV_CARDS)
return -ENODEV;
error = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_es1688), &card);
if (error < 0)
return error;
chip = card->private_data;
error = snd_card_es968_pnp(card, dev, pcard, pid);
if (error < 0) {
snd_card_free(card);
return error;
}
snd_card_set_dev(card, &pcard->card->dev);
error = snd_es1688_probe(card, dev);
if (error < 0)
return error;
pnp_set_card_drvdata(pcard, card);
snd_es968_pnp_is_probed = 1;
return 0;
}
static void snd_es968_pnp_remove(struct pnp_card_link *pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
snd_es968_pnp_is_probed = 0;
}
#ifdef CONFIG_PM
static int snd_es968_pnp_suspend(struct pnp_card_link *pcard,
pm_message_t state)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_es1688 *chip = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
return 0;
}
static int snd_es968_pnp_resume(struct pnp_card_link *pcard)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_es1688 *chip = card->private_data;
snd_es1688_reset(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static struct pnp_card_device_id snd_es968_pnpids[] = {
{ .id = "ESS0968", .devs = { { "@@@0968" }, } },
{ .id = "ESS0968", .devs = { { "ESS0968" }, } },
{ .id = "", } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_es968_pnpids);
static struct pnp_card_driver es968_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = DEV_NAME " PnP",
.id_table = snd_es968_pnpids,
.probe = snd_es968_pnp_detect,
.remove = snd_es968_pnp_remove,
#ifdef CONFIG_PM
.suspend = snd_es968_pnp_suspend,
.resume = snd_es968_pnp_resume,
#endif
};
#endif
static int __init alsa_card_es1688_init(void)
{
#ifdef CONFIG_PNP
pnp_register_card_driver(&es968_pnpc_driver);
if (snd_es968_pnp_is_probed)
return 0;
pnp_unregister_card_driver(&es968_pnpc_driver);
#endif
return isa_register_driver(&snd_es1688_driver, SNDRV_CARDS);
}
static void __exit alsa_card_es1688_exit(void)
{
if (!snd_es968_pnp_is_probed) {
isa_unregister_driver(&snd_es1688_driver);
return;
}
#ifdef CONFIG_PNP
pnp_unregister_card_driver(&es968_pnpc_driver);
#endif
}
module_init(alsa_card_es1688_init);
module_exit(alsa_card_es1688_exit);
|
095ada9c1060bf64a247da79c335eeda532d490f
|
1994b15441624ad5b7f484f007083986cd846b13
|
/cyclone_objects/binaries/audio/deltaclip.c
|
e23c9334d73759a5bcab9905ee0fa5ee7ae3c09d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
porres/pd-cyclone
|
7e7912d5d1a7ebe00e29a643c17ebcb6f50b3747
|
dfb7b8ad4dddde3ff3320d8d32baefbebdff3cf9
|
refs/heads/master
| 2023-09-03T20:28:51.715146
| 2023-08-30T00:03:45
| 2023-08-30T00:03:45
| 51,787,562
| 186
| 26
|
BSD-3-Clause
| 2023-08-30T00:03:46
| 2016-02-15T21:38:34
|
C
|
UTF-8
|
C
| false
| false
| 2,811
|
c
|
deltaclip.c
|
/* Copyright (c) 2002-2003 krzYszcz and others.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution. */
// updated 2016 by Derek Kwan and 2021 by porres
#include "m_pd.h"
#include <common/api.h>
typedef struct _deltaclip{
t_object x_obj;
t_float x_last;
t_inlet *x_lolet;
t_inlet *x_hilet;
}t_deltaclip;
static t_class *deltaclip_class;
static t_int *deltaclip_perform(t_int *w){
t_deltaclip *x = (t_deltaclip *)(w[1]);
int nblock = (int)(w[2]);
t_float *in1 = (t_float *)(w[3]);
t_float *in2 = (t_float *)(w[4]);
t_float *in3 = (t_float *)(w[5]);
t_float *out = (t_float *)(w[6]);
t_float last = x->x_last;
while(nblock--){
float f = *in1++;
float delta = f - last;
float lo = *in2++;
if(lo > 0)
lo = 0;
float hi = *in3++;
if(hi < 0)
hi = 0;
if(delta < lo)
f = last + lo;
else if (delta > hi)
f = last + hi;
*out++ = last = f;
}
x->x_last = last;
return(w+7);
}
static void deltaclip_dsp(t_deltaclip *x, t_signal **sp){
dsp_add(deltaclip_perform, 6, x, sp[0]->s_n,
sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec);
}
static void deltaclip_reset(t_deltaclip *x){
x->x_last = 0;
}
static void *deltaclip_free(t_deltaclip *x){
inlet_free(x->x_lolet);
inlet_free(x->x_hilet);
return(void *)x;
}
static void *deltaclip_new(t_symbol *s, int argc, t_atom *argv){
t_deltaclip *x = (t_deltaclip *)pd_new(deltaclip_class);
t_float cliplo = 0, cliphi = 0;
int argnum = 0;
while(argc > 0){
if(argv -> a_type == A_FLOAT){
t_float argval = atom_getfloatarg(0,argc,argv);
switch(argnum){
case 0:
cliplo = argval;
break;
case 1:
cliphi = argval;
break;
default:
break;
};
argc--;
argv++;
argnum++;
}
else{
goto errstate;
};
};
x->x_lolet = inlet_new((t_object *)x, (t_pd *)x, &s_signal, &s_signal);
pd_float((t_pd *)x->x_lolet, cliplo);
x->x_hilet = inlet_new((t_object *)x, (t_pd *)x, &s_signal, &s_signal);
pd_float((t_pd *)x->x_hilet, cliphi);
outlet_new((t_object *)x, &s_signal);
x->x_last = 0;
return(x);
errstate:
pd_error(x, "deltaclip~: improper args");
return(NULL);
}
CYCLONE_OBJ_API void deltaclip_tilde_setup(void){
deltaclip_class = class_new(gensym("deltaclip~"), (t_newmethod)deltaclip_new,
(t_method)deltaclip_free, sizeof(t_deltaclip), 0, A_GIMME, 0);
class_addmethod(deltaclip_class, nullfn, gensym("signal"), 0);
class_addmethod(deltaclip_class, (t_method)deltaclip_dsp, gensym("dsp"), A_CANT, 0);
class_addmethod(deltaclip_class, (t_method)deltaclip_reset, gensym("reset"), 0);
}
|
160c93ac50c69a341d095283a9a34eae41431eae
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/wayland-protocols/gtk/gdk/broadway/gdkprivate-broadway.h
|
78cab2844028b3e70d026f4d063a4a9b73931836
|
[
"LGPL-2.0-only",
"Apache-2.0",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 6,747
|
h
|
gdkprivate-broadway.h
|
/* GDK - The GIMP Drawing Kit
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* 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/>.
*/
/*
* Modified by the GTK+ Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GTK+ Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GTK+ at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* Private uninstalled header defining things local to X windowing code
*/
#ifndef __GDK_PRIVATE_BROADWAY_H__
#define __GDK_PRIVATE_BROADWAY_H__
#include <gdk/gdkcursor.h>
#include <gdk/gdkinternals.h>
#include "gdksurface-broadway.h"
#include "gdkdisplay-broadway.h"
#include "gdkdrawcontext-broadway.h"
#include "gdkbroadwaycursor.h"
#include "gdkbroadwaysurface.h"
guint32 gdk_broadway_display_ensure_texture (GdkDisplay *display,
GdkTexture *texture);
void gdk_broadway_display_flush_in_idle (GdkDisplay *display);
void gdk_broadway_surface_set_nodes (GdkSurface *surface,
GArray *nodes,
GPtrArray *node_textures);
GdkDrag * _gdk_broadway_surface_drag_begin (GdkSurface *surface,
GdkDevice *device,
GdkContentProvider *content,
GdkDragAction actions,
double dx,
double dy);
void _gdk_broadway_surface_translate (GdkSurface *surface,
cairo_region_t *area,
int dx,
int dy);
gboolean _gdk_broadway_moveresize_handle_event (GdkDisplay *display,
BroadwayInputMsg *msg);
gboolean _gdk_broadway_moveresize_configure_done (GdkDisplay *display,
GdkSurface *surface);
void _gdk_broadway_roundtrip_notify (GdkSurface *surface,
guint32 tag,
gboolean local_reply);
void _gdk_broadway_surface_grab_check_destroy (GdkSurface *surface);
void _gdk_broadway_surface_grab_check_unmap (GdkSurface *surface,
gulong serial);
void gdk_broadway_surface_move_resize (GdkSurface *surface,
int x,
int y,
int width,
int height);
void _gdk_keymap_keys_changed (GdkDisplay *display);
int _gdk_broadway_get_group_for_state (GdkDisplay *display,
GdkModifierType state);
void _gdk_keymap_add_virtual_modifiers_compat (GdkKeymap *keymap,
GdkModifierType *modifiers);
gboolean _gdk_keymap_key_is_modifier (GdkKeymap *keymap,
guint keycode);
void _gdk_broadway_display_size_changed (GdkDisplay *display,
BroadwayInputScreenResizeNotify *msg);
void _gdk_broadway_events_got_input (GdkDisplay *display,
BroadwayInputMsg *message);
void _gdk_broadway_display_init_root_window (GdkDisplay *display);
GdkDisplay * _gdk_broadway_display_open (const char *display_name);
void _gdk_broadway_display_queue_events (GdkDisplay *display);
GdkCursor*_gdk_broadway_display_get_cursor_for_name (GdkDisplay *display,
const char *name);
GdkCursor *_gdk_broadway_display_get_cursor_for_texture (GdkDisplay *display,
GdkTexture *texture,
int x,
int y);
gboolean _gdk_broadway_display_supports_cursor_alpha (GdkDisplay *display);
gboolean _gdk_broadway_display_supports_cursor_color (GdkDisplay *display);
void _gdk_broadway_display_get_default_cursor_size (GdkDisplay *display,
guint *width,
guint *height);
void _gdk_broadway_display_get_maximal_cursor_size (GdkDisplay *display,
guint *width,
guint *height);
GdkSurface * _gdk_broadway_display_create_surface (GdkDisplay *display,
GdkSurfaceType surface_type,
GdkSurface *parent,
int x,
int y,
int width,
int height);
GdkKeymap* _gdk_broadway_display_get_keymap (GdkDisplay *display);
void _gdk_broadway_display_consume_all_input (GdkDisplay *display);
BroadwayInputMsg * _gdk_broadway_display_block_for_input (GdkDisplay *display,
char op,
guint32 serial,
gboolean remove);
/* Surface methods - testing */
void _gdk_broadway_surface_resize_surface (GdkSurface *surface);
void _gdk_broadway_cursor_update_theme (GdkCursor *cursor);
void _gdk_broadway_cursor_display_finalize (GdkDisplay *display);
#endif /* __GDK_PRIVATE_BROADWAY_H__ */
|
79ec7727f2bf8d3bf2127775c80410d725c3c978
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cbmc/struct17/main.c
|
892cef000b9d37766031c83e6aeb935284331520
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 179
|
c
|
main.c
|
#include <assert.h>
struct famt
{
char x;
char vl[];
};
extern struct famt vls;
struct famt vls = {'a', {1, 2, 3, 4}};
int main()
{
assert(vls.vl[3] == 4);
return 0;
}
|
3b78c961dbeecfcca332ceab44d0cba73514c845
|
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
|
/common/sgx/verifier.c
|
ae4e4235789705f26d6e8a6224d3f40bf844b024
|
[
"MIT"
] |
permissive
|
openenclave/openenclave
|
54a38e12d9aa73357d9f438a07cd8c07ffe5e6df
|
cdeb95c1ec163117de409295333b6b2702013e08
|
refs/heads/master
| 2023-08-14T16:43:32.049533
| 2023-07-21T15:58:54
| 2023-07-21T15:58:54
| 101,804,230
| 800
| 372
|
MIT
| 2023-09-12T20:26:02
| 2017-08-29T20:31:38
|
C
|
UTF-8
|
C
| false
| false
| 36,960
|
c
|
verifier.c
|
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#include <openenclave/attestation/sgx/evidence.h>
#include <openenclave/attestation/verifier.h>
#include <openenclave/bits/sgx/sgxtypes.h>
#include <openenclave/internal/hexdump.h>
#include <openenclave/internal/plugin.h>
#include <openenclave/internal/raise.h>
#include <openenclave/internal/report.h>
#include <openenclave/internal/safemath.h>
#include <openenclave/internal/sgx/plugin.h>
#include "../attest_plugin.h"
#include "../common.h"
#include "endorsements.h"
#include "quote.h"
#include "report.h"
#include "tcbinfo.h"
#if !defined(OE_BUILD_ENCLAVE)
#include "../../host/sgx/sgxquoteprovider.h"
#endif
#ifdef OE_BUILD_ENCLAVE
#include <openenclave/internal/safecrt.h>
#include <openenclave/internal/thread.h>
#include "../../enclave/core/sgx/report.h"
#include "../enclave/sgx/report.h"
#else
#include "../../host/hostthread.h"
#include "../../host/sgx/quote.h"
typedef oe_mutex oe_mutex_t;
#define OE_MUTEX_INITIALIZER OE_H_MUTEX_INITIALIZER
#endif
static const oe_uuid_t _uuid_sgx_local_attestation = {
OE_FORMAT_UUID_SGX_LOCAL_ATTESTATION};
static const oe_uuid_t _uuid_sgx_ecdsa = {OE_FORMAT_UUID_SGX_ECDSA};
static const oe_uuid_t _uuid_legacy_report_remote = {
OE_FORMAT_UUID_LEGACY_REPORT_REMOTE};
static const oe_uuid_t _uuid_raw_sgx_quote_ecdsa = {
OE_FORMAT_UUID_RAW_SGX_QUOTE_ECDSA};
static oe_result_t _on_register(
oe_attestation_role_t* context,
const void* configuration_data,
size_t configuration_data_size)
{
OE_UNUSED(context);
OE_UNUSED(configuration_data);
OE_UNUSED(configuration_data_size);
#if defined(OE_BUILD_ENCLAVE)
return OE_OK;
#else
return oe_initialize_quote_provider();
#endif
}
static oe_result_t _on_unregister(oe_attestation_role_t* context)
{
OE_UNUSED(context);
return OE_OK;
}
static void _free_claim(oe_claim_t* claim)
{
oe_free(claim->name);
oe_free(claim->value);
}
oe_result_t oe_sgx_free_claims_list(
oe_verifier_t* context,
oe_claim_t* claims,
size_t claims_length)
{
OE_UNUSED(context);
if (!claims)
return OE_OK;
for (size_t i = 0; i < claims_length; i++)
_free_claim(&claims[i]);
oe_free(claims);
return OE_OK;
}
static oe_result_t _get_input_time(
const oe_policy_t* policies,
size_t policies_size,
oe_datetime_t** time)
{
if (!policies)
{
*time = NULL;
return OE_OK;
}
for (size_t i = 0; i < policies_size; i++)
{
if (policies[i].type == OE_POLICY_ENDORSEMENTS_TIME)
{
if (policies[i].policy_size != sizeof(**time))
return OE_INVALID_PARAMETER;
*time = (oe_datetime_t*)policies[i].policy;
return OE_OK;
}
}
// Time not found, which is fine since it's an optional parameter.
*time = NULL;
return OE_OK;
}
static oe_result_t _verify_local_report(
const uint8_t* report_body,
size_t report_body_size)
{
// Do a normal report verification on the enclave side.
// Local report verification is unsupported for host side.
#ifdef OE_BUILD_ENCLAVE
return oe_verify_raw_sgx_report(report_body, report_body_size);
#else
OE_UNUSED(report_body);
OE_UNUSED(report_body_size);
return OE_UNSUPPORTED;
#endif
}
// If evidence contains custom claims, verify the custom claims' hash;
// otherwise return SGX report data as a claim field.
static oe_result_t _process_sgx_report_data(
const sgx_evidence_format_type_t format_type,
const uint8_t* report_body, // Raw SGX quote or report
const uint8_t* custom_claims_buffer,
size_t custom_claims_buffer_size,
sgx_report_data_t* report_data_out)
{
oe_result_t result = OE_UNEXPECTED;
if (!report_body)
OE_RAISE(OE_INVALID_PARAMETER);
// Evidence generated by oe_get_evidence() has its custom claims buffer
// hashed for the SGX report data.
if (format_type == SGX_FORMAT_TYPE_LOCAL ||
format_type == SGX_FORMAT_TYPE_REMOTE)
{
// Verify custom claims
OE_SHA256 hash;
uint8_t* report_data;
OE_UNUSED(report_data_out);
OE_CHECK(oe_sgx_hash_custom_claims_buffer(
custom_claims_buffer, custom_claims_buffer_size, &hash));
if (format_type == SGX_FORMAT_TYPE_REMOTE)
report_data =
(uint8_t*)&((sgx_quote_t*)report_body)->report_body.report_data;
else
report_data =
(uint8_t*)&((sgx_report_t*)report_body)->body.report_data;
result = !memcmp(report_data, &hash, OE_SHA256_SIZE)
? OE_OK
: OE_QUOTE_HASH_MISMATCH;
}
else // SGX_FORMAT_TYPE_LEGACY_REPORT or SGX_FORMAT_TYPE_RAW_QUOTE
{
// These types of evidence does not contain custom claims buffer.
// SGX report data is returned.
OE_UNUSED(custom_claims_buffer);
OE_UNUSED(custom_claims_buffer_size);
if (!report_data_out)
OE_RAISE(OE_INVALID_PARAMETER);
*report_data_out = ((sgx_quote_t*)report_body)->report_body.report_data;
result = OE_OK;
}
done:
return result;
}
oe_result_t oe_sgx_add_claim(
oe_claim_t* claim,
const void* name,
size_t name_size, // Must cover the '\0' at end of string
const void* value,
size_t value_size)
{
if (*((uint8_t*)name + name_size - 1) != '\0')
return OE_CONSTRAINT_FAILED;
claim->name = (char*)oe_malloc(name_size);
if (claim->name == NULL)
return OE_OUT_OF_MEMORY;
memcpy(claim->name, name, name_size);
claim->value = (uint8_t*)oe_malloc(value_size);
if (claim->value == NULL)
{
oe_free(claim->name);
claim->name = NULL;
return OE_OUT_OF_MEMORY;
}
memcpy(claim->value, value, value_size);
claim->value_size = value_size;
return OE_OK;
}
static oe_result_t _fill_with_known_claims(
const sgx_evidence_format_type_t format_type,
const oe_uuid_t* format_id,
const uint8_t* report_body,
const oe_sgx_endorsements_t* sgx_endorsements,
const oe_tcb_info_tcb_level_t* platform_tcb_level,
oe_datetime_t* valid_from,
oe_datetime_t* valid_until,
oe_claim_t* claims,
size_t claims_length,
size_t* claims_added)
{
oe_result_t result = OE_UNEXPECTED;
oe_report_t parsed_report = {0};
oe_identity_t* id = &parsed_report.identity;
oe_parsed_tcb_info_t parsed_tcb_info = {0};
const sgx_report_body_t* sgx_report_body = NULL;
sgx_quote_t* sgx_quote = NULL;
size_t claims_index = 0;
bool flag;
oe_sgx_tcb_status_t tcb_status =
oe_tcb_level_status_to_sgx_tcb_status(platform_tcb_level->status);
oe_tcb_info_tcb_level_t local_platform_tcb_level = *platform_tcb_level;
if (claims_length < OE_REQUIRED_CLAIMS_COUNT + OE_SGX_REQUIRED_CLAIMS_COUNT)
OE_RAISE(OE_INVALID_PARAMETER);
if (format_type == SGX_FORMAT_TYPE_LOCAL)
{
sgx_report_body = &((sgx_report_t*)report_body)->body;
OE_CHECK(
oe_parse_sgx_report_body(sgx_report_body, false, &parsed_report));
}
else
{
sgx_report_body = &((sgx_quote_t*)report_body)->report_body;
OE_CHECK(
oe_parse_sgx_report_body(sgx_report_body, true, &parsed_report));
sgx_quote = (sgx_quote_t*)report_body;
oe_parse_tcb_info_json(
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_TCB_INFO].data,
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_TCB_INFO].size,
&local_platform_tcb_level,
&parsed_tcb_info);
}
// Optional claims are needed for SGX quotes for remote attestation
if (format_type != SGX_FORMAT_TYPE_LOCAL &&
claims_length < OE_REQUIRED_CLAIMS_COUNT + OE_OPTIONAL_CLAIMS_COUNT +
OE_SGX_REQUIRED_CLAIMS_COUNT +
OE_SGX_OPTIONAL_CLAIMS_COUNT)
OE_RAISE(OE_INVALID_PARAMETER);
// ID version.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_ID_VERSION,
sizeof(OE_CLAIM_ID_VERSION),
&id->id_version,
sizeof(id->id_version)));
// Security version.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SECURITY_VERSION,
sizeof(OE_CLAIM_SECURITY_VERSION),
&id->security_version,
sizeof(id->security_version)));
// Attributes.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_ATTRIBUTES,
sizeof(OE_CLAIM_ATTRIBUTES),
&id->attributes,
sizeof(id->attributes)));
// Unique ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_UNIQUE_ID,
sizeof(OE_CLAIM_UNIQUE_ID),
&id->unique_id,
sizeof(id->unique_id)));
// Signer ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SIGNER_ID,
sizeof(OE_CLAIM_SIGNER_ID),
&id->signer_id,
sizeof(id->signer_id)));
// Product ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_PRODUCT_ID,
sizeof(OE_CLAIM_PRODUCT_ID),
&id->product_id,
sizeof(id->product_id)));
// Plugin UUID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_FORMAT_UUID,
sizeof(OE_CLAIM_FORMAT_UUID),
format_id,
sizeof(*format_id)));
// SGX Exit Info Reported to an SSA Frame or Not
flag = !!(sgx_report_body->miscselect & SGX_MISC_FLAGS_PF_GP_EXIT_INFO);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_PF_GP_EXINFO_ENABLED,
sizeof(OE_CLAIM_SGX_PF_GP_EXINFO_ENABLED),
&flag,
sizeof(flag)));
// SGX Report ISV Extended Product ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_ISV_EXTENDED_PRODUCT_ID,
sizeof(OE_CLAIM_SGX_ISV_EXTENDED_PRODUCT_ID),
sgx_report_body->isvextprodid,
sizeof(sgx_report_body->isvextprodid)));
// SGX Report Is Mode 64bit or Not
flag = !!(sgx_report_body->attributes.flags & SGX_FLAGS_MODE64BIT);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_IS_MODE64BIT,
sizeof(OE_CLAIM_SGX_IS_MODE64BIT),
&flag,
sizeof(flag)));
// SGX Report Has Provision Key or Not
flag = !!(sgx_report_body->attributes.flags & SGX_FLAGS_PROVISION_KEY);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_HAS_PROVISION_KEY,
sizeof(OE_CLAIM_SGX_HAS_PROVISION_KEY),
&flag,
sizeof(flag)));
// SGX Report Has Einittoken Key or Not
flag = !!(sgx_report_body->attributes.flags & SGX_FLAGS_EINITTOKEN_KEY);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_HAS_EINITTOKEN_KEY,
sizeof(OE_CLAIM_SGX_HAS_EINITTOKEN_KEY),
&flag,
sizeof(flag)));
// SGX Use KSS or Not
flag = !!(sgx_report_body->attributes.flags & SGX_FLAGS_KSS);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_USES_KSS,
sizeof(OE_CLAIM_SGX_USES_KSS),
&flag,
sizeof(flag)));
// SGX Report Config ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_CONFIG_ID,
sizeof(OE_CLAIM_SGX_CONFIG_ID),
sgx_report_body->configid,
sizeof(sgx_report_body->configid)));
// SGX Report Config SVN
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_CONFIG_SVN,
sizeof(OE_CLAIM_SGX_CONFIG_SVN),
&sgx_report_body->configsvn,
sizeof(sgx_report_body->configsvn)));
// SGX Report ISV Family ID
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_ISV_FAMILY_ID,
sizeof(OE_CLAIM_SGX_ISV_FAMILY_ID),
sgx_report_body->isvfamilyid,
sizeof(sgx_report_body->isvfamilyid)));
// SGX report CPUSVN
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_CPU_SVN,
sizeof(OE_CLAIM_SGX_CPU_SVN),
sgx_report_body->cpusvn,
SGX_CPUSVN_SIZE));
if (format_type != SGX_FORMAT_TYPE_LOCAL)
{
/* Generic optional claims */
// TCB status.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_TCB_STATUS,
sizeof(OE_CLAIM_TCB_STATUS),
&tcb_status,
sizeof(tcb_status)));
// TCB date.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_TCB_DATE,
sizeof(OE_CLAIM_TCB_DATE),
&platform_tcb_level->tcb_date,
sizeof(platform_tcb_level->tcb_date)));
// Validity from.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_VALIDITY_FROM,
sizeof(OE_CLAIM_VALIDITY_FROM),
valid_from,
sizeof(*valid_from)));
// Validity to.
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_VALIDITY_UNTIL,
sizeof(OE_CLAIM_VALIDITY_UNTIL),
valid_until,
sizeof(*valid_until)));
// quote QEID
uint8_t ueid[OE_UEID_SIZE] = {0};
ueid[0] = OE_UEID_TYPE_RAND;
memcpy(&ueid[1], sgx_quote->user_data, SGX_USERDATA_SIZE);
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_UEID,
sizeof(OE_CLAIM_UEID),
ueid,
OE_UEID_SIZE));
// TCB info FMSPC
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_HARDWARE_MODEL,
sizeof(OE_CLAIM_HARDWARE_MODEL),
OE_TCB_INFO_GET(&parsed_tcb_info, fmspc),
OE_SGX_FMSPC_SIZE));
/* SGX specific optional claims */
// SGX quote verification collaterals
{
// TCB info
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_TCB_INFO,
sizeof(OE_CLAIM_SGX_TCB_INFO),
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_TCB_INFO].data,
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_TCB_INFO]
.size));
// TCB issuer chain
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_TCB_ISSUER_CHAIN,
sizeof(OE_CLAIM_SGX_TCB_ISSUER_CHAIN),
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_TCB_ISSUER_CHAIN]
.data,
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_TCB_ISSUER_CHAIN]
.size));
// PCK CRL
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_PCK_CRL,
sizeof(OE_CLAIM_SGX_PCK_CRL),
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_CRL_PCK_CERT]
.data,
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_CRL_PCK_CERT]
.size));
// Root CA CRL
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_ROOT_CA_CRL,
sizeof(OE_CLAIM_SGX_ROOT_CA_CRL),
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_CRL_PCK_PROC_CA]
.data,
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_CRL_PCK_PROC_CA]
.size));
// CRL Issuer Chain
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_CRL_ISSUER_CHAIN,
sizeof(OE_CLAIM_SGX_CRL_ISSUER_CHAIN),
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_CRL_ISSUER_CHAIN_PCK_CERT]
.data,
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_CRL_ISSUER_CHAIN_PCK_CERT]
.size));
// QE ID info
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_QE_ID_INFO,
sizeof(OE_CLAIM_SGX_QE_ID_INFO),
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_QE_ID_INFO]
.data,
sgx_endorsements->items[OE_SGX_ENDORSEMENT_FIELD_QE_ID_INFO]
.size));
// QE ID issuer chain
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_QE_ID_ISSUER_CHAIN,
sizeof(OE_CLAIM_SGX_QE_ID_ISSUER_CHAIN),
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_QE_ID_ISSUER_CHAIN]
.data,
sgx_endorsements
->items[OE_SGX_ENDORSEMENT_FIELD_QE_ID_ISSUER_CHAIN]
.size));
}
// SGX quote PCESVN
OE_CHECK(oe_sgx_add_claim(
&claims[claims_index++],
OE_CLAIM_SGX_PCE_SVN,
sizeof(OE_CLAIM_SGX_PCE_SVN),
&sgx_quote->pce_svn,
sizeof(sgx_quote->pce_svn)));
}
*claims_added = claims_index;
result = OE_OK;
done:
if (result != OE_OK)
{
for (size_t i = 0; i < claims_index; i++)
_free_claim(&claims[i]);
}
return result;
}
oe_result_t oe_sgx_hash_custom_claims_buffer(
const void* custom_claims_buffer,
size_t custom_claims_buffer_size,
OE_SHA256* hash_out)
{
oe_result_t result = OE_UNEXPECTED;
// Default hash for empty string, as described in the literature.
static const uint8_t sha256_for_empty_string[] = {
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
// Produce a hash of the custom_claims_buffer.
// If there is no data, set to default value
if (!custom_claims_buffer || !custom_claims_buffer_size)
memcpy(hash_out, sha256_for_empty_string, sizeof(*hash_out));
else
// Produce a hash of the custom_claims_buffer.
OE_CHECK(oe_sha256(
custom_claims_buffer, custom_claims_buffer_size, hash_out));
result = OE_OK;
done:
return result;
}
oe_result_t oe_sgx_extract_claims(
const sgx_evidence_format_type_t format_type,
const oe_uuid_t* format_id,
const uint8_t* report_body,
size_t report_body_size,
const uint8_t* custom_claims_buffer,
size_t custom_claims_buffer_size,
const oe_sgx_endorsements_t* sgx_endorsements,
const oe_tcb_info_tcb_level_t* platform_tcb_level,
oe_datetime_t* valid_from,
oe_datetime_t* valid_until,
oe_claim_t** claims_out,
size_t* claims_length_out)
{
oe_result_t result = OE_UNEXPECTED;
oe_claim_t* claims = NULL;
uint64_t claims_length = 0;
uint64_t claims_size = 0;
size_t claims_added = 0;
size_t additional_claim = 0;
sgx_report_data_t report_data;
oe_datetime_t local_valid_from = {0};
oe_datetime_t local_valid_until = {0};
// Note: some callers can have custom_claims_buffer pointing to a non-NULL
// buffer containing a zero-sized array.
if (!format_id || !report_body || !report_body_size || !claims_out ||
!claims_length_out ||
(!custom_claims_buffer != !custom_claims_buffer_size))
OE_RAISE(OE_INVALID_PARAMETER);
// verify the integrity of the custom_claims_buffer with hash stored in
// report_body, or retrieve the SGX report data
OE_CHECK(_process_sgx_report_data(
format_type,
report_body,
custom_claims_buffer,
custom_claims_buffer_size,
&report_data));
// If provided, custom_claims_buffer can only be the
// OE_CLAIM_CUSTOM_CLAIMS_BUFFER or OE_CLAIM_SGX_REPORT_DATA types.
if ((format_type == SGX_FORMAT_TYPE_LOCAL ||
format_type == SGX_FORMAT_TYPE_REMOTE) &&
(!custom_claims_buffer || !custom_claims_buffer_size))
additional_claim = 0;
else
additional_claim = 1;
// Get the number of claims we need and allocate the claims.
OE_CHECK(oe_safe_add_u64(
OE_REQUIRED_CLAIMS_COUNT + OE_SGX_REQUIRED_CLAIMS_COUNT,
additional_claim,
&claims_length));
if (format_type != SGX_FORMAT_TYPE_LOCAL)
{
OE_CHECK(oe_safe_add_u64(
claims_length,
OE_OPTIONAL_CLAIMS_COUNT + OE_SGX_OPTIONAL_CLAIMS_COUNT,
&claims_length));
}
OE_CHECK(oe_safe_mul_u64(claims_length, sizeof(oe_claim_t), &claims_size));
claims = (oe_claim_t*)oe_malloc(claims_size);
if (claims == NULL)
OE_RAISE(OE_OUT_OF_MEMORY);
if (!valid_from || !valid_until)
{
// Get quote validity periods to get validity from and until claims if
// valid_from and valid_until is not provided.
OE_CHECK(oe_get_sgx_quote_validity(
report_body,
report_body_size,
sgx_endorsements,
NULL,
&local_valid_from,
&local_valid_until));
valid_from = &local_valid_from;
valid_until = &local_valid_until;
}
// Fill the list with the known claims.
OE_CHECK(_fill_with_known_claims(
format_type,
format_id,
report_body,
sgx_endorsements,
platform_tcb_level,
valid_from,
valid_until,
claims,
claims_length,
&claims_added));
// Fill with the additional claim
if (additional_claim)
{
if (format_type == SGX_FORMAT_TYPE_LOCAL ||
format_type == SGX_FORMAT_TYPE_REMOTE)
{
// Add custom claims buffer
char* name = OE_CLAIM_CUSTOM_CLAIMS_BUFFER;
OE_CHECK(oe_sgx_add_claim(
claims + claims_added,
name,
oe_strlen(name) + 1,
custom_claims_buffer,
custom_claims_buffer_size));
}
else // SGX_FORMAT_TYPE_LEGACY_REPORT and _QUOTE
{
// Add SGX report data claim
char* name = OE_CLAIM_SGX_REPORT_DATA;
OE_CHECK(oe_sgx_add_claim(
claims + claims_added,
name,
oe_strlen(name) + 1,
&report_data,
sizeof(report_data)));
}
}
*claims_out = claims;
*claims_length_out = claims_length;
claims = NULL;
result = OE_OK;
done:
if (claims)
oe_sgx_free_claims_list(NULL, claims, claims_length);
return result;
}
oe_result_t oe_sgx_verify_evidence(
oe_verifier_t* context,
const uint8_t* evidence_buffer,
size_t evidence_buffer_size,
const uint8_t* endorsements_buffer,
size_t endorsements_buffer_size,
const oe_policy_t* policies,
size_t policies_size,
oe_claim_t** claims,
size_t* claims_length)
{
oe_result_t result = OE_UNEXPECTED;
oe_result_t result_verify_quote = OE_UNEXPECTED;
oe_datetime_t* time = NULL;
oe_datetime_t valid_from = {0};
oe_datetime_t valid_until = {0};
uint8_t* local_endorsements_buffer = NULL;
size_t local_endorsements_buffer_size = 0;
oe_sgx_endorsements_t sgx_endorsements;
oe_tcb_info_tcb_level_t platform_tcb_level = {{0}};
sgx_evidence_format_type_t format_type = SGX_FORMAT_TYPE_UNKNOWN;
const uint8_t* report_body = NULL;
size_t report_body_size = 0;
const uint8_t* custom_claims_buffer = NULL;
size_t custom_claims_buffer_size = 0;
oe_uuid_t* format_id = NULL;
if (!context || !evidence_buffer || !evidence_buffer_size ||
(!endorsements_buffer != !endorsements_buffer_size) ||
(!claims != !claims_length))
OE_RAISE(OE_INVALID_PARAMETER);
format_id = &context->base.format_id;
// Check the datetime policy if it exists.
OE_CHECK(_get_input_time(policies, policies_size, &time));
if (!memcmp(format_id, &_uuid_sgx_local_attestation, sizeof(oe_uuid_t)))
{
// evidence_buffer has an SGX report for local attestation
// followed by an optional custom claims buffer.
// Note: sgx_report_t has no field that can be checked quickly
// to verify it being an SGX report.
if (evidence_buffer_size < sizeof(sgx_report_t))
OE_RAISE(OE_INVALID_PARAMETER);
format_type = SGX_FORMAT_TYPE_LOCAL;
}
else if (!memcmp(format_id, &_uuid_sgx_ecdsa, sizeof(oe_uuid_t)))
{
// evidence_buffer has an SGX ECDSA-p256 quote
// followed by an optional custom claims buffer.
sgx_quote_t* quote = (sgx_quote_t*)evidence_buffer;
if (evidence_buffer_size < sizeof(*quote) + quote->signature_len ||
quote->version != SGX_QE3_QUOTE_VERSION ||
quote->sign_type != SGX_QL_ALG_ECDSA_P256 ||
quote->tee_type != SGX_QUOTE_TYPE)
OE_RAISE(OE_INVALID_PARAMETER);
format_type = SGX_FORMAT_TYPE_REMOTE;
}
else if (!memcmp(format_id, &_uuid_legacy_report_remote, sizeof(oe_uuid_t)))
{
// evidence_buffer has an oe_report_header_t header
// followed by an SGX report or ECDSA-p256 quote.
oe_report_header_t* report = (oe_report_header_t*)evidence_buffer;
if (evidence_buffer_size < sizeof(*report) ||
report->version != OE_REPORT_HEADER_VERSION ||
report->report_type != OE_REPORT_TYPE_SGX_REMOTE)
OE_RAISE(OE_INVALID_PARAMETER);
format_type = SGX_FORMAT_TYPE_LEGACY_REPORT;
}
else if (!memcmp(format_id, &_uuid_raw_sgx_quote_ecdsa, sizeof(oe_uuid_t)))
{
// evidence_buffer has no header.
// It holds an SGX ECDSA_p256 quote generated by the Intel SGX DCAP
// or quote-ex library.
sgx_quote_t* quote = (sgx_quote_t*)evidence_buffer;
if (evidence_buffer_size < sizeof(*quote) + quote->signature_len ||
quote->version != SGX_QE3_QUOTE_VERSION ||
quote->sign_type != SGX_QL_ALG_ECDSA_P256 ||
quote->tee_type != SGX_QUOTE_TYPE)
OE_RAISE(OE_INVALID_PARAMETER);
format_type = SGX_FORMAT_TYPE_RAW_QUOTE;
}
else
OE_RAISE(OE_INVALID_PARAMETER);
// Verify the report. Send the report size to just the oe report,
// not including the custom claims section.
if (format_type == SGX_FORMAT_TYPE_LOCAL)
{
report_body = evidence_buffer;
report_body_size = sizeof(sgx_report_t);
if (evidence_buffer_size > report_body_size)
{
custom_claims_buffer = report_body + report_body_size;
custom_claims_buffer_size = evidence_buffer_size - report_body_size;
}
OE_CHECK(_verify_local_report(report_body, report_body_size));
}
else
{
if (format_type == SGX_FORMAT_TYPE_REMOTE)
{
sgx_quote_t* quote = (sgx_quote_t*)evidence_buffer;
report_body = evidence_buffer;
report_body_size = sizeof(*quote) + quote->signature_len;
if (evidence_buffer_size > report_body_size)
{
custom_claims_buffer = report_body + report_body_size;
custom_claims_buffer_size =
evidence_buffer_size - report_body_size;
}
}
else if (format_type == SGX_FORMAT_TYPE_LEGACY_REPORT)
{
oe_report_header_t* report = (oe_report_header_t*)evidence_buffer;
report_body = report->report;
report_body_size = report->report_size;
custom_claims_buffer = NULL;
custom_claims_buffer_size = 0;
}
else // SGX_FORMAT_TYPE_RAW_QUOTE
{
report_body = evidence_buffer;
report_body_size = evidence_buffer_size;
custom_claims_buffer = NULL;
custom_claims_buffer_size = 0;
}
// Get the endorsements if none were provided.
if (endorsements_buffer == NULL)
{
OE_CHECK(oe_get_sgx_endorsements(
report_body,
report_body_size,
policies,
policies_size,
&local_endorsements_buffer,
&local_endorsements_buffer_size));
endorsements_buffer = local_endorsements_buffer;
endorsements_buffer_size = local_endorsements_buffer_size;
}
// Parse into SGX endorsements.
OE_CHECK(oe_parse_sgx_endorsements(
(oe_endorsements_t*)endorsements_buffer,
endorsements_buffer_size,
&sgx_endorsements));
// Verify the quote now.
OE_CHECK_NO_TCB_LEVEL(
result_verify_quote,
oe_verify_quote_with_sgx_endorsements(
report_body,
report_body_size,
&sgx_endorsements,
time,
&platform_tcb_level,
&valid_from,
&valid_until));
// A successful oe_verify_quote_with_sgx_endorsements() returns either
// OE_OK, or OE_TCB_LEVEL_INVALID as OE does not terminate verification
// due to TCB status not being up to date. So, the verification result
// should be consistent with the retrieved TCB status.
if ((result_verify_quote == OE_OK) !=
(platform_tcb_level.status.fields.up_to_date == 1))
{
OE_RAISE_MSG(
OE_CONSTRAINT_FAILED,
"Inconsistent TCB status: verify quote(%s), tcb status(%s)",
oe_result_str(result_verify_quote),
oe_sgx_tcb_status_str(oe_tcb_level_status_to_sgx_tcb_status(
platform_tcb_level.status)));
}
}
// Last step is to return the required and custom claims.
if (claims)
{
OE_CHECK(oe_sgx_extract_claims(
format_type,
format_id,
report_body,
report_body_size,
custom_claims_buffer,
custom_claims_buffer_size,
&sgx_endorsements,
&platform_tcb_level,
&valid_from,
&valid_until,
claims,
claims_length));
}
result = format_type == SGX_FORMAT_TYPE_LOCAL ? OE_OK : result_verify_quote;
done:
if (local_endorsements_buffer)
oe_free_sgx_endorsements(local_endorsements_buffer);
return result;
}
// Gets the optional format settings for the given verifier plugin context.
// For SGX local attestation, this would be the sgx_target_info_t struct.
static oe_result_t _get_format_settings(
oe_verifier_t* context,
uint8_t** settings,
size_t* settings_size)
{
oe_result_t result = OE_UNEXPECTED;
oe_report_header_t* report = NULL;
if (!context || !settings || !settings_size)
OE_RAISE(OE_INVALID_PARAMETER);
if (!memcmp(
&context->base.format_id,
&_uuid_sgx_local_attestation,
sizeof(oe_uuid_t)))
{
#ifdef OE_BUILD_ENCLAVE
// Enclave-side, SGX local attestation is supported
uint8_t* tmp_target = NULL;
size_t tmp_target_size = 0;
report = (oe_report_header_t*)oe_malloc(
sizeof(oe_report_header_t) + sizeof(sgx_report_t));
if (!report)
OE_RAISE(OE_OUT_OF_MEMORY);
OE_CHECK(sgx_create_report(
NULL, 0, NULL, 0, (sgx_report_t*)&report->report));
report->version = OE_REPORT_HEADER_VERSION;
report->report_type = OE_REPORT_TYPE_SGX_LOCAL;
report->report_size = sizeof(sgx_report_t);
OE_CHECK(oe_get_target_info_v2(
(const uint8_t*)report,
sizeof(oe_report_header_t) + sizeof(sgx_report_t),
(void**)&tmp_target,
&tmp_target_size));
*settings = tmp_target;
*settings_size = tmp_target_size;
tmp_target = NULL;
result = OE_OK;
#else
// Host-side, SGX local attestation is not supported
OE_RAISE(OE_UNSUPPORTED);
#endif
}
else if (!memcmp(
&context->base.format_id, &_uuid_sgx_ecdsa, sizeof(oe_uuid_t)))
{
*settings = NULL;
*settings_size = 0;
result = OE_OK;
}
else
{
OE_RAISE(OE_UNSUPPORTED);
}
done:
if (report)
oe_free(report);
return result;
}
static oe_result_t _verify_report(
oe_verifier_t* context,
const uint8_t* report,
size_t report_size,
oe_report_t* parsed_report)
{
oe_result_t result = OE_UNEXPECTED;
if (!context || !report || report_size == 0)
OE_RAISE(OE_INVALID_PARAMETER);
// Enclave-side, verifies ECDSA and local report
// Host-side, verifies only ECDSA report
if (
#ifdef OE_BUILD_ENCLAVE
!memcmp(
&context->base.format_id,
&_uuid_sgx_local_attestation,
sizeof(oe_uuid_t)) ||
#endif
!memcmp(&context->base.format_id, &_uuid_sgx_ecdsa, sizeof(oe_uuid_t)))
{
#ifdef OE_BUILD_ENCLAVE
OE_CHECK(oe_verify_report_internal(report, report_size, parsed_report));
#else
OE_CHECK(oe_verify_report_internal(
NULL, report, report_size, parsed_report));
#endif
result = OE_OK;
}
else
OE_RAISE(OE_UNSUPPORTED);
done:
return result;
}
static oe_result_t _get_verifier_plugins(
oe_verifier_t** verifiers,
size_t* verifiers_length)
{
oe_result_t result = OE_UNEXPECTED;
size_t uuid_count = 0;
const oe_uuid_t* uuids[4];
if (!verifiers || !verifiers_length)
OE_RAISE(OE_INVALID_PARAMETER);
uuids[0] = &_uuid_sgx_ecdsa;
uuids[1] = &_uuid_legacy_report_remote;
uuids[2] = &_uuid_raw_sgx_quote_ecdsa;
#ifdef OE_BUILD_ENCLAVE
uuids[3] = &_uuid_sgx_local_attestation;
uuid_count =
4; // In enclave, local attestation and 3 ECDSA formats are supported.
#else
// On the host side, only 3 ECDSA formats are supported.
// Note: SGX local attestation can only be performed between enclaves.
uuid_count = 3;
#endif
*verifiers = (oe_verifier_t*)oe_malloc(sizeof(oe_verifier_t) * uuid_count);
if (*verifiers == NULL)
OE_RAISE(OE_OUT_OF_MEMORY);
for (size_t i = 0; i < uuid_count; i++)
{
oe_verifier_t* plugin = *verifiers + i;
plugin->base.format_id = *uuids[i];
plugin->base.on_register = &_on_register;
plugin->base.on_unregister = &_on_unregister;
plugin->get_format_settings = &_get_format_settings;
plugin->verify_evidence = &oe_sgx_verify_evidence;
plugin->verify_report = &_verify_report;
plugin->free_claims = &oe_sgx_free_claims_list;
}
*verifiers_length = uuid_count;
result = OE_OK;
done:
return result;
}
static oe_verifier_t* verifiers = NULL;
static size_t verifiers_length = 0;
static oe_mutex_t init_mutex = OE_MUTEX_INITIALIZER;
oe_result_t oe_verifier_initialize(void)
{
oe_result_t result = OE_UNEXPECTED;
if (oe_mutex_lock(&init_mutex))
OE_RAISE(OE_UNEXPECTED);
// Do nothing if verifier plugins are already initialized
if (verifiers)
{
OE_TRACE_INFO(
"verifiers is not NULL, verifiers_length=%d", verifiers_length);
result = OE_OK;
goto done;
}
OE_CHECK(_get_verifier_plugins(&verifiers, &verifiers_length));
OE_TRACE_INFO("got verifiers_length=%d plugins", verifiers_length);
for (size_t i = 0; i < verifiers_length; i++)
{
result = oe_register_verifier_plugin(verifiers + i, NULL, 0);
OE_CHECK(result);
}
result = OE_OK;
done:
oe_mutex_unlock(&init_mutex);
return result;
}
// Registration of plugins does not allocate any resources to them.
oe_result_t oe_verifier_shutdown(void)
{
oe_result_t result = OE_UNEXPECTED;
if (oe_mutex_lock(&init_mutex))
OE_RAISE(OE_UNEXPECTED);
// Either verifier plugins have not been initialized,
// or there is no supported plugin
if (!verifiers)
{
OE_TRACE_INFO("verifiers is NULL");
result = OE_OK;
goto done;
}
OE_TRACE_INFO("free verifiers_length=%d plugins", verifiers_length);
for (size_t i = 0; i < verifiers_length; i++)
{
result = oe_unregister_verifier_plugin(verifiers + i);
if (result != OE_OK)
OE_TRACE_ERROR(
"oe_unregister_verifier_plugin() #%lu failed with %s",
i,
oe_result_str(result));
}
oe_free(verifiers);
verifiers = NULL;
verifiers_length = 0;
result = OE_OK;
done:
oe_mutex_unlock(&init_mutex);
return result;
}
|
ff99f54111103459483b9949da44cecea4198ba2
|
da1500e0d3040497614d5327d2461a22e934b4d8
|
/cobalt/bindings/shared/idl_conditional_macros.h
|
a34191f5b5de8421c25e09a75fc258a00e3ee7d7
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
youtube/cobalt
|
34085fc93972ebe05b988b15410e99845efd1968
|
acefdaaadd3ef46f10f63d1acae2259e4024d383
|
refs/heads/main
| 2023-09-01T13:09:47.225174
| 2023-09-01T08:54:54
| 2023-09-01T08:54:54
| 50,049,789
| 169
| 80
|
BSD-3-Clause
| 2023-09-14T21:50:50
| 2016-01-20T18:11:34
| null |
UTF-8
|
C
| false
| false
| 1,288
|
h
|
idl_conditional_macros.h
|
// Copyright 2018 The Cobalt Authors. All Rights Reserved.
//
// 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.
#ifndef COBALT_BINDINGS_SHARED_IDL_CONDITIONAL_MACROS_H_
#define COBALT_BINDINGS_SHARED_IDL_CONDITIONAL_MACROS_H_
#include "starboard/configuration.h"
// Define preprocessor macros that cannot be determined at GYP time for use in
// IDL files with Conditionals (e.g. conditional interface definitions, or
// conditional attributes). This is necessary to make macros for IDL
// Conditionals that are dependent on Starboard feature macros that get defined
// in header files.
// This is used to conditionally define the On Screen Keyboard interface and
// attribute.
#define COBALT_ENABLE_ON_SCREEN_KEYBOARD
#endif // COBALT_BINDINGS_SHARED_IDL_CONDITIONAL_MACROS_H_
|
77b744487ad14aa2112cd906878bfd7ac76000d7
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/linux/bootmem.h
|
5f0b0e1f7c08abab8c8701751fe0948667a12149
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 5,657
|
h
|
bootmem.h
|
/*
* Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
*/
#ifndef _LINUX_BOOTMEM_H
#define _LINUX_BOOTMEM_H
#include <linux/mmzone.h>
#include <asm/dma.h>
/*
* simple boot-time physical memory area allocator.
*/
extern unsigned long max_low_pfn;
extern unsigned long min_low_pfn;
/*
* highest page
*/
extern unsigned long max_pfn;
#ifndef CONFIG_NO_BOOTMEM
/*
* node_bootmem_map is a map pointer - the bits represent all physical
* memory pages (including holes) on the node.
*/
typedef struct bootmem_data {
unsigned long node_min_pfn;
unsigned long node_low_pfn;
void *node_bootmem_map;
unsigned long last_end_off;
unsigned long hint_idx;
struct list_head list;
} bootmem_data_t;
extern bootmem_data_t bootmem_node_data[];
#endif
extern unsigned long bootmem_bootmap_pages(unsigned long);
extern unsigned long init_bootmem_node(pg_data_t *pgdat,
unsigned long freepfn,
unsigned long startpfn,
unsigned long endpfn);
extern unsigned long init_bootmem(unsigned long addr, unsigned long memend);
extern unsigned long free_all_bootmem_node(pg_data_t *pgdat);
extern unsigned long free_all_bootmem(void);
extern void free_bootmem_node(pg_data_t *pgdat,
unsigned long addr,
unsigned long size);
extern void free_bootmem(unsigned long physaddr, unsigned long size);
extern void free_bootmem_late(unsigned long physaddr, unsigned long size);
extern void __free_pages_bootmem(struct page *page, unsigned int order);
/*
* Flags for reserve_bootmem (also if CONFIG_HAVE_ARCH_BOOTMEM_NODE,
* the architecture-specific code should honor this).
*
* If flags is 0, then the return value is always 0 (success). If
* flags contains BOOTMEM_EXCLUSIVE, then -EBUSY is returned if the
* memory already was reserved.
*/
#define BOOTMEM_DEFAULT 0
#define BOOTMEM_EXCLUSIVE (1<<0)
extern int reserve_bootmem(unsigned long addr,
unsigned long size,
int flags);
extern int reserve_bootmem_node(pg_data_t *pgdat,
unsigned long physaddr,
unsigned long size,
int flags);
extern void *__alloc_bootmem(unsigned long size,
unsigned long align,
unsigned long goal);
extern void *__alloc_bootmem_nopanic(unsigned long size,
unsigned long align,
unsigned long goal);
extern void *__alloc_bootmem_node(pg_data_t *pgdat,
unsigned long size,
unsigned long align,
unsigned long goal);
void *__alloc_bootmem_node_high(pg_data_t *pgdat,
unsigned long size,
unsigned long align,
unsigned long goal);
extern void *__alloc_bootmem_node_nopanic(pg_data_t *pgdat,
unsigned long size,
unsigned long align,
unsigned long goal);
void *___alloc_bootmem_node_nopanic(pg_data_t *pgdat,
unsigned long size,
unsigned long align,
unsigned long goal,
unsigned long limit);
extern void *__alloc_bootmem_low(unsigned long size,
unsigned long align,
unsigned long goal);
void *__alloc_bootmem_low_nopanic(unsigned long size,
unsigned long align,
unsigned long goal);
extern void *__alloc_bootmem_low_node(pg_data_t *pgdat,
unsigned long size,
unsigned long align,
unsigned long goal);
#ifdef CONFIG_NO_BOOTMEM
/* We are using top down, so it is safe to use 0 here */
#define BOOTMEM_LOW_LIMIT 0
#else
#define BOOTMEM_LOW_LIMIT __pa(MAX_DMA_ADDRESS)
#endif
#define alloc_bootmem(x) \
__alloc_bootmem(x, SMP_CACHE_BYTES, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_align(x, align) \
__alloc_bootmem(x, align, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_nopanic(x) \
__alloc_bootmem_nopanic(x, SMP_CACHE_BYTES, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_pages(x) \
__alloc_bootmem(x, PAGE_SIZE, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_pages_nopanic(x) \
__alloc_bootmem_nopanic(x, PAGE_SIZE, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_node(pgdat, x) \
__alloc_bootmem_node(pgdat, x, SMP_CACHE_BYTES, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_node_nopanic(pgdat, x) \
__alloc_bootmem_node_nopanic(pgdat, x, SMP_CACHE_BYTES, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_pages_node(pgdat, x) \
__alloc_bootmem_node(pgdat, x, PAGE_SIZE, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_pages_node_nopanic(pgdat, x) \
__alloc_bootmem_node_nopanic(pgdat, x, PAGE_SIZE, BOOTMEM_LOW_LIMIT)
#define alloc_bootmem_low(x) \
__alloc_bootmem_low(x, SMP_CACHE_BYTES, 0)
#define alloc_bootmem_low_pages_nopanic(x) \
__alloc_bootmem_low_nopanic(x, PAGE_SIZE, 0)
#define alloc_bootmem_low_pages(x) \
__alloc_bootmem_low(x, PAGE_SIZE, 0)
#define alloc_bootmem_low_pages_node(pgdat, x) \
__alloc_bootmem_low_node(pgdat, x, PAGE_SIZE, 0)
#ifdef CONFIG_HAVE_ARCH_ALLOC_REMAP
extern void *alloc_remap(int nid, unsigned long size);
#else
static inline void *alloc_remap(int nid, unsigned long size)
{
return NULL;
}
#endif /* CONFIG_HAVE_ARCH_ALLOC_REMAP */
extern void *alloc_large_system_hash(const char *tablename,
unsigned long bucketsize,
unsigned long numentries,
int scale,
int flags,
unsigned int *_hash_shift,
unsigned int *_hash_mask,
unsigned long low_limit,
unsigned long high_limit);
#define HASH_EARLY 0x00000001 /* Allocating during early boot? */
#define HASH_SMALL 0x00000002 /* sub-page allocation allowed, min
* shift passed via *_hash_shift */
/* Only NUMA needs hash distribution. 64bit NUMA architectures have
* sufficient vmalloc space.
*/
#if defined(CONFIG_NUMA) && defined(CONFIG_64BIT)
#define HASHDIST_DEFAULT 1
#else
#define HASHDIST_DEFAULT 0
#endif
extern int hashdist; /* Distribute hashes across NUMA nodes? */
#endif /* _LINUX_BOOTMEM_H */
|
ed797b5286196400cf26e31e0f3a89d0626e0800
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/tools/examples/embedviewer/SimpleVisApp.C
|
ea3f433e49ba2899c9a83a1fd05d378d48e6554d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
visit-dav/visit
|
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
|
601ae46e0bef2e18425b482a755d03490ade0493
|
refs/heads/develop
| 2023-09-06T08:19:38.397058
| 2023-09-05T21:29:32
| 2023-09-05T21:29:32
| 165,565,988
| 335
| 120
|
BSD-3-Clause
| 2023-09-14T00:53:37
| 2019-01-13T23:27:26
|
C
|
UTF-8
|
C
| false
| false
| 11,167
|
c
|
SimpleVisApp.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <SimpleVisApp.h>
#include <VisItViewer.h>
#include <ViewerMethods.h>
#include <QApplication>
#include <QButtonGroup>
#include <QDir>
#include <QFileDialog>
#include <QLabel>
#include <QLayout>
#include <QListWidget>
#include <QMenuBar>
#include <QMenu>
#include <QRadioButton>
#include <QSpinBox>
#include <QWidget>
// State objects that we use.
#include <avtDatabaseMetaData.h>
#include <SaveWindowAttributes.h>
// Include this last since something about it on X11 systems seems to
// interfere with some of our other enums. X11 headers must have some
// naughty #define directives.
#include <vtkQtRenderWindow.h>
#include "CommandParser.h"
QWidget *
create_application_main_window(VisItViewer *v, int *argc, char ***argv)
{
return new SimpleVisApp(v, argc, argv);
}
void
show_application_main_window(QWidget *w)
{
// Do it like this since virtual show isn't working...
SimpleVisApp *app = (SimpleVisApp *)w;
app->show();
app->raise();
app->execFile(1);
}
vtkQtRenderWindow *
SimpleVisApp::ReturnVisWin(void *data)
{
SimpleVisApp *This = (SimpleVisApp *)data;
return This->viswin;
}
// ****************************************************************************
// Method: SimpleVisApp::SimpleVisApp
//
// Purpose:
// Constructor.
//
// Arguments:
// v : The VisItViewer object that we'll use to control the viewer.
//
// Programmer: Brad Whitlock
// Creation: Fri Nov 21 10:23:40 PST 2008
//
// Modifications:
// Brad Whitlock, Fri Nov 21 10:23:46 PST 2008
// Fixed some slots for Qt 4.
//
// Kathleen Biagas, Tue Apr 18 16:34:41 PDT 2023
// Support Qt6: buttonClicked -> idClicked.
//
// ****************************************************************************
SimpleVisApp::SimpleVisApp(VisItViewer *v, int *argc, char ***argv)
: QMainWindow()
{
viewer = v;
setWindowTitle(tr("Simple visualization"));
plotType = 0;
// Create the window.
QWidget *central = new QWidget(this);
setCentralWidget(central);
QHBoxLayout *hLayout = new QHBoxLayout(central);
hLayout->setContentsMargins(10,10,10,10);
hLayout->setSpacing(10);
QVBoxLayout *leftLayout = new QVBoxLayout(0);
leftLayout->setSpacing(10);
hLayout->addLayout(leftLayout);
scalarLabel = new QLabel(tr("Scalar variables"), central);
leftLayout->addWidget(scalarLabel);
variables = new QListWidget(central);
leftLayout->addWidget(variables);
connect(variables, SIGNAL(currentTextChanged(const QString &)),
this, SLOT(changeVariable(const QString &)));
plotTypeWidget = new QWidget(central);
leftLayout->addWidget(plotTypeWidget);
QHBoxLayout *ptLayout = new QHBoxLayout(plotTypeWidget);
ptLayout->setSpacing(10);
ptLayout->addWidget(new QLabel(tr("Plot type"), plotTypeWidget));
plotType = new QButtonGroup(plotTypeWidget);
QRadioButton *rb = new QRadioButton(tr("Pseudocolor"), plotTypeWidget);
plotType->addButton(rb, 0);
ptLayout->addWidget(rb);
rb = new QRadioButton(tr("Contour"), plotTypeWidget);
plotType->addButton(rb, 1);
ptLayout->addWidget(rb);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
connect(plotType, SIGNAL(buttonClicked(int)),
this, SLOT(changePlotType(int)));
#else
connect(plotType, SIGNAL(idClicked(int)),
this, SLOT(changePlotType(int)));
#endif
contourWidget = new QWidget(central);
leftLayout->addWidget(contourWidget);
QHBoxLayout *cLayout = new QHBoxLayout(contourWidget);
cLayout->setSpacing(10);
nContours = new QSpinBox(contourWidget);
nContours->setRange(1,40);
nContours->setValue(10);
connect(nContours, SIGNAL(valueChanged(int)),
this, SLOT(setNContours(int)));
cLayout->addWidget(new QLabel(tr("Number of contours"), contourWidget));
cLayout->addWidget(nContours);
// Create the vis window directly.
viswin = new vtkQtRenderWindow(central);
viswin->setMinimumSize(QSize(500,500));
hLayout->addWidget(viswin, 100);
// Create menus
QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(tr("Open . . ."), this, SLOT(selectFile()));
fileMenu->addAction(tr("Open commands. . ."), this, SLOT(execFile()));
fileMenu->addSeparator();
fileMenu->addAction(tr("Save window"), this, SLOT(saveWindow()));
fileMenu->addSeparator();
fileMenu->addAction(tr("Quit"), this, SLOT(quitApp()));
QMenu *controlsMenu = menuBar()->addMenu(tr("Controls"));
controlsMenu->addAction(tr("Open GUI"), this, SLOT(openGUI()));
//
// Register a window creation function (before Setup) that will
// return the vtkQtRenderWindow objects that we've already
// parented into our interface.
//
viewer->SetWindowCreationCallback(ReturnVisWin, (void *)this);
// Set the initial widget sensitivity.
resetWindow();
cmd = 0;
if (*argc > 1)
clfilename = (*argv)[1];
}
SimpleVisApp::~SimpleVisApp()
{
delete cmd;
}
void
SimpleVisApp::quitApp()
{
qApp->quit();
}
void
SimpleVisApp::resetWindow()
{
variables->blockSignals(true);
variables->clear();
variables->blockSignals(false);
plotType->blockSignals(true);
plotType->button(0)->setChecked(true);
plotType->blockSignals(false);
scalarLabel->setEnabled(false);
variables->setEnabled(false);
plotTypeWidget->setEnabled(false);
contourWidget->setEnabled(false);
viewer->Methods()->DeleteActivePlots();
}
void
SimpleVisApp::show()
{
// Tell the viewer to hide toolbars in all windows.
viewer->Methods()->HideToolbars(true);
// Tell the viewer to show all windows. This does not show our windows
// since our windows are embedded but it does do some extra setup for
// the windows and thus needs to be called.
viewer->Methods()->ShowAllWindows();
QMainWindow::show();
}
//
// Qt slots
//
// ****************************************************************************
// Method: SimpleVisApp::selectFile
//
// Programmer: Brad Whitlock
// Creation: Fri Nov 21 10:23:40 PST 2008
//
// Modifications:
// Kathleen Bonnell, Fri Oct 8 08:55:44 PDT 2010
// Make sure path separators are converted to native format.
//
// ****************************************************************************
void
SimpleVisApp::selectFile()
{
// Get a filename from the file dialog.
QString filename = QFileDialog::getOpenFileName(this,
tr("Open File"),
QDir::current().path(),
tr("Data files (*.silo *.vtk *.cgns *.nc *.h5 *.pdb *.visit)"));
filename = QDir::toNativeSeparators(filename);
openFile(filename);
}
void
SimpleVisApp::openFile(const QString &filename)
{
if(!filename.isEmpty())
{
// Open the file.
viewer->Methods()->OpenDatabase(filename.toStdString());
// Get the file's metadata and populate the variable list.
const avtDatabaseMetaData *md = viewer->GetMetaData(filename.toStdString());
if(md != 0)
{
variables->blockSignals(true);
for(int i = 0; i < md->GetNumScalars(); ++i)
variables->addItem(md->GetScalar(i)->name.c_str());
variables->setCurrentRow(0);
variables->blockSignals(false);
if(md->GetNumScalars() > 0)
{
variables->setEnabled(true);
plotTypeWidget->setEnabled(true);
contourWidget->setEnabled(plotType->checkedId() == 1);
// Add a plot of the first variable
changePlotType(plotType->checkedId());
}
scalarLabel->setEnabled(true);
variables->setEnabled(true);
}
else
resetWindow();
}
else
resetWindow();
}
void
SimpleVisApp::changeVariable(const QString &var)
{
viewer->Methods()->ChangeActivePlotsVar(var.toStdString());
}
void
SimpleVisApp::changeVariableAndUpdate(const QString &var)
{
changeVariable(var);
variables->blockSignals(true);
for(int i = 0; i < variables->count(); ++i)
{
if(variables->item(i)->text() == var)
{
variables->setCurrentRow(i);
break;
}
}
variables->blockSignals(false);
}
void
SimpleVisApp::changePlotType(int val)
{
if(variables->currentRow() == -1)
return;
// Determine the variable.
std::string var(variables->currentItem()->text().toStdString());
// Delete the active plots.
viewer->Methods()->DeleteActivePlots();
if(val == 0)
{
int Pseudocolor = viewer->GetPlotIndex("Pseudocolor");
viewer->Methods()->AddPlot(Pseudocolor, var);
}
else
{
int Contour = viewer->GetPlotIndex("Contour");
viewer->Methods()->AddPlot(Contour, var);
}
contourWidget->setEnabled(val == 1);
viewer->Methods()->DrawPlots();
}
void
SimpleVisApp::setNContours(int nc)
{
int Contour = viewer->GetPlotIndex("Contour");
AttributeSubject *contourAtts = viewer->DelayedState()->GetPlotAttributes(Contour);
if(contourAtts != 0)
{
contourAtts->SetValue("contourNLevels", nc);
contourAtts->Notify();
viewer->DelayedMethods()->SetPlotOptions(Contour);
}
}
void
SimpleVisApp::saveWindow()
{
// Set the output format to JPEG
SaveWindowAttributes *swa = viewer->State()->GetSaveWindowAttributes();
swa->SetFormat(SaveWindowAttributes::JPEG);
swa->SetScreenCapture(true);
// Save the window
viewer->Methods()->SaveWindow();
}
void
SimpleVisApp::openGUI()
{
stringVector args;
viewer->DelayedMethods()->OpenClient("GUI", viewer->GetVisItCommand(), args);
}
void
SimpleVisApp::execFile(int openClFile)
{
QString filename;
if (openClFile != 0)
{
filename = clfilename;
}
else
{
// Get a filename from the file dialog.
filename = QFileDialog::getOpenFileName(this,
tr("Open File"),
QDir::current().path(),
tr("command files (*.txt)"));
}
if(!filename.isEmpty())
{
if(cmd == NULL)
{
// Create the command parser.
cmd = new CommandParser(viewer);
connect(cmd, SIGNAL(openFile(const QString &)),
this, SLOT(openFile(const QString &)));
connect(cmd, SIGNAL(changeVariable(const QString &)),
this, SLOT(changeVariableAndUpdate(const QString &)));
connect(cmd, SIGNAL(changePlotType(int)),
this, SLOT(changePlotType(int)));
connect(cmd, SIGNAL(setNContours(int)),
this, SLOT(setNContours(int)));
connect(cmd, SIGNAL(saveWindow()),
this, SLOT(saveWindow()));
connect(cmd, SIGNAL(quitApp()),
this, SLOT(quitApp()));
}
cmd->ProcessCommands(filename);
}
}
|
473b21a2b5d4ab9239c08ffcb0f0360ed051d8d8
|
67305fcba68fdf469862aed2959ad1dd5b22a536
|
/rt-thread/components/libc/compilers/minilibc/sys/types.h
|
d3abc6bb388e1c41088c943f20716eebfd63d038
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
RT-Thread/IoT_Board
|
cdabf100a8d515fbcaa65ab0b72ec67acb0d2c9a
|
2d218a4e06f06dbb356ec00767904f91d00db7cc
|
refs/heads/master
| 2023-09-04T16:51:34.485240
| 2022-01-19T01:26:16
| 2022-01-19T01:26:16
| 161,133,933
| 344
| 238
|
Apache-2.0
| 2023-06-06T04:10:57
| 2018-12-10T07:21:46
|
C
|
UTF-8
|
C
| false
| false
| 1,036
|
h
|
types.h
|
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __TYPES_H__
#define __TYPES_H__
#include <rtconfig.h>
typedef long off_t;
#ifndef ARCH_CPU_64BIT
typedef unsigned int size_t;
typedef signed int ssize_t; /* Used for a count of bytes or an error indication. */
#else
typedef long unsigned int size_t;
typedef long signed int ssize_t; /* Used for a count of bytes or an error indication. */
#endif
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
typedef int mode_t;
typedef unsigned long clockid_t;
typedef int pid_t;
typedef int gid_t;
typedef int uid_t;
typedef int dev_t;
typedef int ino_t;
typedef int mode_t;
typedef int caddr_t;
typedef unsigned int wint_t;
typedef unsigned long useconds_t;
typedef unsigned long clock_t; /* clock() */
#ifndef NULL
#define NULL (0)
#endif
#define __u_char_defined
#endif
|
1a26981b0dadb0ec6a2f0788ea3ecc778328da9d
|
e1b4ba3ef71b3e3141bf17c35e7fc96607cc13b6
|
/timer-hacks/timer.c
|
241641880a412bdf3e06e32dcb3e8eb35193b00f
|
[] |
no_license
|
dougallj/applecpu
|
e5c24f9aa7e4b7f512d2f1f1f067b41aeca56039
|
0e6bc3f6038fa7b3959ab66b33ae25b707edc186
|
refs/heads/main
| 2023-07-25T18:45:12.921978
| 2023-07-13T11:00:10
| 2023-07-13T11:00:10
| 345,242,391
| 183
| 10
| null | null | null | null |
UTF-8
|
C
| false
| false
| 11,031
|
c
|
timer.c
|
#include <assert.h>
#include <dlfcn.h>
#include <getopt.h>
#include <libkern/OSCacheControl.h>
#include <pthread.h>
#include <ptrauth.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/sysctl.h>
#include <fcntl.h>
#define OUTER_ITS 64
#define AMX_START() \
__asm__ volatile( \
"nop \r\n nop \r\n nop \r\n .word (0x201000 | (17 << 5) | 0)" :: \
: "memory")
#define AMX_STOP() \
__asm__ volatile( \
"nop \r\n nop \r\n nop \r\n .word (0x201000 | (17 << 5) | 1)" :: \
: "memory")
#define SREG_PMCR0 "S3_1_c15_c0_0"
#define SREG_PMCR1 "S3_1_c15_c1_0"
#define SREG_PMESR0 "S3_1_c15_c5_0"
#define SREG_PMESR1 "S3_1_c15_c6_0"
#define SREG_PMC0 "S3_2_c15_c0_0"
#define SREG_PMC1 "S3_2_c15_c1_0"
#define SREG_PMC2 "S3_2_c15_c2_0"
#define SREG_PMC3 "S3_2_c15_c3_0"
#define SREG_PMC4 "S3_2_c15_c4_0"
#define SREG_PMC5 "S3_2_c15_c5_0"
#define SREG_PMC6 "S3_2_c15_c6_0"
#define SREG_PMC7 "S3_2_c15_c7_0"
#define SREG_PMC8 "S3_2_c15_c9_0"
#define SREG_PMC9 "S3_2_c15_c10_0"
#define SREG_WRITE(SR, V) \
__asm__ volatile("msr " SR ", %0 \r\n isb \r\n" : : "r"((uint64_t)V))
#define SREG_READ(SR) \
({ \
uint64_t VAL = 0; \
__asm__ volatile("isb \r\n mrs %0, " SR " \r\n isb \r\n" : "=r"(VAL)); \
VAL; \
})
struct file_data {
size_t size;
uint32_t *data;
};
static struct file_data load_file(char *filename) {
struct file_data result = { 0, NULL };
int fd = open(filename, O_RDONLY);
if (fd >= 0) {
size_t length = lseek(fd, 0, SEEK_END);
if (length) {
result.data = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
result.size = length;
}
close(fd);
}
return result;
}
static void set_sysctl(const char *name, uint64_t v) {
if (sysctlbyname(name, NULL, 0, &v, sizeof v)) {
printf("set_sysctl: sysctlbyname failed\n");
exit(1);
}
}
#define COUNTERS_COUNT 10
static uint64_t g_counters0[COUNTERS_COUNT];
static uint64_t g_counters1[COUNTERS_COUNT];
static void make_routine(uint32_t *ibuf, int unroll_count, int iter_count,
uint32_t *body, size_t body_icount, uint32_t *init,
size_t init_icount) {
pthread_jit_write_protect_np(0);
int o = 0;
// prologue
ibuf[o++] = 0xa9b47bfd; // stp x29, x30, [sp, #-0xC0]!
ibuf[o++] = 0xa9013ff0; // stp x16, x15, [sp, #0x10]
ibuf[o++] = 0xa90247f2; // stp x18, x17, [sp, #0x20]
ibuf[o++] = 0xa9034ff4; // stp x20, x19, [sp, #0x30]
ibuf[o++] = 0xa90457f6; // stp x22, x21, [sp, #0x40]
ibuf[o++] = 0xa9055ff8; // stp x24, x23, [sp, #0x50]
ibuf[o++] = 0xa90667fa; // stp x26, x25, [sp, #0x60]
ibuf[o++] = 0xa9076ffc; // stp x28, x27, [sp, #0x70]
ibuf[o++] = 0x6d083bef; // stp d15, d14, [sp, #0x80]
ibuf[o++] = 0x6d0933ed; // stp d13, d12, [sp, #0x90]
ibuf[o++] = 0x6d0a2beb; // stp d11, d10, [sp, #0xA0]
ibuf[o++] = 0x6d0b23e9; // stp d9, d8, [sp, #0xB0]
// prep
ibuf[o++] = 0x2a0003fc; // mov w28, w0
ibuf[o++] = 0xaa0103fb; // mov x27, x1
ibuf[o++] = 0xaa0203fd; // mov x29, x2
for (size_t i = 0; i < init_icount; i++) {
ibuf[o++] = init[i];
}
// enable
ibuf[o++] = 0xd519f01b; // msr S3_1_C15_C0_0, x27
ibuf[o++] = 0xd5033fdf; // isb
int start = o;
for (int unroll = 0; unroll < unroll_count; unroll++) {
for (size_t i = 0; i < body_icount; i++) {
ibuf[o++] = body[i];
}
}
if (iter_count > 1) {
// loop back to top
ibuf[o++] = 0xd100079c; // sub x28, x28, #1
int off = start - o;
assert(off < 0 && off > -0x40000);
ibuf[o++] = 0xb500001c | ((off & 0x7ffff) << 5); // cbnz x28
}
// disable
ibuf[o++] = 0xd519f01d; // msr S3_1_C15_C0_0, x29
ibuf[o++] = 0xd5033fdf; // isb
// epilogue
ibuf[o++] = 0xa9413ff0; // ldp x16, x15, [sp, #0x10]
ibuf[o++] = 0xa94247f2; // ldp x18, x17, [sp, #0x20]
ibuf[o++] = 0xa9434ff4; // ldp x20, x19, [sp, #0x30]
ibuf[o++] = 0xa94457f6; // ldp x22, x21, [sp, #0x40]
ibuf[o++] = 0xa9455ff8; // ldp x24, x23, [sp, #0x50]
ibuf[o++] = 0xa94667fa; // ldp x26, x25, [sp, #0x60]
ibuf[o++] = 0xa9476ffc; // ldp x28, x27, [sp, #0x70]
ibuf[o++] = 0x6d483bef; // ldp d15, d14, [sp, #0x80]
ibuf[o++] = 0x6d4933ed; // ldp d13, d12, [sp, #0x90]
ibuf[o++] = 0x6d4a2beb; // ldp d11, d10, [sp, #0xA0]
ibuf[o++] = 0x6d4b23e9; // ldp d9, d8, [sp, #0xB0]
ibuf[o++] = 0xa8cc7bfd; // ldp x29, x30, [sp], #0xC0
ibuf[o++] = 0xd65f03c0; // ret
#if 0
// clang timer.dump.s -c && objdump -d timer.dump.o
FILE *f = fopen("timer.dump.s", "wb");
if (f) {
for (int i = 0; i < o; i++) {
fprintf(f, ".word 0x%X\n", ibuf[i]);
}
fclose(f);
}
#endif
pthread_jit_write_protect_np(1);
sys_icache_invalidate(ibuf, o * 4);
}
static jmp_buf retry;
static void sighandler() {
printf("SIGILL\n");
longjmp(retry, 1);
}
static char memory[4 * 1024 * 1024];
static int get_current_core() { return SREG_READ("TPIDRRO_EL0") & 7; }
int main(int argc, char **argv) {
signal(SIGILL, sighandler);
assert(argc == 6);
#ifdef ICESTORM
pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
#else
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
#endif
struct file_data configs_file = load_file(argv[5]);
uint32_t *configs = configs_file.data;
size_t configs_size = configs_file.size;
struct file_data test_code_file = load_file(argv[1]);
uint32_t *test_code = test_code_file.data;
size_t test_code_size = test_code_file.size;
struct file_data init_code_file = load_file(argv[2]);
uint32_t *init_code = init_code_file.data;
size_t init_code_size = init_code_file.size;
void *mapping =
mmap(NULL, 0x400000 + ((test_code_size + init_code_size) & ~0xFFFF),
PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE | MAP_JIT,
-1, 0);
uint32_t *ibuf = (uint32_t *)mapping;
size_t unroll_count = atoi(argv[3]);
size_t iter_count = atoi(argv[4]);
make_routine(ibuf, unroll_count, iter_count, test_code, test_code_size / 4,
init_code, init_code_size / 4);
uint64_t (*routine)(uint64_t, uint64_t, uint64_t, void *, void *, void *,
void *) =
ptrauth_sign_unauthenticated((void *)ibuf, ptrauth_key_function_pointer,
0);
uint64_t sum_diffs[0x100];
uint64_t counts[0x100];
uint64_t results[0x100][OUTER_ITS];
for (int i = 0; i < 256; i++) {
sum_diffs[i] = 0;
counts[i] = 0;
}
for (int outer_i = 0; outer_i < OUTER_ITS; outer_i++) {
for (size_t config_index = 0; config_index < configs_size / 4;
config_index += 2) {
uint64_t end0, end1;
{
Lretry:
AMX_START();
// in case we migrate cores and lose control of PMCR
setjmp(retry);
int start_core = get_current_core();
#define ENABLE 0x3003400ff4ff
#define DISABLE 0x3000400ff403
set_sysctl("kern.pmcr0", 0x3003400ff4ff);
SREG_WRITE(SREG_PMESR0, configs[config_index]);
SREG_WRITE(SREG_PMESR1, configs[config_index + 1]);
SREG_WRITE(SREG_PMCR1, 0x3000003ff00);
SREG_WRITE(SREG_PMCR0, DISABLE);
g_counters0[0] = SREG_READ(SREG_PMC0);
g_counters0[1] = SREG_READ(SREG_PMC1);
SREG_WRITE(SREG_PMC2, 0);
SREG_WRITE(SREG_PMC3, 0);
SREG_WRITE(SREG_PMC4, 0);
SREG_WRITE(SREG_PMC5, 0);
SREG_WRITE(SREG_PMC6, 0);
SREG_WRITE(SREG_PMC7, 0);
SREG_WRITE(SREG_PMC8, 0);
SREG_WRITE(SREG_PMC9, 0);
routine(iter_count, ENABLE, DISABLE, &memory, &memory, &memory,
&memory);
g_counters1[0] = SREG_READ(SREG_PMC0);
g_counters1[1] = SREG_READ(SREG_PMC1);
g_counters1[2] = SREG_READ(SREG_PMC2);
g_counters1[3] = SREG_READ(SREG_PMC3);
g_counters1[4] = SREG_READ(SREG_PMC4);
g_counters1[5] = SREG_READ(SREG_PMC5);
g_counters1[6] = SREG_READ(SREG_PMC6);
g_counters1[7] = SREG_READ(SREG_PMC7);
g_counters1[8] = SREG_READ(SREG_PMC8);
g_counters1[9] = SREG_READ(SREG_PMC9);
end0 = SREG_READ(SREG_PMESR0);
end1 = SREG_READ(SREG_PMESR1);
SREG_WRITE(SREG_PMESR0, 0);
SREG_WRITE(SREG_PMESR1, 0);
int end_core = get_current_core();
AMX_STOP();
if (start_core != end_core || end0 != configs[config_index] ||
end1 != configs[config_index + 1]) {
// yes, obviously this is a terrible hack that doesn't really fix
// things.
printf("context switch\n");
goto Lretry;
}
#ifdef ICESTORM
if (start_core >= 4) {
goto Lretry;
}
#else
if (start_core < 4) {
goto Lretry;
}
#endif
}
if (configs[config_index] == configs[config_index + 1]) {
int mask = 0;
int good = 1;
uint64_t value = 0;
for (int v = 2; v < COUNTERS_COUNT; v++) {
if (g_counters1[v]) {
if (value && g_counters1[v] != value) {
good = 0;
} else {
value = g_counters1[v];
}
mask |= (1 << v);
}
}
int event = configs[config_index] & 0xFF;
if (counts[event] >= OUTER_ITS) {
printf("error\n");
exit(1);
}
results[event][counts[event]++] = value;
sum_diffs[event] += value;
} else {
uint64_t config = (((uint64_t)configs[config_index + 1]) << 32) |
configs[config_index];
for (int i = 0; i < 8; i++) {
int event = (config >> (8 * i)) & 0xFF;
if (!event)
continue;
uint64_t value = g_counters1[i + 2];
if (counts[event] >= OUTER_ITS) {
printf("error\n");
exit(1);
}
results[event][counts[event]++] = value;
sum_diffs[event] += value;
}
}
}
}
int first = 1;
printf("{\n");
for (int event = 1; event < 0x100; event++) {
if (sum_diffs[event] == 0)
continue;
if (counts[event] != OUTER_ITS) {
printf("error at event %d\n", event);
exit(1);
}
if (first) {
first = 0;
} else {
printf(",\n");
}
printf(" \"%02x\": [", event);
for (size_t i = 0; i < counts[event]; i++) {
if (i != 0)
printf(", ");
printf("%llu", results[event][i]);
}
printf("]");
}
printf("\n}\n");
return 0;
}
|
3e7c7864e82f6fa87e32574753aec86fa12cf38d
|
17d7357e5c5130ace022b3c9d9f98e7b13dda0ca
|
/src/meta/fsb5_streamfile.h
|
1917514891d32fd5b4baea0ba07e48524dd36780
|
[
"ISC",
"LicenseRef-scancode-public-domain"
] |
permissive
|
vgmstream/vgmstream
|
4a7747bb75ff513f8fc8cc26f31d6e3a4150bc43
|
883d796d4b63c42810586e9f1ffbdcdd28c73ef5
|
refs/heads/master
| 2023-09-04T16:14:38.136915
| 2023-09-02T18:06:38
| 2023-09-02T18:06:38
| 5,591,410
| 762
| 137
|
NOASSERTION
| 2023-09-10T22:58:26
| 2012-08-28T20:08:24
|
C
|
UTF-8
|
C
| false
| false
| 676
|
h
|
fsb5_streamfile.h
|
#ifndef _FSB5_STREAMFILE_H_
#define _FSB5_STREAMFILE_H_
#include "deblock_streamfile.h"
static STREAMFILE* setup_fsb5_streamfile(STREAMFILE* sf, off_t stream_start, size_t stream_size, int stream_count, int stream_number, size_t interleave) {
STREAMFILE* new_sf = NULL;
deblock_config_t cfg = {0};
cfg.stream_start = stream_start;
cfg.stream_size = stream_size;
cfg.chunk_size = interleave;
cfg.step_start = stream_number;
cfg.step_count = stream_count;
/* setup sf */
new_sf = open_wrap_streamfile(sf);
new_sf = open_io_deblock_streamfile_f(new_sf, &cfg);
return new_sf;
}
#endif /* _FSB5_STREAMFILE_H_ */
|
6c217a7c95f2fad72f3fee55cc0bd07c97dd744d
|
c72e8e7a91acfc92d6cbd02dfbbcc20f00aab63f
|
/src/command/repo/create.c
|
3b4d64f7ea3d30adce959812129e673fe1653d19
|
[
"MIT"
] |
permissive
|
pgbackrest/pgbackrest
|
83b3760b0faaaf7a0da4a54caeaa2231d6144704
|
e3fcd8cd9e0be42a32fc4cbd2ae3db2c072eabcd
|
refs/heads/main
| 2023-09-03T22:27:01.317021
| 2023-08-31T20:36:52
| 2023-08-31T20:36:52
| 14,313,288
| 1,826
| 211
|
NOASSERTION
| 2023-09-14T13:56:30
| 2013-11-11T21:08:39
|
C
|
UTF-8
|
C
| false
| false
| 2,244
|
c
|
create.c
|
/***********************************************************************************************************************************
Repository Create Command
***********************************************************************************************************************************/
#include "build.auto.h"
#include "common/debug.h"
#include "common/log.h"
#include "common/memContext.h"
#include "common/type/json.h"
#include "config/config.h"
#include "storage/azure/storage.intern.h"
#include "storage/gcs/storage.intern.h"
#include "storage/helper.h"
#include "storage/s3/storage.intern.h"
/**********************************************************************************************************************************/
FN_EXTERN void
cmdRepoCreate(void)
{
FUNCTION_LOG_VOID(logLevelDebug);
MEM_CONTEXT_TEMP_BEGIN()
{
switch (storageType(storageRepo()))
{
case STORAGE_AZURE_TYPE:
{
storageAzureRequestP(
(StorageAzure *)storageDriver(storageRepoWrite()), HTTP_VERB_PUT_STR,
.query = httpQueryAdd(httpQueryNewP(), AZURE_QUERY_RESTYPE_STR, AZURE_QUERY_VALUE_CONTAINER_STR));
break;
}
case STORAGE_GCS_TYPE:
{
storageGcsRequestP(
(StorageGcs *)storageDriver(storageRepoWrite()), HTTP_VERB_POST_STR, .noBucket = true,
.content = BUFSTR(
jsonWriteResult(
jsonWriteObjectEnd(
jsonWriteStr(
jsonWriteKeyZ(
jsonWriteObjectBegin(
jsonWriteNewP()), GCS_JSON_NAME), cfgOptionStr(cfgOptRepoGcsBucket))))));
break;
}
case STORAGE_S3_TYPE:
storageS3RequestP((StorageS3 *)storageDriver(storageRepoWrite()), HTTP_VERB_PUT_STR, FSLASH_STR);
break;
// Other storage types do not require the repo to be created
default:
break;
}
}
MEM_CONTEXT_TEMP_END();
FUNCTION_LOG_RETURN_VOID();
}
|
de2814cb1254b67a8d96fdb3292a85dc32a4f952
|
25c64fb97b7cdb30ec1b6ddd2acf9a755fc33adf
|
/test/testparse.c
|
2b38332687ee7b2f2cc88db63a3d91ba59bb6906
|
[
"MIT"
] |
permissive
|
arminbiere/kissat
|
386c1cfadf43562d36fccc47064c95296c9b812f
|
630d64d4d63c2816fc79a1a0340286b39677e97d
|
refs/heads/master
| 2023-09-04T01:39:44.293487
| 2023-06-24T15:51:43
| 2023-06-24T15:51:43
| 267,257,286
| 350
| 63
|
MIT
| 2022-06-23T12:15:24
| 2020-05-27T07:57:59
|
C
|
UTF-8
|
C
| false
| false
| 4,577
|
c
|
testparse.c
|
#include "../src/file.h"
#include "../src/parse.h"
#include <inttypes.h>
#include "test.h"
static bool test_parse (bool expect_parse_error, unsigned strict,
const char *path) {
const char *type;
switch (strict) {
default:
case RELAXED_PARSING:
type = "relaxed";
break;
case NORMAL_PARSING:
type = "normal";
break;
case PEDANTIC_PARSING:
type = "pedantic";
break;
}
tissat_verbose ("Parsing %svalid '%s' in '%s' mode.",
expect_parse_error ? "in" : "", path, type);
kissat *solver = kissat_init ();
tissat_init_solver (solver);
file file;
if (!kissat_open_to_read_file (&file, path))
FATAL ("could not open '%s' for reading", path);
uint64_t lineno;
int max_var;
const char *error =
kissat_parse_dimacs (solver, strict, &file, &lineno, &max_var);
if (expect_parse_error) {
if (!error)
FATAL ("%s parsing '%s' succeeded unexpectedly", type, path);
tissat_verbose ("%s:%" PRIu64 ": %s", path, lineno, error);
} else if (!expect_parse_error && error) {
FATAL ("%s parsing failed unexpectedly: %s:%" PRIu64 ": %s", type, path,
lineno, error);
tissat_verbose ("found maximum variable '%d' in '%s'", max_var, path);
}
kissat_close_file (&file);
kissat_release (solver);
return false;
}
static void test_parse_errors (void) {
#define PARSE(STRICT, NAME) \
do { \
const char *path = "../test/parse/" #NAME; \
bool expect_error; \
if (STRICT == RELAXED_PARSING) \
expect_error = true; \
else if (STRICT == NORMAL_PARSING) \
expect_error = \
(strict == NORMAL_PARSING || strict == PEDANTIC_PARSING); \
else \
assert (STRICT == PEDANTIC_PARSING), \
expect_error = (strict == PEDANTIC_PARSING); \
test_parse (expect_error, strict, path); \
} while (0)
for (strictness strict = RELAXED_PARSING; strict <= PEDANTIC_PARSING;
strict++) {
PARSE (0, emptyfile);
PARSE (0, onlycomments);
PARSE (0, eofheadercomment);
PARSE (0, eofinheaderafterc);
PARSE (0, eofbeforeheader);
PARSE (0, eofinheaderafterc);
PARSE (0, nonlaftercrafterheadliner);
PARSE (0, onlycr);
PARSE (0, emptyline);
PARSE (2, emptyheaderline);
PARSE (2, emptyheadercrnl);
PARSE (0, embeddedcrmissingnl);
PARSE (0, nonlafterinvalidembeddedoption);
PARSE (0, nocnorp);
PARSE (0, nospaceafterp);
PARSE (0, nlafterp);
PARSE (0, nocafterpspace);
PARSE (0, nonafterc);
PARSE (0, nofaftern);
PARSE (0, nospaceafterf);
PARSE (0, nodigitafterpcnfspace);
PARSE (0, toolargevars1);
PARSE (0, toolargevars2);
PARSE (0, eofinmaxvar);
PARSE (0, onlycraftervars);
PARSE (0, nlaftervars);
PARSE (0, nospaceaftervars);
PARSE (0, nodigitaftervarsnspace);
PARSE (0, toolargeclauses1);
PARSE (0, toolargeclauses2);
PARSE (0, nonlaftercrafterheaderline);
PARSE (0, eofinclauses);
PARSE (0, nonlafterheaderline);
PARSE (0, othercharafterheaderline);
PARSE (0, nonlaftercrinbody);
PARSE (2, eofbodycomment);
PARSE (0, eofafterlit);
PARSE (2, eofafterzero);
PARSE (0, signeof);
PARSE (0, nlaftersign);
PARSE (0, nodigitaftersign);
PARSE (0, zeroaftersign);
PARSE (0, anainsteadoflit);
PARSE (1, toomanyclauses);
PARSE (0, varidxtoolarge1);
PARSE (0, varidxtoolarge2);
PARSE (0, nonlaftercrafterlit);
PARSE (0, nowsafterlit);
PARSE (1, varidxexceeded);
PARSE (0, notrailingzero);
PARSE (1, oneclausemissing);
PARSE (1, twoclausesmissing);
PARSE (2, tabs);
PARSE (2, headerspaces);
PARSE (2, eofincommmentafterliteral);
}
#undef PARSE
}
static void test_parse_coverage (void) {
#define PARSE(STRICT, NAME) \
do { \
if (!strict && STRICT) \
break; \
if (strict == 1 && STRICT == 2) \
break; \
const char *path = "../test/parse/" #NAME; \
test_parse (false, strict, path); \
} while (0)
for (unsigned strict = 0; strict <= 2; strict++) {
PARSE (0, crnl);
PARSE (0, signedunit);
PARSE (0, comments);
PARSE (0, invalidembeddedoption);
PARSE (0, embeddedoptiocrnl);
PARSE (0, embeddedoptioneqmissing);
PARSE (0, embeddedoptionametoolong);
PARSE (0, embeddednegative);
PARSE (0, embeddedcoverage);
PARSE (0, crnlfile);
}
#undef PARSE
}
void tissat_schedule_parse (void) {
if (tissat_found_test_directory)
SCHEDULE_FUNCTION (test_parse_errors);
if (tissat_found_test_directory)
SCHEDULE_FUNCTION (test_parse_coverage);
}
|
0304fdfc8f4d3fd06010754f801dd772a312a64d
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/Runtime/Online/HTTP/Public/PlatformHttp.h
|
563c5616d9fe58ae0d1e2e41579a7332bd221cef
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C
| false
| false
| 623
|
h
|
PlatformHttp.h
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#if PLATFORM_WINDOWS
#include "Windows/WindowsPlatformHttp.h"
#elif PLATFORM_PS4
#include "PS4/PS4PlatformHttp.h"
#elif PLATFORM_XBOXONE
#include "XboxOne/XboxOneHttp.h"
#elif PLATFORM_MAC
#include "Apple/ApplePlatformHttp.h"
#elif PLATFORM_IOS
#include "Apple/ApplePlatformHttp.h"
#elif PLATFORM_ANDROID
#include "Android/AndroidHttp.h"
#elif PLATFORM_HTML5
#include "HTML5/HTML5PlatformHttp.h"
#elif PLATFORM_LINUX
#include "Linux/LinuxPlatformHttp.h"
#elif PLATFORM_SWITCH
#include "Switch/SwitchPlatformHttp.h"
#endif
|
8a5826e48efcbfead0ec8c4bafe980b9759a820f
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/eigen3/src/Eigen/src/OrderingMethods/InternalHeaderCheck.h
|
713c447947b3b4e164d110a572a731835f9d4bc9
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"Minpack"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 156
|
h
|
InternalHeaderCheck.h
|
#ifndef EIGEN_ORDERINGMETHODS_MODULE_H
#error "Please include Eigen/OrderingMethods instead of including headers inside the src directory directly."
#endif
|
7e1f86e8fdbb0740b3c60a8199a3caf191d89802
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGPP/MUON/lite/MakeTrend.C
|
7a69ab88bab71eeecb7b063ebcd1095b046ee3a8
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 13,418
|
c
|
MakeTrend.C
|
#if !defined(__CINT__) || defined(__MAKECINT__)
// ROOT includes
#include "TFile.h"
#include "TGrid.h"
#include "TString.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TKey.h"
#include "TTree.h"
#include "TParameter.h"
#include "TFileMerger.h"
#include "THashList.h"
// Aliroot includes
#include "AliAnalysisManager.h"
#include "AliAnalysisAlien.h"
#include "AliESDInputHandler.h"
#include "AliCounterCollection.h"
#define COMPILEMACRO
#endif
//_____________________________________________________________________________
void LoadLibs()
{
// gSystem->Load("libTree");
// gSystem->Load("libGeom");
// gSystem->Load("libVMC");
// gSystem->Load("libPhysics");
// gSystem->Load("libProof");
//
// gSystem->Load("libANALYSIS");
// gSystem->Load("libOADB");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libCORRFW");
// gSystem->Load("libPWGmuon");
TString libName = "libPWGPPMUONlite";
TString getLib = gSystem->GetLibraries(libName.Data(),"",kFALSE);
if ( getLib.IsNull() ) gSystem->Load(libName.Data());
}
//_____________________________________________________________________________
AliAnalysisAlien* CreateAlienHandler()
{
AliAnalysisAlien *plugin = new AliAnalysisAlien();
// Set the run mode
plugin->SetRunMode("terminate");
// Declare all libraries
plugin->SetAdditionalLibs("libCORRFW.so libPWGHFbase.so libPWGmuon.so libPWGPPMUONlite.so");
plugin->SetAdditionalRootLibs("libXMLParser.so libGui.so libProofPlayer.so");
plugin->AddIncludePath("-I.");
plugin->AddIncludePath("-I$ALICE_PHYSICS/PWGPP/MUON/lite");
return plugin;
}
enum {
trackQA = 1 << 0,
trigQA = 1 << 1
};
//_____________________________________________________________________________
void terminateQA ( TString outfilename = "QAresults.root", Bool_t isMC = kFALSE, Bool_t usePhysicsSelection = kTRUE, UInt_t mask = (trackQA|trigQA), UInt_t force = (trackQA|trigQA) )
{
//
// Run terminate on QA output
// Terminate is skipped if it was already run during the production
// Unless the "force" option is specified
//
LoadLibs();
AliAnalysisAlien* alienHandler = CreateAlienHandler();
AliAnalysisManager* mgr = new AliAnalysisManager("testAnalysis");
mgr->SetCommonFileName(outfilename.Data());
mgr->SetGridHandler(alienHandler);
// Needed to the manager (but not used in terminate mode)
AliESDInputHandler* esdH = new AliESDInputHandler();
esdH->SetReadFriends(kFALSE);
mgr->SetInputEventHandler(esdH);
TString trigOutName = "trigChEff_ANY_Apt_allTrig.root";
if ( ( force & trigQA ) == 0 ) {
if ( gSystem->AccessPathName(trigOutName) == 0 ) {
printf("Terminate already done for trigger. Skip\n");
mask &= ~trigQA;
}
}
if ( ( force & trackQA ) == 0 ) {
TFile* file = TFile::Open(outfilename.Data());
TKey* key = file->FindKeyAny("general2");
if ( key ) {
printf("Terminate already done for tracker. Skip\n");
mask &= ~trackQA;
}
delete file;
}
if ( mask == 0 ) return;
#ifndef COMPILEMACRO
if ( mask & trigQA ) {
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/macros/AddTaskMTRchamberEfficiency.C");
AliAnalysisTaskTrigChEff* trigChEffTask = AddTaskMTRchamberEfficiency(isMC);
TString physSelName = "PhysSelPass";
if ( ! usePhysicsSelection ) physSelName += ",PhysSelReject";
trigChEffTask->SetTerminateOptions(physSelName,"ANY","-5_105",Form("FORCEBATCH NoSelMatchApt FromTrg %s?%s?ANY?-5_105?NoSelMatchAptFromTrg",trigOutName.Data(),physSelName.Data()));
}
if ( mask & trackQA ) {
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/PilotTrain/AddTaskMuonQA.C");
AliAnalysisTaskMuonQA* muonQATask = AddTaskMuonQA(usePhysicsSelection);
}
#endif
// // Check if terminate was already performed
// if ( ! force ) {
// TObject* paramContainer = mgr->GetParamOutputs()->At(0);
// if ( paramContainer ) {
// TFile* file = TFile::Open(outfilename);
// if ( file->FindObjectAny(paramContainer->GetName() ) ) {
// printf("\nTerminate was already executed!\n");
// printf("Nothing to be done\n");
// file->Close();
// return;
// }
// file->Close();
// }
// }
if ( ! mgr->InitAnalysis()) {
printf("Fatal: Cannot initialize analysis\n");
return;
}
mgr->PrintStatus();
mgr->StartAnalysis("grid terminate");
if ( ! gSystem->AccessPathName("outputs_valid") ) gSystem->Exec("rm outputs_valid");
}
//_____________________________________________________________________________
TString GetFullPath ( TString filename )
{
if ( filename.BeginsWith("alien://") ) return filename;
TString dirName = gSystem->DirName(filename);
TString baseName = gSystem->BaseName(filename);
TString currDir = gSystem->pwd();
gSystem->cd(dirName);
TString fullDir = gSystem->pwd();
gSystem->cd(currDir);
TString fullPath = fullDir.Data();
if ( ! fullDir.EndsWith("/") ) fullPath.Append("/");
fullPath += baseName;
return fullPath;
}
//_____________________________________________________________________________
TString GetBaseName ( TString filename )
{
TString baseName = gSystem->BaseName(filename);
Int_t idx = baseName.Index("#");
if ( idx > 0 ) baseName.Remove(0,idx+1);
return baseName;
}
//_____________________________________________________________________________
void CopyDir(TDirectory *source) {
//copy all objects and subdirs of directory source as a subdir of the current directory
TDirectory *savdir = gDirectory;
TDirectory *adir = savdir->mkdir(source->GetName());
adir->cd();
//loop on all entries of this directory
TKey *key;
TIter nextkey(source->GetListOfKeys());
while ((key = (TKey*)nextkey())) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom(TDirectory::Class())) {
source->cd(key->GetName());
TDirectory *subdir = gDirectory;
adir->cd();
CopyDir(subdir);
adir->cd();
} else if (cl->InheritsFrom(TTree::Class())) {
TTree *T = (TTree*)source->Get(key->GetName());
adir->cd();
TTree *newT = T->CloneTree(-1,"fast");
newT->Write();
} else {
source->cd();
TObject *obj = key->ReadObj();
adir->cd();
obj->Write(obj->GetName(),TObject::kSingleKey);
delete obj;
}
}
adir->SaveSelf(kTRUE);
savdir->cd();
}
//_____________________________________________________________________________
UInt_t GetQAInfo ( const char* qaFileName, TString dirNames = "MUON_QA MTR_ChamberEffMap MUON.TrigEfficiencyMap MUON.TriggerEfficiencyMap" )
{
LoadLibs();
UInt_t info = 0;
TString outFilename = GetBaseName(qaFileName);
TString inFullPath = GetFullPath(qaFileName);
TString outFullPath = GetFullPath(outFilename);
if ( inFullPath == outFullPath ) {
printf("Warning: input and output are same file!\n");
return info;
}
if ( inFullPath.BeginsWith("alien") && ! gGrid ) TGrid::Connect("alien://");
TObjArray* dirList = dirNames.Tokenize(" ");
TFile* inFile = TFile::Open(qaFileName);
if ( ! inFile ) {
// This might happen when checking for QAresults_outer.root
// when an input QAresults_barrel.root is provided
printf("Warning: file %s cannot be opened\n",qaFileName);
return info;
}
TFile* outFile = TFile::Open(outFilename,"RECREATE");
TIter next(dirList);
TObjString* objStr = 0x0;
while ( (objStr=static_cast<TObjString*>(next())) ) {
inFile->cd();
TString currDir = objStr->String();
TObject* obj = inFile->Get(currDir.Data());
if ( ! obj ) continue;
if ( currDir == "MUON_QA" ) info |= trackQA;
else info |= trigQA;
outFile->cd();
CopyDir(static_cast<TDirectory*>(obj));
}
delete outFile;
delete inFile;
delete dirList;
return info;
}
//_____________________________________________________________________________
Bool_t CheckMergedOverlap ( TString fileList )
{
LoadLibs();
TObjArray* arr = fileList.Tokenize(" ");
THashList triggerList;
triggerList.SetOwner();
Bool_t hasOverlap = kFALSE;
for ( Int_t iarr=0; iarr<arr->GetEntries(); iarr++ ) {
TFile* file = TFile::Open(arr->At(iarr)->GetName());
AliCounterCollection* eventCounters = (AliCounterCollection*)file->FindObjectAny("eventCounters");
if ( eventCounters ) {
TString listFromContainer = eventCounters->GetKeyWords("trigger");
TObjArray* trigArr = listFromContainer.Tokenize(",");
for ( Int_t itrig=0; itrig<trigArr->GetEntries(); itrig++ ) {
TString currTrig = trigArr->At(itrig)->GetName();
if ( triggerList.FindObject(currTrig.Data()) ) {
if ( currTrig != "ANY" ) {
printf("Warning: duplicated trigger %s\n", currTrig.Data());
hasOverlap = kTRUE;
}
}
else triggerList.Add(new TObjString(currTrig));
}
delete trigArr;
}
delete file;
}
delete arr;
return hasOverlap;
}
//_____________________________________________________________________________
Bool_t GetMergedQAInfo ( TString fileList, TString outFilename = "QAresults.root" )
{
LoadLibs();
TObjArray* arr = fileList.Tokenize(" ");
TFileMerger fm;
fm.OutputFile(outFilename.Data());
for ( Int_t iarr=0; iarr<arr->GetEntries(); iarr++ ) {
fm.AddFile(arr->At(iarr)->GetName());
}
delete arr;
return fm.Merge();
}
//_____________________________________________________________________________
Bool_t AddTreeVariable ( TList& parList, const char* varName, char varType, Float_t val )
{
if ( varType == 'D' ) varType = 'F';
TString parName = Form("%s/%c",varName,varType);
if ( varType == 'F' ) {
parList.Add(new TParameter<float>(parName,val));
}
else if ( varType == 'I' ) {
parList.Add(new TParameter<int>(parName,(Int_t)val));
}
else {
printf("Error: variable type %c not accepted", varType);
return kFALSE;
}
return kTRUE;
}
//_____________________________________________________________________________
void FillTree ( TTree* tree, TList &parList )
{
Int_t nVars = parList.GetEntries();
TArrayI varInt(nVars);
TArrayF varFloat(nVars);
for ( Int_t ivar=0; ivar<nVars; ivar++ ) {
TObject* obj = parList.At(ivar);
TString varName = obj->GetName();
TString branchName = varName;
branchName.Remove(varName.Length()-2);
if ( varName.EndsWith("F") ) {
varFloat[ivar] = ((TParameter<float>*)obj)->GetVal();
tree->Branch(branchName.Data(),&varFloat[ivar],varName.Data());
}
else if ( varName.EndsWith("I") ) {
varInt[ivar] = (Int_t)((TParameter<int>*)obj)->GetVal();
tree->Branch(branchName.Data(),&varInt[ivar],varName.Data());
}
}
tree->Fill();
}
//_____________________________________________________________________________
void AddTrigVars ( TString filename, TList &parList )
{
TString trigOutName = "trigChEff_ANY_Apt_allTrig.root";
if ( gSystem->AccessPathName(trigOutName.Data()) ) trigOutName = filename;
TFile* file = TFile::Open(filename.Data());
TList* inList = (TList*)file->FindObjectAny("triggerChamberEff");
TString hChNames[] = {"bendPlaneCountChamber","nonBendPlaneCountChamber","allTracksCountChamber"};
Int_t nHistos = sizeof(hChNames)/sizeof(hChNames[0]);
for ( Int_t ihisto=0; ihisto<nHistos; ihisto++ ) {
TH1* histo = (TH1*)inList->FindObject(hChNames[ihisto].Data());
for ( Int_t ibin=1; ibin<=4; ibin++ ) {
Double_t currVal = ( histo ) ? histo->GetBinContent(ibin) : 0.;
AddTreeVariable(parList, Form("%s%i",hChNames[ihisto].Data(),ibin),'F',currVal);
}
}
delete file;
}
//_____________________________________________________________________________
void MakeTrend ( const char* qaFile, Int_t runNumber, Bool_t isMC = kFALSE, Bool_t usePhysicsSelection = kTRUE, UInt_t mask = (trackQA|trigQA) )
{
UInt_t info = GetQAInfo(qaFile);
if ( info == 0 ) return;
TString baseFilename = "QAresults.root";
TString inFilename = GetBaseName(qaFile);
UInt_t forceTerminate = 0;
if ( inFilename.Contains("barrel") ) {
TString outerInFilename(qaFile);
outerInFilename.ReplaceAll("barrel","outer");
UInt_t outerInfo = GetQAInfo(outerInFilename);
if ( outerInfo ) {
// Merge outer and barrel
TString fileList = GetBaseName(outerInFilename);
fileList += " " + inFilename;
Bool_t isMergedOk = GetMergedQAInfo(fileList,baseFilename);
if ( isMergedOk ) {
printf("Merged files: %s => %s\n",fileList.Data(),baseFilename.Data());
CheckMergedOverlap(fileList);
gSystem->Exec(Form("rm %s",fileList.Data())); // Remove QAresults_barrel and outer
forceTerminate = info; // Re-do terminate when merging barrel and outer
}
}
}
if ( inFilename != baseFilename && gSystem->AccessPathName(baseFilename) ) {
gSystem->Exec(Form("mv -v %s %s",inFilename.Data(),baseFilename.Data()));
}
UInt_t checkedMask = mask&info;
terminateQA(baseFilename,isMC,usePhysicsSelection,checkedMask,forceTerminate);
TList parList;
parList.SetOwner();
AddTreeVariable(parList, "run", 'I', runNumber);
// function for trigger
if ( checkedMask & trigQA ) AddTrigVars(baseFilename.Data(),parList);
TFile* outFile = TFile::Open("trending.root","RECREATE");
TTree* tree = new TTree("trending","trending");
FillTree(tree, parList);
tree->Write();
delete outFile;
}
|
3a8b16db76ca33b4836a26dcd1bde6996a120a74
|
6c08b0a957d79fc6ee9ae4d1ba65327b43842056
|
/testdata/invalid_btf_map_init.c
|
8938d2ebe0d637e676d874c3bd3f4c1e079ef83c
|
[
"MIT"
] |
permissive
|
cilium/ebpf
|
7bd32b93598b9cdf8e78b4d1e8585ff30f158c68
|
01ebd4c1e2b9f8b3dd4fd2382aa1092c3c9bfc9d
|
refs/heads/main
| 2023-08-31T00:46:07.573666
| 2023-08-14T15:34:25
| 2023-08-14T15:34:25
| 206,649,463
| 4,889
| 587
|
MIT
| 2023-09-14T15:45:40
| 2019-09-05T20:13:28
|
Go
|
UTF-8
|
C
| false
| false
| 419
|
c
|
invalid_btf_map_init.c
|
/* This file excercises the ELF loader. It is not a valid BPF program. */
#include "common.h"
#if __clang_major__ >= 9
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__type(key, uint32_t);
__type(value, uint64_t);
__uint(max_entries, 1);
} hash_map __section(".maps") = {
/* This forces a non-zero byte into the .maps section. */
.key = (void *)1,
};
#else
#error This file has to be compiled with clang >= 9
#endif
|
687383ee03db68fe3a02c8455b705867cfbd2133
|
3cc53333f5cc7daf8e9e107432ffcf3176ec18ef
|
/examples/c/test_capi.c
|
98842bb9cf5a4df271665c46c7e19a99750ecb63
|
[
"MIT"
] |
permissive
|
Z3Prover/z3
|
86449330d4083744d33e7d81f67ec41e7134a436
|
4d9af7848dcbb51293ba3002875b3e63c4c5733b
|
refs/heads/master
| 2023-09-05T19:43:50.039168
| 2023-09-03T22:27:37
| 2023-09-03T22:27:37
| 32,944,298
| 9,613
| 1,812
|
NOASSERTION
| 2023-09-12T07:09:02
| 2015-03-26T18:16:07
|
C++
|
UTF-8
|
C
| false
| false
| 93,153
|
c
|
test_capi.c
|
/*++
Copyright (c) 2015 Microsoft Corporation
--*/
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
#include<memory.h>
#include<setjmp.h>
#include<z3.h>
#define LOG_Z3_CALLS
#ifdef LOG_Z3_CALLS
#define LOG_MSG(msg) Z3_append_log(msg)
#else
#define LOG_MSG(msg) ((void)0)
#endif
/**
\defgroup capi_ex C API examples
*/
/**@{*/
/**
@name Auxiliary Functions
*/
/**@{*/
/**
\brief exit gracefully in case of error.
*/
void exitf(const char* message)
{
fprintf(stderr,"BUG: %s.\n", message);
exit(1);
}
/**
\brief exit if unreachable code was reached.
*/
void unreachable()
{
exitf("unreachable code was reached");
}
/**
\brief Simpler error handler.
*/
void error_handler(Z3_context c, Z3_error_code e)
{
printf("Error code: %d\n", e);
exitf("incorrect use of Z3");
}
static jmp_buf g_catch_buffer;
/**
\brief Low tech exceptions.
In high-level programming languages, an error handler can throw an exception.
*/
void throw_z3_error(Z3_context c, Z3_error_code e)
{
longjmp(g_catch_buffer, e);
}
/**
\brief Error handling that depends on checking an error code on the context.
*/
void nothrow_z3_error(Z3_context c, Z3_error_code e) {
// no-op
}
/**
\brief Create a logical context.
Enable model construction. Other configuration parameters can be passed in the cfg variable.
Also enable tracing to stderr and register custom error handler.
*/
Z3_context mk_context_custom(Z3_config cfg, Z3_error_handler err)
{
Z3_context ctx;
Z3_set_param_value(cfg, "model", "true");
ctx = Z3_mk_context(cfg);
Z3_set_error_handler(ctx, err);
return ctx;
}
Z3_solver mk_solver(Z3_context ctx)
{
Z3_solver s = Z3_mk_solver(ctx);
Z3_solver_inc_ref(ctx, s);
return s;
}
void del_solver(Z3_context ctx, Z3_solver s)
{
Z3_solver_dec_ref(ctx, s);
}
/**
\brief Create a logical context.
Enable model construction only.
Also enable tracing to stderr and register standard error handler.
*/
Z3_context mk_context()
{
Z3_config cfg;
Z3_context ctx;
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, error_handler);
Z3_del_config(cfg);
return ctx;
}
/**
\brief Create a logical context.
Enable fine-grained proof construction.
Enable model construction.
Also enable tracing to stderr and register standard error handler.
*/
Z3_context mk_proof_context() {
Z3_config cfg = Z3_mk_config();
Z3_context ctx;
Z3_set_param_value(cfg, "proof", "true");
ctx = mk_context_custom(cfg, throw_z3_error);
Z3_del_config(cfg);
return ctx;
}
/**
\brief Create a variable using the given name and type.
*/
Z3_ast mk_var(Z3_context ctx, const char * name, Z3_sort ty)
{
Z3_symbol s = Z3_mk_string_symbol(ctx, name);
return Z3_mk_const(ctx, s, ty);
}
/**
\brief Create a boolean variable using the given name.
*/
Z3_ast mk_bool_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_bool_sort(ctx);
return mk_var(ctx, name, ty);
}
/**
\brief Create an integer variable using the given name.
*/
Z3_ast mk_int_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_int_sort(ctx);
return mk_var(ctx, name, ty);
}
/**
\brief Create a Z3 integer node using a C int.
*/
Z3_ast mk_int(Z3_context ctx, int v)
{
Z3_sort ty = Z3_mk_int_sort(ctx);
return Z3_mk_int(ctx, v, ty);
}
/**
\brief Create a real variable using the given name.
*/
Z3_ast mk_real_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_real_sort(ctx);
return mk_var(ctx, name, ty);
}
/**
\brief Create the unary function application: <tt>(f x)</tt>.
*/
Z3_ast mk_unary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x)
{
Z3_ast args[1] = {x};
return Z3_mk_app(ctx, f, 1, args);
}
/**
\brief Create the binary function application: <tt>(f x y)</tt>.
*/
Z3_ast mk_binary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x, Z3_ast y)
{
Z3_ast args[2] = {x, y};
return Z3_mk_app(ctx, f, 2, args);
}
/**
\brief Check whether the logical context is satisfiable, and compare the result with the expected result.
If the context is satisfiable, then display the model.
*/
void check(Z3_context ctx, Z3_solver s, Z3_lbool expected_result)
{
Z3_model m = 0;
Z3_lbool result = Z3_solver_check(ctx, s);
switch (result) {
case Z3_L_FALSE:
printf("unsat\n");
break;
case Z3_L_UNDEF:
printf("unknown\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
printf("potential model:\n%s\n", Z3_model_to_string(ctx, m));
break;
case Z3_L_TRUE:
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
printf("sat\n%s\n", Z3_model_to_string(ctx, m));
break;
}
if (result != expected_result) {
exitf("unexpected result");
}
if (m) Z3_model_dec_ref(ctx, m);
}
/**
\brief Prove that the constraints already asserted into the logical
context implies the given formula. The result of the proof is
displayed.
Z3 is a satisfiability checker. So, one can prove \c f by showing
that <tt>(not f)</tt> is unsatisfiable.
The context \c ctx is not modified by this function.
*/
void prove(Z3_context ctx, Z3_solver s, Z3_ast f, bool is_valid)
{
Z3_model m = 0;
Z3_ast not_f;
/* save the current state of the context */
Z3_solver_push(ctx, s);
not_f = Z3_mk_not(ctx, f);
Z3_solver_assert(ctx, s, not_f);
switch (Z3_solver_check(ctx, s)) {
case Z3_L_FALSE:
/* proved */
printf("valid\n");
if (!is_valid) {
exitf("unexpected result");
}
break;
case Z3_L_UNDEF:
/* Z3 failed to prove/disprove f. */
printf("unknown\n");
m = Z3_solver_get_model(ctx, s);
if (m != 0) {
Z3_model_inc_ref(ctx, m);
/* m should be viewed as a potential counterexample. */
printf("potential counterexample:\n%s\n", Z3_model_to_string(ctx, m));
}
if (is_valid) {
exitf("unexpected result");
}
break;
case Z3_L_TRUE:
/* disproved */
printf("invalid\n");
m = Z3_solver_get_model(ctx, s);
if (m) {
Z3_model_inc_ref(ctx, m);
/* the model returned by Z3 is a counterexample */
printf("counterexample:\n%s\n", Z3_model_to_string(ctx, m));
}
if (is_valid) {
exitf("unexpected result");
}
break;
}
if (m) Z3_model_dec_ref(ctx, m);
/* restore scope */
Z3_solver_pop(ctx, s, 1);
}
/**
\brief Assert the axiom: function f is injective in the i-th argument.
The following axiom is asserted into the logical context:
\code
forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i
\endcode
Where, \c finv is a fresh function declaration.
*/
void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
{
unsigned sz, j;
Z3_sort finv_domain, finv_range;
Z3_func_decl finv;
Z3_sort * types; /* types of the quantified variables */
Z3_symbol * names; /* names of the quantified variables */
Z3_ast * xs; /* arguments for the application f(x_0, ..., x_i, ..., x_{n-1}) */
Z3_ast x_i, fxs, finv_fxs, eq;
Z3_pattern p;
Z3_ast q;
sz = Z3_get_domain_size(ctx, f);
if (i >= sz) {
exitf("failed to create inj axiom");
}
/* declare the i-th inverse of f: finv */
finv_domain = Z3_get_range(ctx, f);
finv_range = Z3_get_domain(ctx, f, i);
finv = Z3_mk_fresh_func_decl(ctx, "inv", 1, &finv_domain, finv_range);
/* allocate temporary arrays */
types = (Z3_sort *) malloc(sizeof(Z3_sort) * sz);
names = (Z3_symbol *) malloc(sizeof(Z3_symbol) * sz);
xs = (Z3_ast *) malloc(sizeof(Z3_ast) * sz);
/* fill types, names and xs */
for (j = 0; j < sz; j++) { types[j] = Z3_get_domain(ctx, f, j); };
for (j = 0; j < sz; j++) { names[j] = Z3_mk_int_symbol(ctx, j); };
for (j = 0; j < sz; j++) { xs[j] = Z3_mk_bound(ctx, j, types[j]); };
x_i = xs[i];
/* create f(x_0, ..., x_i, ..., x_{n-1}) */
fxs = Z3_mk_app(ctx, f, sz, xs);
/* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */
finv_fxs = mk_unary_app(ctx, finv, fxs);
/* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */
eq = Z3_mk_eq(ctx, finv_fxs, x_i);
/* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */
p = Z3_mk_pattern(ctx, 1, &fxs);
printf("pattern: %s\n", Z3_pattern_to_string(ctx, p));
printf("\n");
/* create & assert quantifier */
q = Z3_mk_forall(ctx,
0, /* using default weight */
1, /* number of patterns */
&p, /* address of the "array" of patterns */
sz, /* number of quantified variables */
types,
names,
eq);
printf("assert axiom:\n%s\n", Z3_ast_to_string(ctx, q));
Z3_solver_assert(ctx, s, q);
/* free temporary arrays */
free(types);
free(names);
free(xs);
}
/**
\brief Assert the axiom: function f is commutative.
This example uses the SMT-LIB parser to simplify the axiom construction.
*/
void assert_comm_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f)
{
Z3_sort t;
Z3_symbol f_name, t_name;
Z3_ast_vector q;
unsigned i;
t = Z3_get_range(ctx, f);
if (Z3_get_domain_size(ctx, f) != 2 ||
Z3_get_domain(ctx, f, 0) != t ||
Z3_get_domain(ctx, f, 1) != t) {
exitf("function must be binary, and argument types must be equal to return type");
}
/* Inside the parser, function f will be referenced using the symbol 'f'. */
f_name = Z3_mk_string_symbol(ctx, "f");
/* Inside the parser, type t will be referenced using the symbol 'T'. */
t_name = Z3_mk_string_symbol(ctx, "T");
q = Z3_parse_smtlib2_string(ctx,
"(assert (forall ((x T) (y T)) (= (f x y) (f y x))))",
1, &t_name, &t,
1, &f_name, &f);
printf("assert axiom:\n%s\n", Z3_ast_vector_to_string(ctx, q));
for (i = 0; i < Z3_ast_vector_size(ctx, q); ++i) {
Z3_solver_assert(ctx, s, Z3_ast_vector_get(ctx, q, i));
}
}
/**
\brief Z3 does not support explicitly tuple updates. They can be easily implemented
as macros. The argument \c t must have tuple type.
A tuple update is a new tuple where field \c i has value \c new_val, and all
other fields have the value of the respective field of \c t.
<tt>update(t, i, new_val)</tt> is equivalent to
<tt>mk_tuple(proj_0(t), ..., new_val, ..., proj_n(t))</tt>
*/
Z3_ast mk_tuple_update(Z3_context c, Z3_ast t, unsigned i, Z3_ast new_val)
{
Z3_sort ty;
Z3_func_decl mk_tuple_decl;
unsigned num_fields, j;
Z3_ast * new_fields;
Z3_ast result;
ty = Z3_get_sort(c, t);
if (Z3_get_sort_kind(c, ty) != Z3_DATATYPE_SORT) {
exitf("argument must be a tuple");
}
num_fields = Z3_get_tuple_sort_num_fields(c, ty);
if (i >= num_fields) {
exitf("invalid tuple update, index is too big");
}
new_fields = (Z3_ast*) malloc(sizeof(Z3_ast) * num_fields);
for (j = 0; j < num_fields; j++) {
if (i == j) {
/* use new_val at position i */
new_fields[j] = new_val;
}
else {
/* use field j of t */
Z3_func_decl proj_decl = Z3_get_tuple_sort_field_decl(c, ty, j);
new_fields[j] = mk_unary_app(c, proj_decl, t);
}
}
mk_tuple_decl = Z3_get_tuple_sort_mk_decl(c, ty);
result = Z3_mk_app(c, mk_tuple_decl, num_fields, new_fields);
free(new_fields);
return result;
}
/**
\brief Display a symbol in the given output stream.
*/
void display_symbol(Z3_context c, FILE * out, Z3_symbol s)
{
switch (Z3_get_symbol_kind(c, s)) {
case Z3_INT_SYMBOL:
fprintf(out, "#%d", Z3_get_symbol_int(c, s));
break;
case Z3_STRING_SYMBOL:
fprintf(out, "%s", Z3_get_symbol_string(c, s));
break;
default:
unreachable();
}
}
/**
\brief Display the given type.
*/
void display_sort(Z3_context c, FILE * out, Z3_sort ty)
{
switch (Z3_get_sort_kind(c, ty)) {
case Z3_UNINTERPRETED_SORT:
display_symbol(c, out, Z3_get_sort_name(c, ty));
break;
case Z3_BOOL_SORT:
fprintf(out, "bool");
break;
case Z3_INT_SORT:
fprintf(out, "int");
break;
case Z3_REAL_SORT:
fprintf(out, "real");
break;
case Z3_BV_SORT:
fprintf(out, "bv%d", Z3_get_bv_sort_size(c, ty));
break;
case Z3_ARRAY_SORT:
fprintf(out, "[");
display_sort(c, out, Z3_get_array_sort_domain(c, ty));
fprintf(out, "->");
display_sort(c, out, Z3_get_array_sort_range(c, ty));
fprintf(out, "]");
break;
case Z3_DATATYPE_SORT:
if (Z3_get_datatype_sort_num_constructors(c, ty) != 1)
{
fprintf(out, "%s", Z3_sort_to_string(c,ty));
break;
}
{
unsigned num_fields = Z3_get_tuple_sort_num_fields(c, ty);
unsigned i;
fprintf(out, "(");
for (i = 0; i < num_fields; i++) {
Z3_func_decl field = Z3_get_tuple_sort_field_decl(c, ty, i);
if (i > 0) {
fprintf(out, ", ");
}
display_sort(c, out, Z3_get_range(c, field));
}
fprintf(out, ")");
break;
}
default:
fprintf(out, "unknown[");
display_symbol(c, out, Z3_get_sort_name(c, ty));
fprintf(out, "]");
break;
}
}
/**
\brief Custom ast pretty printer.
This function demonstrates how to use the API to navigate terms.
*/
void display_ast(Z3_context c, FILE * out, Z3_ast v)
{
switch (Z3_get_ast_kind(c, v)) {
case Z3_NUMERAL_AST: {
Z3_sort t;
fprintf(out, "%s", Z3_get_numeral_string(c, v));
t = Z3_get_sort(c, v);
fprintf(out, ":");
display_sort(c, out, t);
break;
}
case Z3_APP_AST: {
unsigned i;
Z3_app app = Z3_to_app(c, v);
unsigned num_fields = Z3_get_app_num_args(c, app);
Z3_func_decl d = Z3_get_app_decl(c, app);
fprintf(out, "%s", Z3_func_decl_to_string(c, d));
if (num_fields > 0) {
fprintf(out, "[");
for (i = 0; i < num_fields; i++) {
if (i > 0) {
fprintf(out, ", ");
}
display_ast(c, out, Z3_get_app_arg(c, app, i));
}
fprintf(out, "]");
}
break;
}
case Z3_QUANTIFIER_AST: {
fprintf(out, "quantifier");
break;
}
default:
fprintf(out, "#unknown");
}
}
/**
\brief Custom function interpretations pretty printer.
*/
void display_function_interpretations(Z3_context c, FILE * out, Z3_model m)
{
unsigned num_functions, i;
fprintf(out, "function interpretations:\n");
num_functions = Z3_model_get_num_funcs(c, m);
for (i = 0; i < num_functions; i++) {
Z3_func_decl fdecl;
Z3_symbol name;
Z3_ast func_else;
unsigned num_entries = 0, j;
Z3_func_interp_opt finterp;
fdecl = Z3_model_get_func_decl(c, m, i);
finterp = Z3_model_get_func_interp(c, m, fdecl);
Z3_func_interp_inc_ref(c, finterp);
name = Z3_get_decl_name(c, fdecl);
display_symbol(c, out, name);
fprintf(out, " = {");
if (finterp)
num_entries = Z3_func_interp_get_num_entries(c, finterp);
for (j = 0; j < num_entries; j++) {
unsigned num_args, k;
Z3_func_entry fentry = Z3_func_interp_get_entry(c, finterp, j);
Z3_func_entry_inc_ref(c, fentry);
if (j > 0) {
fprintf(out, ", ");
}
num_args = Z3_func_entry_get_num_args(c, fentry);
fprintf(out, "(");
for (k = 0; k < num_args; k++) {
if (k > 0) {
fprintf(out, ", ");
}
display_ast(c, out, Z3_func_entry_get_arg(c, fentry, k));
}
fprintf(out, "|->");
display_ast(c, out, Z3_func_entry_get_value(c, fentry));
fprintf(out, ")");
Z3_func_entry_dec_ref(c, fentry);
}
if (num_entries > 0) {
fprintf(out, ", ");
}
fprintf(out, "(else|->");
func_else = Z3_func_interp_get_else(c, finterp);
display_ast(c, out, func_else);
fprintf(out, ")}\n");
Z3_func_interp_dec_ref(c, finterp);
}
}
/**
\brief Custom model pretty printer.
*/
void display_model(Z3_context c, FILE * out, Z3_model m)
{
unsigned num_constants;
unsigned i;
if (!m) return;
num_constants = Z3_model_get_num_consts(c, m);
for (i = 0; i < num_constants; i++) {
Z3_symbol name;
Z3_func_decl cnst = Z3_model_get_const_decl(c, m, i);
Z3_ast a, v;
bool ok;
name = Z3_get_decl_name(c, cnst);
display_symbol(c, out, name);
fprintf(out, " = ");
a = Z3_mk_app(c, cnst, 0, 0);
v = a;
ok = Z3_model_eval(c, m, a, 1, &v);
(void)ok;
display_ast(c, out, v);
fprintf(out, "\n");
}
display_function_interpretations(c, out, m);
}
/**
\brief Similar to #check, but uses #display_model instead of #Z3_model_to_string.
*/
void check2(Z3_context ctx, Z3_solver s, Z3_lbool expected_result)
{
Z3_model m = 0;
Z3_lbool result = Z3_solver_check(ctx, s);
switch (result) {
case Z3_L_FALSE:
printf("unsat\n");
break;
case Z3_L_UNDEF:
printf("unknown\n");
printf("potential model:\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
display_model(ctx, stdout, m);
break;
case Z3_L_TRUE:
printf("sat\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
display_model(ctx, stdout, m);
break;
}
if (result != expected_result) {
exitf("unexpected result");
}
if (m) Z3_model_dec_ref(ctx, m);
}
/**
\brief Display Z3 version in the standard output.
*/
void display_version()
{
unsigned major, minor, build, revision;
Z3_get_version(&major, &minor, &build, &revision);
printf("Z3 %d.%d.%d.%d\n", major, minor, build, revision);
}
/**@}*/
/**
@name Examples
*/
/**@{*/
/**
\brief "Hello world" example: create a Z3 logical context, and delete it.
*/
void simple_example()
{
Z3_context ctx;
LOG_MSG("simple_example");
printf("\nsimple_example\n");
ctx = mk_context();
/* delete logical context */
Z3_del_context(ctx);
}
/**
Demonstration of how Z3 can be used to prove validity of
De Morgan's Duality Law: {e not(x and y) <-> (not x) or ( not y) }
*/
void demorgan()
{
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_sort bool_sort;
Z3_symbol symbol_x, symbol_y;
Z3_ast x, y, not_x, not_y, x_and_y, ls, rs, conjecture, negated_conjecture;
Z3_ast args[2];
printf("\nDeMorgan\n");
LOG_MSG("DeMorgan");
cfg = Z3_mk_config();
ctx = Z3_mk_context(cfg);
Z3_del_config(cfg);
bool_sort = Z3_mk_bool_sort(ctx);
symbol_x = Z3_mk_int_symbol(ctx, 0);
symbol_y = Z3_mk_int_symbol(ctx, 1);
x = Z3_mk_const(ctx, symbol_x, bool_sort);
y = Z3_mk_const(ctx, symbol_y, bool_sort);
/* De Morgan - with a negation around */
/* !(!(x && y) <-> (!x || !y)) */
not_x = Z3_mk_not(ctx, x);
not_y = Z3_mk_not(ctx, y);
args[0] = x;
args[1] = y;
x_and_y = Z3_mk_and(ctx, 2, args);
ls = Z3_mk_not(ctx, x_and_y);
args[0] = not_x;
args[1] = not_y;
rs = Z3_mk_or(ctx, 2, args);
conjecture = Z3_mk_iff(ctx, ls, rs);
negated_conjecture = Z3_mk_not(ctx, conjecture);
s = mk_solver(ctx);
Z3_solver_assert(ctx, s, negated_conjecture);
switch (Z3_solver_check(ctx, s)) {
case Z3_L_FALSE:
/* The negated conjecture was unsatisfiable, hence the conjecture is valid */
printf("DeMorgan is valid\n");
break;
case Z3_L_UNDEF:
/* Check returned undef */
printf("Undef\n");
break;
case Z3_L_TRUE:
/* The negated conjecture was satisfiable, hence the conjecture is not valid */
printf("DeMorgan is not valid\n");
break;
}
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Find a model for <tt>x xor y</tt>.
*/
void find_model_example1()
{
Z3_context ctx;
Z3_ast x, y, x_xor_y;
Z3_solver s;
printf("\nfind_model_example1\n");
LOG_MSG("find_model_example1");
ctx = mk_context();
s = mk_solver(ctx);
x = mk_bool_var(ctx, "x");
y = mk_bool_var(ctx, "y");
x_xor_y = Z3_mk_xor(ctx, x, y);
Z3_solver_assert(ctx, s, x_xor_y);
printf("model for: x xor y\n");
check(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Find a model for <tt>x < y + 1, x > 2</tt>.
Then, assert <tt>not(x = y)</tt>, and find another model.
*/
void find_model_example2()
{
Z3_context ctx;
Z3_ast x, y, one, two, y_plus_one;
Z3_ast x_eq_y;
Z3_ast args[2];
Z3_ast c1, c2, c3;
Z3_solver s;
printf("\nfind_model_example2\n");
LOG_MSG("find_model_example2");
ctx = mk_context();
s = mk_solver(ctx);
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
one = mk_int(ctx, 1);
two = mk_int(ctx, 2);
args[0] = y;
args[1] = one;
y_plus_one = Z3_mk_add(ctx, 2, args);
c1 = Z3_mk_lt(ctx, x, y_plus_one);
c2 = Z3_mk_gt(ctx, x, two);
Z3_solver_assert(ctx, s, c1);
Z3_solver_assert(ctx, s, c2);
printf("model for: x < y + 1, x > 2\n");
check(ctx, s, Z3_L_TRUE);
/* assert not(x = y) */
x_eq_y = Z3_mk_eq(ctx, x, y);
c3 = Z3_mk_not(ctx, x_eq_y);
Z3_solver_assert(ctx, s,c3);
printf("model for: x < y + 1, x > 2, not(x = y)\n");
check(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Prove <tt>x = y implies g(x) = g(y)</tt>, and
disprove <tt>x = y implies g(g(x)) = g(y)</tt>.
This function demonstrates how to create uninterpreted types and
functions.
*/
void prove_example1()
{
Z3_context ctx;
Z3_solver s;
Z3_symbol U_name, g_name, x_name, y_name;
Z3_sort U;
Z3_sort g_domain[1];
Z3_func_decl g;
Z3_ast x, y, gx, ggx, gy;
Z3_ast eq, f;
printf("\nprove_example1\n");
LOG_MSG("prove_example1");
ctx = mk_context();
s = mk_solver(ctx);
/* create uninterpreted type. */
U_name = Z3_mk_string_symbol(ctx, "U");
U = Z3_mk_uninterpreted_sort(ctx, U_name);
/* declare function g */
g_name = Z3_mk_string_symbol(ctx, "g");
g_domain[0] = U;
g = Z3_mk_func_decl(ctx, g_name, 1, g_domain, U);
/* create x and y */
x_name = Z3_mk_string_symbol(ctx, "x");
y_name = Z3_mk_string_symbol(ctx, "y");
x = Z3_mk_const(ctx, x_name, U);
y = Z3_mk_const(ctx, y_name, U);
/* create g(x), g(y) */
gx = mk_unary_app(ctx, g, x);
gy = mk_unary_app(ctx, g, y);
/* assert x = y */
eq = Z3_mk_eq(ctx, x, y);
Z3_solver_assert(ctx, s, eq);
/* prove g(x) = g(y) */
f = Z3_mk_eq(ctx, gx, gy);
printf("prove: x = y implies g(x) = g(y)\n");
prove(ctx, s, f, true);
/* create g(g(x)) */
ggx = mk_unary_app(ctx, g, gx);
/* disprove g(g(x)) = g(y) */
f = Z3_mk_eq(ctx, ggx, gy);
printf("disprove: x = y implies g(g(x)) = g(y)\n");
prove(ctx, s, f, false);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Prove <tt>not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0 </tt>.
Then, show that <tt>z < -1</tt> is not implied.
This example demonstrates how to combine uninterpreted functions and arithmetic.
*/
void prove_example2()
{
Z3_context ctx;
Z3_solver s;
Z3_sort int_sort;
Z3_symbol g_name;
Z3_sort g_domain[1];
Z3_func_decl g;
Z3_ast x, y, z, zero, minus_one, x_plus_z, gx, gy, gz, gx_gy, ggx_gy;
Z3_ast args[2];
Z3_ast eq, c1, c2, c3, f;
printf("\nprove_example2\n");
LOG_MSG("prove_example2");
ctx = mk_context();
s = mk_solver(ctx);
/* declare function g */
int_sort = Z3_mk_int_sort(ctx);
g_name = Z3_mk_string_symbol(ctx, "g");
g_domain[0] = int_sort;
g = Z3_mk_func_decl(ctx, g_name, 1, g_domain, int_sort);
/* create x, y, and z */
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
z = mk_int_var(ctx, "z");
/* create gx, gy, gz */
gx = mk_unary_app(ctx, g, x);
gy = mk_unary_app(ctx, g, y);
gz = mk_unary_app(ctx, g, z);
/* create zero */
zero = mk_int(ctx, 0);
/* assert not(g(g(x) - g(y)) = g(z)) */
args[0] = gx;
args[1] = gy;
gx_gy = Z3_mk_sub(ctx, 2, args);
ggx_gy = mk_unary_app(ctx, g, gx_gy);
eq = Z3_mk_eq(ctx, ggx_gy, gz);
c1 = Z3_mk_not(ctx, eq);
Z3_solver_assert(ctx, s, c1);
/* assert x + z <= y */
args[0] = x;
args[1] = z;
x_plus_z = Z3_mk_add(ctx, 2, args);
c2 = Z3_mk_le(ctx, x_plus_z, y);
Z3_solver_assert(ctx, s, c2);
/* assert y <= x */
c3 = Z3_mk_le(ctx, y, x);
Z3_solver_assert(ctx, s, c3);
/* prove z < 0 */
f = Z3_mk_lt(ctx, z, zero);
printf("prove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0\n");
prove(ctx, s, f, true);
/* disprove z < -1 */
minus_one = mk_int(ctx, -1);
f = Z3_mk_lt(ctx, z, minus_one);
printf("disprove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < -1\n");
prove(ctx, s, f, false);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Show how push & pop can be used to create "backtracking"
points.
This example also demonstrates how big numbers can be created in Z3.
*/
void push_pop_example1()
{
Z3_context ctx;
Z3_solver s;
Z3_sort int_sort;
Z3_symbol x_sym, y_sym;
Z3_ast x, y, big_number, three;
Z3_ast c1, c2, c3;
printf("\npush_pop_example1\n");
LOG_MSG("push_pop_example1");
ctx = mk_context();
s = mk_solver(ctx);
/* create a big number */
int_sort = Z3_mk_int_sort(ctx);
big_number = Z3_mk_numeral(ctx, "1000000000000000000000000000000000000000000000000000000", int_sort);
/* create number 3 */
three = Z3_mk_numeral(ctx, "3", int_sort);
/* create x */
x_sym = Z3_mk_string_symbol(ctx, "x");
x = Z3_mk_const(ctx, x_sym, int_sort);
/* assert x >= "big number" */
c1 = Z3_mk_ge(ctx, x, big_number);
printf("assert: x >= 'big number'\n");
Z3_solver_assert(ctx, s, c1);
/* create a backtracking point */
printf("push\n");
Z3_solver_push(ctx, s);
printf("number of scopes: %d\n", Z3_solver_get_num_scopes(ctx, s));
/* assert x <= 3 */
c2 = Z3_mk_le(ctx, x, three);
printf("assert: x <= 3\n");
Z3_solver_assert(ctx, s, c2);
/* context is inconsistent at this point */
check2(ctx, s, Z3_L_FALSE);
/* backtrack: the constraint x <= 3 will be removed, since it was
asserted after the last Z3_solver_push. */
printf("pop\n");
Z3_solver_pop(ctx, s, 1);
printf("number of scopes: %d\n", Z3_solver_get_num_scopes(ctx, s));
/* the context is consistent again. */
check2(ctx, s, Z3_L_TRUE);
/* new constraints can be asserted... */
/* create y */
y_sym = Z3_mk_string_symbol(ctx, "y");
y = Z3_mk_const(ctx, y_sym, int_sort);
/* assert y > x */
c3 = Z3_mk_gt(ctx, y, x);
printf("assert: y > x\n");
Z3_solver_assert(ctx, s, c3);
/* the context is still consistent. */
check2(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when
\c f is injective in the second argument.
\sa assert_inj_axiom.
*/
void quantifier_example1()
{
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_sort int_sort;
Z3_symbol f_name;
Z3_sort f_domain[2];
Z3_func_decl f;
Z3_ast x, y, w, v, fxy, fwv;
Z3_ast p1, p2, p3, not_p3;
printf("\nquantifier_example1\n");
LOG_MSG("quantifier_example1");
cfg = Z3_mk_config();
/* If quantified formulas are asserted in a logical context, then
Z3 may return L_UNDEF. In this case, the model produced by Z3 should be viewed as a potential/candidate model.
*/
/*
The current model finder for quantified formulas cannot handle injectivity.
So, we are limiting the number of iterations to avoid a long "wait".
*/
Z3_global_param_set("smt.mbqi.max_iterations", "10");
ctx = mk_context_custom(cfg, error_handler);
Z3_del_config(cfg);
s = mk_solver(ctx);
/* declare function f */
int_sort = Z3_mk_int_sort(ctx);
f_name = Z3_mk_string_symbol(ctx, "f");
f_domain[0] = int_sort;
f_domain[1] = int_sort;
f = Z3_mk_func_decl(ctx, f_name, 2, f_domain, int_sort);
/* assert that f is injective in the second argument. */
assert_inj_axiom(ctx, s, f, 1);
/* create x, y, v, w, fxy, fwv */
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
v = mk_int_var(ctx, "v");
w = mk_int_var(ctx, "w");
fxy = mk_binary_app(ctx, f, x, y);
fwv = mk_binary_app(ctx, f, w, v);
/* assert f(x, y) = f(w, v) */
p1 = Z3_mk_eq(ctx, fxy, fwv);
Z3_solver_assert(ctx, s, p1);
/* prove f(x, y) = f(w, v) implies y = v */
p2 = Z3_mk_eq(ctx, y, v);
printf("prove: f(x, y) = f(w, v) implies y = v\n");
prove(ctx, s, p2, true);
/* disprove f(x, y) = f(w, v) implies x = w */
/* using check2 instead of prove */
p3 = Z3_mk_eq(ctx, x, w);
not_p3 = Z3_mk_not(ctx, p3);
Z3_solver_assert(ctx, s, not_p3);
printf("disprove: f(x, y) = f(w, v) implies x = w\n");
printf("that is: not(f(x, y) = f(w, v) implies x = w) is satisfiable\n");
check2(ctx, s, Z3_L_UNDEF);
printf("reason for last failure: %s\n", Z3_solver_get_reason_unknown(ctx, s));
del_solver(ctx, s);
Z3_del_context(ctx);
/* reset global parameters set by this function */
Z3_global_param_reset_all();
}
/**
\brief Prove <tt>store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3))</tt>.
This example demonstrates how to use the array theory.
*/
void array_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort int_sort, array_sort;
Z3_ast a1, a2, i1, v1, i2, v2, i3;
Z3_ast st1, st2, sel1, sel2;
Z3_ast antecedent, consequent;
Z3_ast ds[3];
Z3_ast thm;
printf("\narray_example1\n");
LOG_MSG("array_example1");
int_sort = Z3_mk_int_sort(ctx);
array_sort = Z3_mk_array_sort(ctx, int_sort, int_sort);
a1 = mk_var(ctx, "a1", array_sort);
a2 = mk_var(ctx, "a2", array_sort);
i1 = mk_var(ctx, "i1", int_sort);
i2 = mk_var(ctx, "i2", int_sort);
i3 = mk_var(ctx, "i3", int_sort);
v1 = mk_var(ctx, "v1", int_sort);
v2 = mk_var(ctx, "v2", int_sort);
st1 = Z3_mk_store(ctx, a1, i1, v1);
st2 = Z3_mk_store(ctx, a2, i2, v2);
sel1 = Z3_mk_select(ctx, a1, i3);
sel2 = Z3_mk_select(ctx, a2, i3);
/* create antecedent */
antecedent = Z3_mk_eq(ctx, st1, st2);
/* create consequent: i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3) */
ds[0] = Z3_mk_eq(ctx, i1, i3);
ds[1] = Z3_mk_eq(ctx, i2, i3);
ds[2] = Z3_mk_eq(ctx, sel1, sel2);
consequent = Z3_mk_or(ctx, 3, ds);
/* prove store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3)) */
thm = Z3_mk_implies(ctx, antecedent, consequent);
printf("prove: store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3))\n");
printf("%s\n", Z3_ast_to_string(ctx, thm));
prove(ctx, s, thm, true);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Show that <tt>distinct(a_0, ... , a_n)</tt> is
unsatisfiable when \c a_i's are arrays from boolean to
boolean and n > 4.
This example also shows how to use the \c distinct construct.
*/
void array_example2()
{
Z3_context ctx;
Z3_solver s;
Z3_sort bool_sort, array_sort;
Z3_ast a[5];
Z3_ast d;
unsigned i, n;
printf("\narray_example2\n");
LOG_MSG("array_example2");
for (n = 2; n <= 5; n++) {
printf("n = %d\n", n);
ctx = mk_context();
s = mk_solver(ctx);
bool_sort = Z3_mk_bool_sort(ctx);
array_sort = Z3_mk_array_sort(ctx, bool_sort, bool_sort);
/* create arrays */
for (i = 0; i < n; i++) {
Z3_symbol s = Z3_mk_int_symbol(ctx, i);
a[i] = Z3_mk_const(ctx, s, array_sort);
}
/* assert distinct(a[0], ..., a[n]) */
d = Z3_mk_distinct(ctx, n, a);
printf("%s\n", Z3_ast_to_string(ctx, d));
Z3_solver_assert(ctx, s, d);
/* context is satisfiable if n < 5 */
check2(ctx, s, n < 5 ? Z3_L_TRUE : Z3_L_FALSE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
}
/**
\brief Simple array type construction/deconstruction example.
*/
void array_example3()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort bool_sort, int_sort, array_sort;
Z3_sort domain, range;
printf("\narray_example3\n");
LOG_MSG("array_example3");
bool_sort = Z3_mk_bool_sort(ctx);
int_sort = Z3_mk_int_sort(ctx);
array_sort = Z3_mk_array_sort(ctx, int_sort, bool_sort);
if (Z3_get_sort_kind(ctx, array_sort) != Z3_ARRAY_SORT) {
exitf("type must be an array type");
}
domain = Z3_get_array_sort_domain(ctx, array_sort);
range = Z3_get_array_sort_range(ctx, array_sort);
printf("domain: ");
display_sort(ctx, stdout, domain);
printf("\n");
printf("range: ");
display_sort(ctx, stdout, range);
printf("\n");
if (int_sort != domain || bool_sort != range) {
exitf("invalid array type");
}
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Simple tuple type example. It creates a tuple that is a pair of real numbers.
*/
void tuple_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort real_sort, pair_sort;
Z3_symbol mk_tuple_name;
Z3_func_decl mk_tuple_decl;
Z3_symbol proj_names[2];
Z3_sort proj_sorts[2];
Z3_func_decl proj_decls[2];
Z3_func_decl get_x_decl, get_y_decl;
printf("\ntuple_example1\n");
LOG_MSG("tuple_example1");
real_sort = Z3_mk_real_sort(ctx);
/* Create pair (tuple) type */
mk_tuple_name = Z3_mk_string_symbol(ctx, "mk_pair");
proj_names[0] = Z3_mk_string_symbol(ctx, "get_x");
proj_names[1] = Z3_mk_string_symbol(ctx, "get_y");
proj_sorts[0] = real_sort;
proj_sorts[1] = real_sort;
/* Z3_mk_tuple_sort will set mk_tuple_decl and proj_decls */
pair_sort = Z3_mk_tuple_sort(ctx, mk_tuple_name, 2, proj_names, proj_sorts, &mk_tuple_decl, proj_decls);
get_x_decl = proj_decls[0]; /* function that extracts the first element of a tuple. */
get_y_decl = proj_decls[1]; /* function that extracts the second element of a tuple. */
printf("tuple_sort: ");
display_sort(ctx, stdout, pair_sort);
printf("\n");
{
/* prove that get_x(mk_pair(x,y)) == 1 implies x = 1*/
Z3_ast app1, app2, x, y, one;
Z3_ast eq1, eq2, eq3, thm;
x = mk_real_var(ctx, "x");
y = mk_real_var(ctx, "y");
app1 = mk_binary_app(ctx, mk_tuple_decl, x, y);
app2 = mk_unary_app(ctx, get_x_decl, app1);
one = Z3_mk_numeral(ctx, "1", real_sort);
eq1 = Z3_mk_eq(ctx, app2, one);
eq2 = Z3_mk_eq(ctx, x, one);
thm = Z3_mk_implies(ctx, eq1, eq2);
printf("prove: get_x(mk_pair(x, y)) = 1 implies x = 1\n");
prove(ctx, s, thm, true);
/* disprove that get_x(mk_pair(x,y)) == 1 implies y = 1*/
eq3 = Z3_mk_eq(ctx, y, one);
thm = Z3_mk_implies(ctx, eq1, eq3);
printf("disprove: get_x(mk_pair(x, y)) = 1 implies y = 1\n");
prove(ctx, s, thm, false);
}
{
/* prove that get_x(p1) = get_x(p2) and get_y(p1) = get_y(p2) implies p1 = p2 */
Z3_ast p1, p2, x1, x2, y1, y2;
Z3_ast antecedents[2];
Z3_ast antecedent, consequent, thm;
p1 = mk_var(ctx, "p1", pair_sort);
p2 = mk_var(ctx, "p2", pair_sort);
x1 = mk_unary_app(ctx, get_x_decl, p1);
y1 = mk_unary_app(ctx, get_y_decl, p1);
x2 = mk_unary_app(ctx, get_x_decl, p2);
y2 = mk_unary_app(ctx, get_y_decl, p2);
antecedents[0] = Z3_mk_eq(ctx, x1, x2);
antecedents[1] = Z3_mk_eq(ctx, y1, y2);
antecedent = Z3_mk_and(ctx, 2, antecedents);
consequent = Z3_mk_eq(ctx, p1, p2);
thm = Z3_mk_implies(ctx, antecedent, consequent);
printf("prove: get_x(p1) = get_x(p2) and get_y(p1) = get_y(p2) implies p1 = p2\n");
prove(ctx, s, thm, true);
/* disprove that get_x(p1) = get_x(p2) implies p1 = p2 */
thm = Z3_mk_implies(ctx, antecedents[0], consequent);
printf("disprove: get_x(p1) = get_x(p2) implies p1 = p2\n");
prove(ctx, s, thm, false);
}
{
/* demonstrate how to use the mk_tuple_update function */
/* prove that p2 = update(p1, 0, 10) implies get_x(p2) = 10 */
Z3_ast p1, p2, ten, updt, x, y;
Z3_ast antecedent, consequent, thm;
p1 = mk_var(ctx, "p1", pair_sort);
p2 = mk_var(ctx, "p2", pair_sort);
ten = Z3_mk_numeral(ctx, "10", real_sort);
updt = mk_tuple_update(ctx, p1, 0, ten);
antecedent = Z3_mk_eq(ctx, p2, updt);
x = mk_unary_app(ctx, get_x_decl, p2);
consequent = Z3_mk_eq(ctx, x, ten);
thm = Z3_mk_implies(ctx, antecedent, consequent);
printf("prove: p2 = update(p1, 0, 10) implies get_x(p2) = 10\n");
prove(ctx, s, thm, true);
/* disprove that p2 = update(p1, 0, 10) implies get_y(p2) = 10 */
y = mk_unary_app(ctx, get_y_decl, p2);
consequent = Z3_mk_eq(ctx, y, ten);
thm = Z3_mk_implies(ctx, antecedent, consequent);
printf("disprove: p2 = update(p1, 0, 10) implies get_y(p2) = 10\n");
prove(ctx, s, thm, false);
}
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Simple bit-vector example. This example disproves that x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers
*/
void bitvector_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort bv_sort;
Z3_ast x, zero, ten, x_minus_ten, c1, c2, thm;
printf("\nbitvector_example1\n");
LOG_MSG("bitvector_example1");
bv_sort = Z3_mk_bv_sort(ctx, 32);
x = mk_var(ctx, "x", bv_sort);
zero = Z3_mk_numeral(ctx, "0", bv_sort);
ten = Z3_mk_numeral(ctx, "10", bv_sort);
x_minus_ten = Z3_mk_bvsub(ctx, x, ten);
/* bvsle is signed less than or equal to */
c1 = Z3_mk_bvsle(ctx, x, ten);
c2 = Z3_mk_bvsle(ctx, x_minus_ten, zero);
thm = Z3_mk_iff(ctx, c1, c2);
printf("disprove: x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers\n");
prove(ctx, s, thm, false);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Find x and y such that: x ^ y - 103 == x * y
*/
void bitvector_example2()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
/* construct x ^ y - 103 == x * y */
Z3_sort bv_sort = Z3_mk_bv_sort(ctx, 32);
Z3_ast x = mk_var(ctx, "x", bv_sort);
Z3_ast y = mk_var(ctx, "y", bv_sort);
Z3_ast x_xor_y = Z3_mk_bvxor(ctx, x, y);
Z3_ast c103 = Z3_mk_numeral(ctx, "103", bv_sort);
Z3_ast lhs = Z3_mk_bvsub(ctx, x_xor_y, c103);
Z3_ast rhs = Z3_mk_bvmul(ctx, x, y);
Z3_ast ctr = Z3_mk_eq(ctx, lhs, rhs);
printf("\nbitvector_example2\n");
LOG_MSG("bitvector_example2");
printf("find values of x and y, such that x ^ y - 103 == x * y\n");
/* add the constraint <tt>x ^ y - 103 == x * y<\tt> to the logical context */
Z3_solver_assert(ctx, s, ctr);
/* find a model (i.e., values for x an y that satisfy the constraint */
check(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrate how to use #Z3_eval.
*/
void eval_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_ast x, y, two;
Z3_ast c1, c2;
Z3_model m = 0;
printf("\neval_example1\n");
LOG_MSG("eval_example1");
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
two = mk_int(ctx, 2);
/* assert x < y */
c1 = Z3_mk_lt(ctx, x, y);
Z3_solver_assert(ctx, s, c1);
/* assert x > 2 */
c2 = Z3_mk_gt(ctx, x, two);
Z3_solver_assert(ctx, s, c2);
/* find model for the constraints above */
if (Z3_solver_check(ctx, s) == Z3_L_TRUE) {
Z3_ast x_plus_y;
Z3_ast args[2] = {x, y};
Z3_ast v;
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
printf("MODEL:\n%s", Z3_model_to_string(ctx, m));
x_plus_y = Z3_mk_add(ctx, 2, args);
printf("\nevaluating x+y\n");
if (Z3_model_eval(ctx, m, x_plus_y, 1, &v)) {
printf("result = ");
display_ast(ctx, stdout, v);
printf("\n");
}
else {
exitf("failed to evaluate: x+y");
}
}
else {
exitf("the constraints are satisfiable");
}
if (m) Z3_model_dec_ref(ctx, m);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Several logical context can be used simultaneously.
*/
void two_contexts_example1()
{
Z3_context ctx1, ctx2;
Z3_ast x1, x2;
printf("\ntwo_contexts_example1\n");
LOG_MSG("two_contexts_example1");
/* using the same (default) configuration to initialized both logical contexts. */
ctx1 = mk_context();
ctx2 = mk_context();
x1 = Z3_mk_const(ctx1, Z3_mk_int_symbol(ctx1,0), Z3_mk_bool_sort(ctx1));
x2 = Z3_mk_const(ctx2, Z3_mk_int_symbol(ctx2,0), Z3_mk_bool_sort(ctx2));
(void)x1;
Z3_del_context(ctx1);
/* ctx2 can still be used. */
printf("%s\n", Z3_ast_to_string(ctx2, x2));
Z3_del_context(ctx2);
}
/**
\brief Demonstrates how error codes can be read instead of registering an error handler.
*/
void error_code_example1()
{
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_ast x;
Z3_model m;
Z3_ast v;
const char * str;
printf("\nerror_code_example1\n");
LOG_MSG("error_code_example11");
/* Do not register an error handler, as we want to use Z3_get_error_code manually */
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, NULL);
Z3_del_config(cfg);
s = mk_solver(ctx);
x = mk_bool_var(ctx, "x");
Z3_solver_assert(ctx, s, x);
if (Z3_solver_check(ctx, s) != Z3_L_TRUE) {
exitf("unexpected result");
}
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
if (!Z3_model_eval(ctx, m, x, 1, &v)) {
exitf("did not obtain value for declaration.\n");
}
if (Z3_get_error_code(ctx) == Z3_OK) {
printf("last call succeeded.\n");
}
/* The following call will fail since the value of x is a boolean */
str = Z3_get_numeral_string(ctx, v);
(void)str;
if (Z3_get_error_code(ctx) != Z3_OK) {
printf("last call failed.\n");
}
if (m) Z3_model_dec_ref(ctx, m);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrates how error handlers can be used.
*/
void error_code_example2() {
Z3_config cfg;
Z3_context ctx = NULL;
Z3_error_code e;
printf("\nerror_code_example2\n");
LOG_MSG("error_code_example2");
if (1) {
Z3_ast x, y, app;
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, nothrow_z3_error);
Z3_del_config(cfg);
x = mk_int_var(ctx, "x");
y = mk_bool_var(ctx, "y");
printf("before Z3_mk_iff\n");
/* the next call will produce an error */
app = Z3_mk_iff(ctx, x, y);
(void)app;
e = Z3_get_error_code(ctx);
if (e != Z3_OK) goto err;
unreachable();
Z3_del_context(ctx);
}
else {
err:
printf("Z3 error: %s.\n", Z3_get_error_msg(ctx, e));
if (ctx != NULL) {
Z3_del_context(ctx);
}
}
}
/**
\brief Demonstrates how to initialize the parser symbol table.
*/
void parser_example2()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_ast x, y;
Z3_symbol names[2];
Z3_func_decl decls[2];
Z3_ast_vector f;
unsigned i;
printf("\nparser_example2\n");
LOG_MSG("parser_example2");
/* Z3_enable_arithmetic doesn't need to be invoked in this example
because it will be implicitly invoked by mk_int_var.
*/
x = mk_int_var(ctx, "x");
decls[0] = Z3_get_app_decl(ctx, Z3_to_app(ctx, x));
y = mk_int_var(ctx, "y");
decls[1] = Z3_get_app_decl(ctx, Z3_to_app(ctx, y));
names[0] = Z3_mk_string_symbol(ctx, "a");
names[1] = Z3_mk_string_symbol(ctx, "b");
f = Z3_parse_smtlib2_string(ctx,
"(assert (> a b))",
0, 0, 0,
/* 'x' and 'y' declarations are inserted as 'a' and 'b' into the parser symbol table. */
2, names, decls);
printf("formula: %s\n", Z3_ast_vector_to_string(ctx, f));
printf("assert axiom:\n%s\n", Z3_ast_vector_to_string(ctx, f));
for (i = 0; i < Z3_ast_vector_size(ctx, f); ++i) {
Z3_solver_assert(ctx, s, Z3_ast_vector_get(ctx, f, i));
}
check(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrates how to initialize the parser symbol table.
*/
void parser_example3()
{
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_sort int_sort;
Z3_symbol g_name;
Z3_sort g_domain[2];
Z3_func_decl g;
Z3_ast_vector thm;
printf("\nparser_example3\n");
LOG_MSG("parser_example3");
cfg = Z3_mk_config();
/* See quantifier_example1 */
Z3_set_param_value(cfg, "model", "true");
ctx = mk_context_custom(cfg, error_handler);
Z3_del_config(cfg);
s = mk_solver(ctx);
/* declare function g */
int_sort = Z3_mk_int_sort(ctx);
g_name = Z3_mk_string_symbol(ctx, "g");
g_domain[0] = int_sort;
g_domain[1] = int_sort;
g = Z3_mk_func_decl(ctx, g_name, 2, g_domain, int_sort);
assert_comm_axiom(ctx, s, g);
thm = Z3_parse_smtlib2_string(ctx,
"(assert (forall ((x Int) (y Int)) (=> (= x y) (= (g x 0) (g 0 y)))))",
0, 0, 0,
1, &g_name, &g);
printf("formula: %s\n", Z3_ast_vector_to_string(ctx, thm));
prove(ctx, s, Z3_ast_vector_get(ctx, thm, 0), true);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrates how to handle parser errors using Z3 error handling support.
*/
void parser_example5() {
Z3_config cfg;
Z3_context ctx = NULL;
Z3_solver s = NULL;
Z3_error_code e;
printf("\nparser_example5\n");
LOG_MSG("parser_example5");
if (1) {
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, nothrow_z3_error);
s = mk_solver(ctx);
Z3_del_config(cfg);
Z3_parse_smtlib2_string(ctx,
/* the following string has a parsing error: missing parenthesis */
"(declare-const x Int) declare-const y Int) (assert (and (> x y) (> x 0)))",
0, 0, 0,
0, 0, 0);
e = Z3_get_error_code(ctx);
if (e != Z3_OK) goto err;
unreachable();
del_solver(ctx, s);
Z3_del_context(ctx);
}
else {
err:
printf("Z3 error: %s.\n", Z3_get_error_msg(ctx, e));
if (ctx != NULL) {
del_solver(ctx, s);
Z3_del_context(ctx);
}
}
}
/**
\brief Demonstrate different ways of creating rational numbers: decimal and fractional representations.
*/
void numeral_example() {
Z3_context ctx;
Z3_solver s;
Z3_ast n1, n2;
Z3_sort real_ty;
printf("\nnumeral_example\n");
LOG_MSG("numeral_example");
ctx = mk_context();
s = mk_solver(ctx);
real_ty = Z3_mk_real_sort(ctx);
n1 = Z3_mk_numeral(ctx, "1/2", real_ty);
n2 = Z3_mk_numeral(ctx, "0.5", real_ty);
printf("Numerals n1:%s", Z3_ast_to_string(ctx, n1));
printf(" n2:%s\n", Z3_ast_to_string(ctx, n2));
prove(ctx, s, Z3_mk_eq(ctx, n1, n2), true);
n1 = Z3_mk_numeral(ctx, "-1/3", real_ty);
n2 = Z3_mk_numeral(ctx, "-0.33333333333333333333333333333333333333333333333333", real_ty);
printf("Numerals n1:%s", Z3_ast_to_string(ctx, n1));
printf(" n2:%s\n", Z3_ast_to_string(ctx, n2));
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, n1, n2)), true);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Test ite-term (if-then-else terms).
*/
void ite_example()
{
Z3_context ctx;
Z3_ast f, one, zero, ite;
printf("\nite_example\n");
LOG_MSG("ite_example");
ctx = mk_context();
f = Z3_mk_false(ctx);
one = mk_int(ctx, 1);
zero = mk_int(ctx, 0);
ite = Z3_mk_ite(ctx, f, one, zero);
printf("term: %s\n", Z3_ast_to_string(ctx, ite));
/* delete logical context */
Z3_del_context(ctx);
}
/**
\brief Create an enumeration data type.
*/
void enum_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort fruit;
Z3_symbol name = Z3_mk_string_symbol(ctx, "fruit");
Z3_symbol enum_names[3];
Z3_func_decl enum_consts[3];
Z3_func_decl enum_testers[3];
Z3_ast apple, orange, banana, fruity;
Z3_ast ors[3];
printf("\nenum_example\n");
LOG_MSG("enum_example");
enum_names[0] = Z3_mk_string_symbol(ctx,"apple");
enum_names[1] = Z3_mk_string_symbol(ctx,"banana");
enum_names[2] = Z3_mk_string_symbol(ctx,"orange");
fruit = Z3_mk_enumeration_sort(ctx, name, 3, enum_names, enum_consts, enum_testers);
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[0]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[1]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[2]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_testers[0]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_testers[1]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_testers[2]));
apple = Z3_mk_app(ctx, enum_consts[0], 0, 0);
banana = Z3_mk_app(ctx, enum_consts[1], 0, 0);
orange = Z3_mk_app(ctx, enum_consts[2], 0, 0);
/* Apples are different from oranges */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, apple, orange)), true);
/* Apples pass the apple test */
prove(ctx, s, Z3_mk_app(ctx, enum_testers[0], 1, &apple), true);
/* Oranges fail the apple test */
prove(ctx, s, Z3_mk_app(ctx, enum_testers[0], 1, &orange), false);
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_app(ctx, enum_testers[0], 1, &orange)), true);
fruity = mk_var(ctx, "fruity", fruit);
/* If something is fruity, then it is an apple, banana, or orange */
ors[0] = Z3_mk_eq(ctx, fruity, apple);
ors[1] = Z3_mk_eq(ctx, fruity, banana);
ors[2] = Z3_mk_eq(ctx, fruity, orange);
prove(ctx, s, Z3_mk_or(ctx, 3, ors), true);
/* delete logical context */
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Create a list datatype.
*/
void list_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort int_ty, int_list;
Z3_func_decl nil_decl, is_nil_decl, cons_decl, is_cons_decl, head_decl, tail_decl;
Z3_ast nil, l1, l2, x, y, u, v, fml, fml1;
Z3_ast ors[2];
printf("\nlist_example\n");
LOG_MSG("list_example");
int_ty = Z3_mk_int_sort(ctx);
int_list = Z3_mk_list_sort(ctx, Z3_mk_string_symbol(ctx, "int_list"), int_ty,
&nil_decl, &is_nil_decl, &cons_decl, &is_cons_decl, &head_decl, &tail_decl);
nil = Z3_mk_app(ctx, nil_decl, 0, 0);
l1 = mk_binary_app(ctx, cons_decl, mk_int(ctx, 1), nil);
l2 = mk_binary_app(ctx, cons_decl, mk_int(ctx, 2), nil);
/* nil != cons(1, nil) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, nil, l1)), true);
/* cons(2,nil) != cons(1, nil) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, l1, l2)), true);
/* cons(x,nil) = cons(y, nil) => x = y */
x = mk_var(ctx, "x", int_ty);
y = mk_var(ctx, "y", int_ty);
l1 = mk_binary_app(ctx, cons_decl, x, nil);
l2 = mk_binary_app(ctx, cons_decl, y, nil);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, x, y)), true);
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", int_list);
v = mk_var(ctx, "v", int_list);
l1 = mk_binary_app(ctx, cons_decl, x, u);
l2 = mk_binary_app(ctx, cons_decl, y, v);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, u, v)), true);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, x, y)), true);
/* is_nil(u) or is_cons(u) */
ors[0] = Z3_mk_app(ctx, is_nil_decl, 1, &u);
ors[1] = Z3_mk_app(ctx, is_cons_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), true);
/* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), true);
/* destructors: is_cons(u) => u = cons(head(u),tail(u)) */
fml1 = Z3_mk_eq(ctx, u, mk_binary_app(ctx, cons_decl, mk_unary_app(ctx, head_decl, u), mk_unary_app(ctx, tail_decl, u)));
fml = Z3_mk_implies(ctx, Z3_mk_app(ctx, is_cons_decl, 1, &u), fml1);
printf("Formula %s\n", Z3_ast_to_string(ctx, fml));
prove(ctx, s, fml, true);
prove(ctx, s, fml1, false);
/* delete logical context */
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Create a binary tree datatype.
*/
void tree_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort cell;
Z3_func_decl nil_decl, is_nil_decl, cons_decl, is_cons_decl, car_decl, cdr_decl;
Z3_ast nil, l1, l2, x, y, u, v, fml, fml1;
Z3_symbol head_tail[2] = { Z3_mk_string_symbol(ctx, "car"), Z3_mk_string_symbol(ctx, "cdr") };
Z3_sort sorts[2] = { 0, 0 };
unsigned sort_refs[2] = { 0, 0 };
Z3_constructor nil_con, cons_con;
Z3_constructor constructors[2];
Z3_func_decl cons_accessors[2];
Z3_ast ors[2];
printf("\ntree_example\n");
LOG_MSG("tree_example");
nil_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "nil"), Z3_mk_string_symbol(ctx, "is_nil"), 0, 0, 0, 0);
cons_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "cons"), Z3_mk_string_symbol(ctx, "is_cons"), 2, head_tail, sorts, sort_refs);
constructors[0] = nil_con;
constructors[1] = cons_con;
cell = Z3_mk_datatype(ctx, Z3_mk_string_symbol(ctx, "cell"), 2, constructors);
Z3_query_constructor(ctx, nil_con, 0, &nil_decl, &is_nil_decl, 0);
Z3_query_constructor(ctx, cons_con, 2, &cons_decl, &is_cons_decl, cons_accessors);
car_decl = cons_accessors[0];
cdr_decl = cons_accessors[1];
Z3_del_constructor(ctx,nil_con);
Z3_del_constructor(ctx,cons_con);
nil = Z3_mk_app(ctx, nil_decl, 0, 0);
l1 = mk_binary_app(ctx, cons_decl, nil, nil);
l2 = mk_binary_app(ctx, cons_decl, l1, nil);
/* nil != cons(nil, nil) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, nil, l1)), true);
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", cell);
v = mk_var(ctx, "v", cell);
x = mk_var(ctx, "x", cell);
y = mk_var(ctx, "y", cell);
l1 = mk_binary_app(ctx, cons_decl, x, u);
l2 = mk_binary_app(ctx, cons_decl, y, v);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, u, v)), true);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, x, y)), true);
/* is_nil(u) or is_cons(u) */
ors[0] = Z3_mk_app(ctx, is_nil_decl, 1, &u);
ors[1] = Z3_mk_app(ctx, is_cons_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), true);
/* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), true);
/* destructors: is_cons(u) => u = cons(car(u),cdr(u)) */
fml1 = Z3_mk_eq(ctx, u, mk_binary_app(ctx, cons_decl, mk_unary_app(ctx, car_decl, u), mk_unary_app(ctx, cdr_decl, u)));
fml = Z3_mk_implies(ctx, Z3_mk_app(ctx, is_cons_decl, 1, &u), fml1);
printf("Formula %s\n", Z3_ast_to_string(ctx, fml));
prove(ctx, s, fml, true);
prove(ctx, s, fml1, false);
/* delete logical context */
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Create a forest of trees.
forest ::= nil | cons(tree, forest)
tree ::= nil | cons(forest, forest)
*/
void forest_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort tree, forest;
Z3_func_decl nil1_decl, is_nil1_decl, cons1_decl, is_cons1_decl, car1_decl, cdr1_decl;
Z3_func_decl nil2_decl, is_nil2_decl, cons2_decl, is_cons2_decl, car2_decl, cdr2_decl;
Z3_ast nil1, nil2, t1, t2, t3, t4, f1, f2, f3, l1, l2, x, y, u, v;
Z3_symbol head_tail[2] = { Z3_mk_string_symbol(ctx, "car"), Z3_mk_string_symbol(ctx, "cdr") };
Z3_sort sorts[2] = { 0, 0 };
unsigned sort_refs[2] = { 0, 0 };
Z3_constructor nil1_con, cons1_con, nil2_con, cons2_con;
Z3_constructor constructors1[2], constructors2[2];
Z3_func_decl cons_accessors[2];
Z3_ast ors[2];
Z3_constructor_list clist1, clist2;
Z3_constructor_list clists[2];
Z3_symbol sort_names[2] = { Z3_mk_string_symbol(ctx, "forest"), Z3_mk_string_symbol(ctx, "tree") };
printf("\nforest_example\n");
LOG_MSG("forest_example");
/* build a forest */
nil1_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "nil1"), Z3_mk_string_symbol(ctx, "is_nil1"), 0, 0, 0, 0);
sort_refs[0] = 1; /* the car of a forest is a tree */
sort_refs[1] = 0;
cons1_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "cons1"), Z3_mk_string_symbol(ctx, "is_cons1"), 2, head_tail, sorts, sort_refs);
constructors1[0] = nil1_con;
constructors1[1] = cons1_con;
/* build a tree */
nil2_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "nil2"), Z3_mk_string_symbol(ctx, "is_nil2"),0, 0, 0, 0);
sort_refs[0] = 0; /* both branches of a tree are forests */
sort_refs[1] = 0;
cons2_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "cons2"), Z3_mk_string_symbol(ctx, "is_cons2"),2, head_tail, sorts, sort_refs);
constructors2[0] = nil2_con;
constructors2[1] = cons2_con;
clist1 = Z3_mk_constructor_list(ctx, 2, constructors1);
clist2 = Z3_mk_constructor_list(ctx, 2, constructors2);
clists[0] = clist1;
clists[1] = clist2;
Z3_mk_datatypes(ctx, 2, sort_names, sorts, clists);
forest = sorts[0];
tree = sorts[1];
Z3_query_constructor(ctx, nil1_con, 0, &nil1_decl, &is_nil1_decl, 0);
Z3_query_constructor(ctx, cons1_con, 2, &cons1_decl, &is_cons1_decl, cons_accessors);
car1_decl = cons_accessors[0];
cdr1_decl = cons_accessors[1];
Z3_query_constructor(ctx, nil2_con, 0, &nil2_decl, &is_nil2_decl, 0);
Z3_query_constructor(ctx, cons2_con, 2, &cons2_decl, &is_cons2_decl, cons_accessors);
car2_decl = cons_accessors[0];
cdr2_decl = cons_accessors[1];
(void)cdr2_decl;
(void)car2_decl;
(void)car1_decl;
(void)cdr1_decl;
Z3_del_constructor_list(ctx, clist1);
Z3_del_constructor_list(ctx, clist2);
Z3_del_constructor(ctx,nil1_con);
Z3_del_constructor(ctx,cons1_con);
Z3_del_constructor(ctx,nil2_con);
Z3_del_constructor(ctx,cons2_con);
nil1 = Z3_mk_app(ctx, nil1_decl, 0, 0);
nil2 = Z3_mk_app(ctx, nil2_decl, 0, 0);
f1 = mk_binary_app(ctx, cons1_decl, nil2, nil1);
t1 = mk_binary_app(ctx, cons2_decl, nil1, nil1);
t2 = mk_binary_app(ctx, cons2_decl, f1, nil1);
t3 = mk_binary_app(ctx, cons2_decl, f1, f1);
t4 = mk_binary_app(ctx, cons2_decl, nil1, f1);
f2 = mk_binary_app(ctx, cons1_decl, t1, nil1);
f3 = mk_binary_app(ctx, cons1_decl, t1, f1);
(void)f3;
(void)f2;
(void)t4;
(void)t3;
(void)t2;
/* nil != cons(nil,nil) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, nil1, f1)), true);
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, nil2, t1)), true);
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", forest);
v = mk_var(ctx, "v", forest);
x = mk_var(ctx, "x", tree);
y = mk_var(ctx, "y", tree);
l1 = mk_binary_app(ctx, cons1_decl, x, u);
l2 = mk_binary_app(ctx, cons1_decl, y, v);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, u, v)), true);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, x, y)), true);
/* is_nil(u) or is_cons(u) */
ors[0] = Z3_mk_app(ctx, is_nil1_decl, 1, &u);
ors[1] = Z3_mk_app(ctx, is_cons1_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), true);
/* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), true);
/* delete logical context */
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Create a binary tree datatype of the form
BinTree ::= nil
| node(value : Int, left : BinTree, right : BinTree)
*/
void binary_tree_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort cell;
Z3_func_decl
nil_decl, /* nil : BinTree (constructor) */
is_nil_decl, /* is_nil : BinTree -> Bool (tester, return true if the given BinTree is a nil) */
node_decl, /* node : Int, BinTree, BinTree -> BinTree (constructor) */
is_node_decl, /* is_node : BinTree -> Bool (tester, return true if the given BinTree is a node) */
value_decl, /* value : BinTree -> Int (accessor for nodes) */
left_decl, /* left : BinTree -> BinTree (accessor for nodes, retrieves the left child of a node) */
right_decl; /* right : BinTree -> BinTree (accessor for nodes, retrieves the right child of a node) */
Z3_symbol node_accessor_names[3] = { Z3_mk_string_symbol(ctx, "value"), Z3_mk_string_symbol(ctx, "left"), Z3_mk_string_symbol(ctx, "right") };
Z3_sort node_accessor_sorts[3] = { Z3_mk_int_sort(ctx), 0, 0 };
unsigned node_accessor_sort_refs[3] = { 0, 0, 0 };
Z3_constructor nil_con, node_con;
Z3_constructor constructors[2];
Z3_func_decl node_accessors[3];
printf("\nbinary_tree_example\n");
LOG_MSG("binary_tree_example");
/* nil_con and node_con are auxiliary datastructures used to create the new recursive datatype BinTree */
nil_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "nil"), Z3_mk_string_symbol(ctx, "is-nil"), 0, 0, 0, 0);
node_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "node"), Z3_mk_string_symbol(ctx, "is-cons"),
3, node_accessor_names, node_accessor_sorts, node_accessor_sort_refs);
constructors[0] = nil_con;
constructors[1] = node_con;
/* create the new recursive datatype */
cell = Z3_mk_datatype(ctx, Z3_mk_string_symbol(ctx, "BinTree"), 2, constructors);
(void)cell;
/* retrieve the new declarations: constructors (nil_decl, node_decl), testers (is_nil_decl, is_cons_del), and
accessors (value_decl, left_decl, right_decl */
Z3_query_constructor(ctx, nil_con, 0, &nil_decl, &is_nil_decl, 0);
Z3_query_constructor(ctx, node_con, 3, &node_decl, &is_node_decl, node_accessors);
value_decl = node_accessors[0];
left_decl = node_accessors[1];
right_decl = node_accessors[2];
/* delete auxiliary/helper structures */
Z3_del_constructor(ctx, nil_con);
Z3_del_constructor(ctx, node_con);
/* small example using the recursive datatype BinTree */
{
/* create nil */
Z3_ast nil = Z3_mk_app(ctx, nil_decl, 0, 0);
/* create node1 ::= node(10, nil, nil) */
Z3_ast args1[3] = { mk_int(ctx, 10), nil, nil };
Z3_ast node1 = Z3_mk_app(ctx, node_decl, 3, args1);
/* create node2 ::= node(30, node1, nil) */
Z3_ast args2[3] = { mk_int(ctx, 30), node1, nil };
Z3_ast node2 = Z3_mk_app(ctx, node_decl, 3, args2);
/* create node3 ::= node(20, node2, node1); */
Z3_ast args3[3] = { mk_int(ctx, 20), node2, node1 };
Z3_ast node3 = Z3_mk_app(ctx, node_decl, 3, args3);
/* prove that nil != node1 */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, nil, node1)), true);
/* prove that nil = left(node1) */
prove(ctx, s, Z3_mk_eq(ctx, nil, mk_unary_app(ctx, left_decl, node1)), true);
/* prove that node1 = right(node3) */
prove(ctx, s, Z3_mk_eq(ctx, node1, mk_unary_app(ctx, right_decl, node3)), true);
/* prove that !is-nil(node2) */
prove(ctx, s, Z3_mk_not(ctx, mk_unary_app(ctx, is_nil_decl, node2)), true);
/* prove that value(node2) >= 0 */
prove(ctx, s, Z3_mk_ge(ctx, mk_unary_app(ctx, value_decl, node2), mk_int(ctx, 0)), true);
}
/* delete logical context */
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Prove a theorem and extract, and print the proof.
This example illustrates the use of #Z3_check_assumptions.
*/
void unsat_core_and_proof_example() {
Z3_context ctx = mk_proof_context();
Z3_solver s = mk_solver(ctx);
Z3_ast pa = mk_bool_var(ctx, "PredA");
Z3_ast pb = mk_bool_var(ctx, "PredB");
Z3_ast pc = mk_bool_var(ctx, "PredC");
Z3_ast pd = mk_bool_var(ctx, "PredD");
Z3_ast p1 = mk_bool_var(ctx, "P1");
Z3_ast p2 = mk_bool_var(ctx, "P2");
Z3_ast p3 = mk_bool_var(ctx, "P3");
Z3_ast p4 = mk_bool_var(ctx, "P4");
Z3_ast assumptions[4] = { Z3_mk_not(ctx, p1), Z3_mk_not(ctx, p2), Z3_mk_not(ctx, p3), Z3_mk_not(ctx, p4) };
Z3_ast args1[3] = { pa, pb, pc };
Z3_ast f1 = Z3_mk_and(ctx, 3, args1);
Z3_ast args2[3] = { pa, Z3_mk_not(ctx, pb), pc };
Z3_ast f2 = Z3_mk_and(ctx, 3, args2);
Z3_ast args3[2] = { Z3_mk_not(ctx, pa), Z3_mk_not(ctx, pc) };
Z3_ast f3 = Z3_mk_or(ctx, 2, args3);
Z3_ast f4 = pd;
Z3_ast g1[2] = { f1, p1 };
Z3_ast g2[2] = { f2, p2 };
Z3_ast g3[2] = { f3, p3 };
Z3_ast g4[2] = { f4, p4 };
Z3_lbool result;
Z3_ast proof;
Z3_model m = 0;
unsigned i;
Z3_ast_vector core;
printf("\nunsat_core_and_proof_example\n");
LOG_MSG("unsat_core_and_proof_example");
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g1));
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g2));
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g3));
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g4));
result = Z3_solver_check_assumptions(ctx, s, 4, assumptions);
switch (result) {
case Z3_L_FALSE:
core = Z3_solver_get_unsat_core(ctx, s);
proof = Z3_solver_get_proof(ctx, s);
printf("unsat\n");
printf("proof: %s\n", Z3_ast_to_string(ctx, proof));
printf("\ncore:\n");
for (i = 0; i < Z3_ast_vector_size(ctx, core); ++i) {
printf("%s\n", Z3_ast_to_string(ctx, Z3_ast_vector_get(ctx, core, i)));
}
printf("\n");
break;
case Z3_L_UNDEF:
printf("unknown\n");
printf("potential model:\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
display_model(ctx, stdout, m);
break;
case Z3_L_TRUE:
printf("sat\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
display_model(ctx, stdout, m);
break;
}
/* delete logical context */
if (m) Z3_model_dec_ref(ctx, m);
del_solver(ctx, s);
Z3_del_context(ctx);
}
#define MAX_RETRACTABLE_ASSERTIONS 1024
/**
\brief Very simple logical context wrapper with support for retractable constraints.
A retractable constraint can be "removed" without using push/pop.
*/
typedef struct {
Z3_context m_context;
Z3_solver m_solver;
// IMPORTANT: the fields m_answer_literals, m_retracted and m_num_answer_literals must be saved/restored
// if push/pop operations are performed on m_context.
Z3_ast m_answer_literals[MAX_RETRACTABLE_ASSERTIONS];
bool m_retracted[MAX_RETRACTABLE_ASSERTIONS]; // true if the assertion was retracted.
unsigned m_num_answer_literals;
} Z3_ext_context_struct;
typedef Z3_ext_context_struct * Z3_ext_context;
/**
\brief Create a logical context wrapper with support for retractable constraints.
*/
Z3_ext_context mk_ext_context() {
Z3_ext_context ctx = (Z3_ext_context) malloc(sizeof(Z3_ext_context_struct));
ctx->m_context = mk_context();
ctx->m_solver = mk_solver(ctx->m_context);
ctx->m_num_answer_literals = 0;
return ctx;
}
/**
\brief Delete the given logical context wrapper.
*/
void del_ext_context(Z3_ext_context ctx) {
del_solver(ctx->m_context, ctx->m_solver);
Z3_del_context(ctx->m_context);
free(ctx);
}
/**
\brief Create a retractable constraint.
\return An id that can be used to retract/reassert the constraint.
*/
unsigned assert_retractable_cnstr(Z3_ext_context ctx, Z3_ast c) {
unsigned result;
Z3_sort ty;
Z3_ast ans_lit;
Z3_ast args[2];
if (ctx->m_num_answer_literals == MAX_RETRACTABLE_ASSERTIONS) {
exitf("maximum number of retractable constraints was exceeded.");
}
ty = Z3_mk_bool_sort(ctx->m_context);
ans_lit = Z3_mk_fresh_const(ctx->m_context, "k", ty);
result = ctx->m_num_answer_literals;
ctx->m_answer_literals[result] = ans_lit;
ctx->m_retracted[result] = false;
ctx->m_num_answer_literals++;
// assert: c OR (not ans_lit)
args[0] = c;
args[1] = Z3_mk_not(ctx->m_context, ans_lit);
Z3_solver_assert(ctx->m_context, ctx->m_solver, Z3_mk_or(ctx->m_context, 2, args));
return result;
}
/**
\brief Retract an constraint asserted using #assert_retractable_cnstr.
*/
void retract_cnstr(Z3_ext_context ctx, unsigned id) {
if (id >= ctx->m_num_answer_literals) {
exitf("invalid constraint id.");
}
ctx->m_retracted[id] = true;
}
/**
\brief Reassert a constraint retracted using #retract_cnstr.
*/
void reassert_cnstr(Z3_ext_context ctx, unsigned id) {
if (id >= ctx->m_num_answer_literals) {
exitf("invalid constraint id.");
}
ctx->m_retracted[id] = false;
}
/**
\brief Check whether the logical context wrapper with support for retractable assertions is feasible or not.
*/
Z3_lbool ext_check(Z3_ext_context ctx) {
Z3_lbool result;
unsigned num_assumptions = 0;
Z3_ast assumptions[MAX_RETRACTABLE_ASSERTIONS];
Z3_ast_vector core;
unsigned core_size;
unsigned i;
for (i = 0; i < ctx->m_num_answer_literals; i++) {
if (ctx->m_retracted[i] == false) {
// Since the answer literal was not retracted, we added it as an assumption.
// Recall that we assert (C \/ (not ans_lit)). Therefore, adding ans_lit as an assumption has the effect of "asserting" C.
// If the constraint was "retracted" (ctx->m_retracted[i] == Z3_true), then we don't really need to add (not ans_lit) as an assumption.
assumptions[num_assumptions] = ctx->m_answer_literals[i];
num_assumptions ++;
}
}
result = Z3_solver_check_assumptions(ctx->m_context, ctx->m_solver, num_assumptions, assumptions);
if (result == Z3_L_FALSE) {
// Display the UNSAT core
printf("unsat core: ");
core = Z3_solver_get_unsat_core(ctx->m_context, ctx->m_solver);
core_size = Z3_ast_vector_size(ctx->m_context, core);
for (i = 0; i < core_size; i++) {
// In this example, we display the core based on the assertion ids.
unsigned j;
for (j = 0; j < ctx->m_num_answer_literals; j++) {
if (Z3_ast_vector_get(ctx->m_context, core, i) == ctx->m_answer_literals[j]) {
printf("%d ", j);
break;
}
}
if (j == ctx->m_num_answer_literals) {
exitf("bug in Z3, the core contains something that is not an assumption.");
}
}
printf("\n");
}
return result;
}
/**
\brief Simple example using the functions: #mk_ext_context, #assert_retractable_cnstr, #retract_cnstr, #reassert_cnstr and #del_ext_context.
*/
void incremental_example1() {
Z3_ext_context ext_ctx = mk_ext_context();
Z3_context ctx = ext_ctx->m_context;
Z3_ast x, y, z, two, one;
unsigned c1, c2, c3, c4;
Z3_lbool result;
printf("\nincremental_example1\n");
LOG_MSG("incremental_example1");
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
z = mk_int_var(ctx, "z");
two = mk_int(ctx, 2);
one = mk_int(ctx, 1);
/* assert x < y */
c1 = assert_retractable_cnstr(ext_ctx, Z3_mk_lt(ctx, x, y));
/* assert x = z */
c2 = assert_retractable_cnstr(ext_ctx, Z3_mk_eq(ctx, x, z));
/* assert x > 2 */
c3 = assert_retractable_cnstr(ext_ctx, Z3_mk_gt(ctx, x, two));
/* assert y < 1 */
c4 = assert_retractable_cnstr(ext_ctx, Z3_mk_lt(ctx, y, one));
(void)c1;
result = ext_check(ext_ctx);
if (result != Z3_L_FALSE)
exitf("bug in Z3");
printf("unsat\n");
retract_cnstr(ext_ctx, c4);
result = ext_check(ext_ctx);
if (result != Z3_L_TRUE)
exitf("bug in Z3");
printf("sat\n");
reassert_cnstr(ext_ctx, c4);
result = ext_check(ext_ctx);
if (result != Z3_L_FALSE)
exitf("bug in Z3");
printf("unsat\n");
retract_cnstr(ext_ctx, c2);
result = ext_check(ext_ctx);
if (result != Z3_L_FALSE)
exitf("bug in Z3");
printf("unsat\n");
retract_cnstr(ext_ctx, c3);
result = ext_check(ext_ctx);
if (result != Z3_L_TRUE)
exitf("bug in Z3");
printf("sat\n");
del_ext_context(ext_ctx);
}
/**
\brief Simple example showing how to use reference counters in Z3
to manage memory efficiently.
*/
void reference_counter_example() {
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_sort ty;
Z3_ast x, y, x_xor_y;
Z3_symbol sx, sy;
printf("\nreference_counter_example\n");
LOG_MSG("reference_counter_example");
cfg = Z3_mk_config();
Z3_set_param_value(cfg, "model", "true");
// Create a Z3 context where the user is responsible for managing
// Z3_ast reference counters.
ctx = Z3_mk_context_rc(cfg);
Z3_del_config(cfg);
s = mk_solver(ctx);
Z3_solver_inc_ref(ctx, s);
ty = Z3_mk_bool_sort(ctx);
Z3_inc_ref(ctx, Z3_sort_to_ast(ctx, ty)); // Z3_sort_to_ast(ty) is just syntax sugar for ((Z3_ast) ty)
sx = Z3_mk_string_symbol(ctx, "x");
// Z3_symbol is not a Z3_ast. No reference counting is needed.
x = Z3_mk_const(ctx, sx, ty);
Z3_inc_ref(ctx, x);
sy = Z3_mk_string_symbol(ctx, "y");
y = Z3_mk_const(ctx, sy, ty);
Z3_inc_ref(ctx, y);
// ty is not needed anymore.
Z3_dec_ref(ctx, Z3_sort_to_ast(ctx, ty));
x_xor_y = Z3_mk_xor(ctx, x, y);
Z3_inc_ref(ctx, x_xor_y);
// x and y are not needed anymore.
Z3_dec_ref(ctx, x);
Z3_dec_ref(ctx, y);
Z3_solver_assert(ctx, s, x_xor_y);
// x_or_y is not needed anymore.
Z3_dec_ref(ctx, x_xor_y);
printf("model for: x xor y\n");
check(ctx, s, Z3_L_TRUE);
// Test push & pop
Z3_solver_push(ctx, s);
Z3_solver_pop(ctx, s, 1);
Z3_solver_dec_ref(ctx, s);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrates how to use SMT2 parser.
*/
void smt2parser_example() {
Z3_context ctx;
Z3_ast_vector fs;
printf("\nsmt2parser_example\n");
LOG_MSG("smt2parser_example");
ctx = mk_context();
fs = Z3_parse_smtlib2_string(ctx, "(declare-fun a () (_ BitVec 8)) (assert (bvuge a #x10)) (assert (bvule a #xf0))", 0, 0, 0, 0, 0, 0);
Z3_ast_vector_inc_ref(ctx, fs);
printf("formulas: %s\n", Z3_ast_vector_to_string(ctx, fs));
Z3_ast_vector_dec_ref(ctx, fs);
Z3_del_context(ctx);
}
/**
\brief Demonstrates how to use the function \c Z3_substitute to replace subexpressions in a Z3 AST.
*/
void substitute_example() {
Z3_context ctx;
Z3_sort int_ty;
Z3_ast a, b;
Z3_func_decl f;
Z3_func_decl g;
Z3_ast fab, ga, ffabga, r;
printf("\nsubstitute_example\n");
LOG_MSG("substitute_example");
ctx = mk_context();
int_ty = Z3_mk_int_sort(ctx);
a = mk_int_var(ctx,"a");
b = mk_int_var(ctx,"b");
{
Z3_sort f_domain[2] = { int_ty, int_ty };
f = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "f"), 2, f_domain, int_ty);
}
g = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "g"), 1, &int_ty, int_ty);
{
Z3_ast args[2] = { a, b };
fab = Z3_mk_app(ctx, f, 2, args);
}
ga = Z3_mk_app(ctx, g, 1, &a);
{
Z3_ast args[2] = { fab, ga };
ffabga = Z3_mk_app(ctx, f, 2, args);
}
// Replace b -> 0, g(a) -> 1 in f(f(a, b), g(a))
{
Z3_ast zero = Z3_mk_numeral(ctx, "0", int_ty);
Z3_ast one = Z3_mk_numeral(ctx, "1", int_ty);
Z3_ast from[2] = { b, ga };
Z3_ast to[2] = { zero, one };
r = Z3_substitute(ctx, ffabga, 2, from, to);
}
// Display r
printf("substitution result: %s\n", Z3_ast_to_string(ctx, r));
Z3_del_context(ctx);
}
/**
\brief Demonstrates how to use the function \c Z3_substitute_vars to replace (free) variables with expressions in a Z3 AST.
*/
void substitute_vars_example() {
Z3_context ctx;
Z3_sort int_ty;
Z3_ast x0, x1;
Z3_ast a, b, gb;
Z3_func_decl f;
Z3_func_decl g;
Z3_ast f01, ff010, r;
printf("\nsubstitute_vars_example\n");
LOG_MSG("substitute_vars_example");
ctx = mk_context();
int_ty = Z3_mk_int_sort(ctx);
x0 = Z3_mk_bound(ctx, 0, int_ty);
x1 = Z3_mk_bound(ctx, 1, int_ty);
{
Z3_sort f_domain[2] = { int_ty, int_ty };
f = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "f"), 2, f_domain, int_ty);
}
g = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "g"), 1, &int_ty, int_ty);
{
Z3_ast args[2] = { x0, x1 };
f01 = Z3_mk_app(ctx, f, 2, args);
}
{
Z3_ast args[2] = { f01, x0 };
ff010 = Z3_mk_app(ctx, f, 2, args);
}
a = mk_int_var(ctx, "a");
b = mk_int_var(ctx, "b");
gb = Z3_mk_app(ctx, g, 1, &b);
// Replace x0 -> a, x1 -> g(b) in f(f(x0,x1),x0)
{
Z3_ast to[2] = { a, gb };
r = Z3_substitute_vars(ctx, ff010, 2, to);
}
// Display r
printf("substitution result: %s\n", Z3_ast_to_string(ctx, r));
Z3_del_context(ctx);
}
/**
\brief Demonstrates some basic features of the FloatingPoint theory.
*/
void fpa_example() {
Z3_config cfg;
Z3_context ctx;
Z3_solver s;
Z3_sort double_sort, rm_sort;
Z3_symbol s_rm, s_x, s_y, s_x_plus_y;
Z3_ast rm, x, y, n, x_plus_y, c1, c2, c3, c4, c5;
Z3_ast args[2], args2[2], and_args[3], args3[3];
printf("\nFPA-example\n");
LOG_MSG("FPA-example");
cfg = Z3_mk_config();
ctx = Z3_mk_context(cfg);
s = mk_solver(ctx);
Z3_del_config(cfg);
double_sort = Z3_mk_fpa_sort(ctx, 11, 53);
rm_sort = Z3_mk_fpa_rounding_mode_sort(ctx);
// Show that there are x, y s.t. (x + y) = 42.0 (with rounding mode).
s_rm = Z3_mk_string_symbol(ctx, "rm");
rm = Z3_mk_const(ctx, s_rm, rm_sort);
s_x = Z3_mk_string_symbol(ctx, "x");
s_y = Z3_mk_string_symbol(ctx, "y");
x = Z3_mk_const(ctx, s_x, double_sort);
y = Z3_mk_const(ctx, s_y, double_sort);
n = Z3_mk_fpa_numeral_double(ctx, 42.0, double_sort);
s_x_plus_y = Z3_mk_string_symbol(ctx, "x_plus_y");
x_plus_y = Z3_mk_const(ctx, s_x_plus_y, double_sort);
c1 = Z3_mk_eq(ctx, x_plus_y, Z3_mk_fpa_add(ctx, rm, x, y));
args[0] = c1;
args[1] = Z3_mk_eq(ctx, x_plus_y, n);
c2 = Z3_mk_and(ctx, 2, (Z3_ast*)&args);
args2[0] = c2;
args2[1] = Z3_mk_not(ctx, Z3_mk_eq(ctx, rm, Z3_mk_fpa_rtz(ctx)));
c3 = Z3_mk_and(ctx, 2, (Z3_ast*)&args2);
and_args[0] = Z3_mk_not(ctx, Z3_mk_fpa_is_zero(ctx, y));
and_args[1] = Z3_mk_not(ctx, Z3_mk_fpa_is_nan(ctx, y));
and_args[2] = Z3_mk_not(ctx, Z3_mk_fpa_is_infinite(ctx, y));
args3[0] = c3;
args3[1] = Z3_mk_and(ctx, 3, and_args);
c4 = Z3_mk_and(ctx, 2, (Z3_ast*)&args3);
printf("c4: %s\n", Z3_ast_to_string(ctx, c4));
Z3_solver_push(ctx, s);
Z3_solver_assert(ctx, s, c4);
check(ctx, s, Z3_L_TRUE);
Z3_solver_pop(ctx, s, 1);
// Show that the following are equal:
// (fp #b0 #b10000000001 #xc000000000000)
// ((_ to_fp 11 53) #x401c000000000000))
// ((_ to_fp 11 53) RTZ 1.75 2)))
// ((_ to_fp 11 53) RTZ 7.0)))
Z3_solver_push(ctx, s);
c1 = Z3_mk_fpa_fp(ctx,
Z3_mk_numeral(ctx, "0", Z3_mk_bv_sort(ctx, 1)),
Z3_mk_numeral(ctx, "1025", Z3_mk_bv_sort(ctx, 11)),
Z3_mk_numeral(ctx, "3377699720527872", Z3_mk_bv_sort(ctx, 52)));
c2 = Z3_mk_fpa_to_fp_bv(ctx,
Z3_mk_numeral(ctx, "4619567317775286272", Z3_mk_bv_sort(ctx, 64)),
Z3_mk_fpa_sort(ctx, 11, 53));
c3 = Z3_mk_fpa_to_fp_int_real(ctx,
Z3_mk_fpa_rtz(ctx),
Z3_mk_numeral(ctx, "2", Z3_mk_int_sort(ctx)), /* exponent */
Z3_mk_numeral(ctx, "1.75", Z3_mk_real_sort(ctx)), /* significand */
Z3_mk_fpa_sort(ctx, 11, 53));
c4 = Z3_mk_fpa_to_fp_real(ctx,
Z3_mk_fpa_rtz(ctx),
Z3_mk_numeral(ctx, "7.0", Z3_mk_real_sort(ctx)),
Z3_mk_fpa_sort(ctx, 11, 53));
args3[0] = Z3_mk_eq(ctx, c1, c2);
args3[1] = Z3_mk_eq(ctx, c1, c3);
args3[2] = Z3_mk_eq(ctx, c1, c4);
c5 = Z3_mk_and(ctx, 3, args3);
printf("c5: %s\n", Z3_ast_to_string(ctx, c5));
Z3_solver_assert(ctx, s, c5);
check(ctx, s, Z3_L_TRUE);
Z3_solver_pop(ctx, s, 1);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
\brief Demonstrates some basic features of model construction
*/
void mk_model_example() {
Z3_context ctx;
Z3_model m;
Z3_sort intSort;
Z3_symbol aSymbol, bSymbol, cSymbol;
Z3_func_decl aFuncDecl, bFuncDecl, cFuncDecl;
Z3_ast aApp, bApp, cApp;
Z3_sort int2intArraySort;
Z3_ast zeroNumeral, oneNumeral, twoNumeral, threeNumeral, fourNumeral;
Z3_sort arrayDomain[1];
Z3_func_decl cAsFuncDecl;
Z3_func_interp cAsFuncInterp;
Z3_ast_vector zeroArgs;
Z3_ast_vector oneArgs;
Z3_ast cFuncDeclAsArray;
Z3_string modelAsString;
printf("\nmk_model_example\n");
ctx = mk_context();
// Construct empty model
m = Z3_mk_model(ctx);
Z3_model_inc_ref(ctx, m);
// Create constants "a" and "b"
intSort = Z3_mk_int_sort(ctx);
aSymbol = Z3_mk_string_symbol(ctx, "a");
aFuncDecl = Z3_mk_func_decl(ctx, aSymbol,
/*domain_size=*/0,
/*domain=*/NULL,
/*range=*/intSort);
aApp = Z3_mk_app(ctx, aFuncDecl,
/*num_args=*/0,
/*args=*/NULL);
bSymbol = Z3_mk_string_symbol(ctx, "b");
bFuncDecl = Z3_mk_func_decl(ctx, bSymbol,
/*domain_size=*/0,
/*domain=*/NULL,
/*range=*/intSort);
bApp = Z3_mk_app(ctx, bFuncDecl,
/*num_args=*/0,
/*args=*/NULL);
// Create array "c" that maps int to int.
cSymbol = Z3_mk_string_symbol(ctx, "c");
int2intArraySort = Z3_mk_array_sort(ctx,
/*domain=*/intSort,
/*range=*/intSort);
cFuncDecl = Z3_mk_func_decl(ctx, cSymbol,
/*domain_size=*/0,
/*domain=*/NULL,
/*range=*/int2intArraySort);
cApp = Z3_mk_app(ctx, cFuncDecl,
/*num_args=*/0,
/*args=*/NULL);
// Create numerals to be used in model
zeroNumeral = Z3_mk_int(ctx, 0, intSort);
oneNumeral = Z3_mk_int(ctx, 1, intSort);
twoNumeral = Z3_mk_int(ctx, 2, intSort);
threeNumeral = Z3_mk_int(ctx, 3, intSort);
fourNumeral = Z3_mk_int(ctx, 4, intSort);
// Add assignments to model
// a == 1
Z3_add_const_interp(ctx, m, aFuncDecl, oneNumeral);
// b == 2
Z3_add_const_interp(ctx, m, bFuncDecl, twoNumeral);
// Create a fresh function that represents
// reading from array.
arrayDomain[0] = intSort;
cAsFuncDecl = Z3_mk_fresh_func_decl(ctx,
/*prefix=*/"",
/*domain_size*/ 1,
/*domain=*/arrayDomain,
/*sort=*/intSort);
// Create function interpretation with default
// value of "0".
cAsFuncInterp =
Z3_add_func_interp(ctx, m, cAsFuncDecl,
/*default_value=*/zeroNumeral);
Z3_func_interp_inc_ref(ctx, cAsFuncInterp);
// Add [0] = 3
zeroArgs = Z3_mk_ast_vector(ctx);
Z3_ast_vector_inc_ref(ctx, zeroArgs);
Z3_ast_vector_push(ctx, zeroArgs, zeroNumeral);
Z3_func_interp_add_entry(ctx, cAsFuncInterp, zeroArgs, threeNumeral);
// Add [1] = 4
oneArgs = Z3_mk_ast_vector(ctx);
Z3_ast_vector_inc_ref(ctx, oneArgs);
Z3_ast_vector_push(ctx, oneArgs, oneNumeral);
Z3_func_interp_add_entry(ctx, cAsFuncInterp, oneArgs, fourNumeral);
// Now use the `(_ as_array)` to associate
// the `cAsFuncInterp` with the `cFuncDecl`
// in the model
cFuncDeclAsArray = Z3_mk_as_array(ctx, cAsFuncDecl);
Z3_add_const_interp(ctx, m, cFuncDecl, cFuncDeclAsArray);
// Print the model
modelAsString = Z3_model_to_string(ctx, m);
printf("Model:\n%s\n", modelAsString);
// Check the interpretations we expect to be present
// are.
{
Z3_func_decl expectedInterpretations[3] = {aFuncDecl, bFuncDecl, cFuncDecl};
int index;
for (index = 0;
index < sizeof(expectedInterpretations) / sizeof(Z3_func_decl);
++index) {
Z3_func_decl d = expectedInterpretations[index];
if (Z3_model_has_interp(ctx, m, d)) {
printf("Found interpretation for \"%s\"\n",
Z3_ast_to_string(ctx, Z3_func_decl_to_ast(ctx, d)));
} else {
printf("Missing interpretation");
exit(1);
}
}
}
{
// Evaluate a + b under model
Z3_ast addArgs[] = {aApp, bApp};
Z3_ast aPlusB = Z3_mk_add(ctx,
/*num_args=*/2,
/*args=*/addArgs);
Z3_ast aPlusBEval = NULL;
bool aPlusBEvalSuccess =
Z3_model_eval(ctx, m, aPlusB,
/*model_completion=*/false, &aPlusBEval);
if (aPlusBEvalSuccess != true) {
printf("Failed to evaluate model\n");
exit(1);
}
{
int aPlusBValue = 0;
bool getAPlusBValueSuccess =
Z3_get_numeral_int(ctx, aPlusBEval, &aPlusBValue);
if (getAPlusBValueSuccess != true) {
printf("Failed to get integer value for a+b\n");
exit(1);
}
printf("Evaluated a + b = %d\n", aPlusBValue);
if (aPlusBValue != 3) {
printf("a+b did not evaluate to expected value\n");
exit(1);
}
}
}
{
// Evaluate c[0] + c[1] + c[2] under model
Z3_ast c0 = Z3_mk_select(ctx, cApp, zeroNumeral);
Z3_ast c1 = Z3_mk_select(ctx, cApp, oneNumeral);
Z3_ast c2 = Z3_mk_select(ctx, cApp, twoNumeral);
Z3_ast arrayAddArgs[] = {c0, c1, c2};
Z3_ast arrayAdd = Z3_mk_add(ctx,
/*num_args=*/3,
/*args=*/arrayAddArgs);
Z3_ast arrayAddEval = NULL;
bool arrayAddEvalSuccess =
Z3_model_eval(ctx, m, arrayAdd,
/*model_completion=*/false, &arrayAddEval);
if (arrayAddEvalSuccess != true) {
printf("Failed to evaluate model\n");
exit(1);
}
{
int arrayAddValue = 0;
bool getArrayAddValueSuccess =
Z3_get_numeral_int(ctx, arrayAddEval, &arrayAddValue);
if (getArrayAddValueSuccess != true) {
printf("Failed to get integer value for c[0] + c[1] + c[2]\n");
exit(1);
}
printf("Evaluated c[0] + c[1] + c[2] = %d\n", arrayAddValue);
if (arrayAddValue != 7) {
printf("c[0] + c[1] + c[2] did not evaluate to expected value\n");
exit(1);
}
}
}
Z3_ast_vector_dec_ref(ctx, oneArgs);
Z3_ast_vector_dec_ref(ctx, zeroArgs);
Z3_func_interp_dec_ref(ctx, cAsFuncInterp);
Z3_model_dec_ref(ctx, m);
Z3_del_context(ctx);
}
void divides_example()
{
Z3_context ctx;
Z3_solver s;
Z3_ast x, number;
Z3_ast c;
ctx = mk_context();
s = mk_solver(ctx);
x = mk_int_var(ctx, "x");
number = mk_int(ctx, 2);
c = Z3_mk_divides(ctx, number, x);
Z3_solver_assert(ctx, s, c);
check2(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**@}*/
/**@}*/
int main() {
#ifdef LOG_Z3_CALLS
Z3_open_log("z3.log");
#endif
divides_example();
display_version();
simple_example();
demorgan();
find_model_example1();
find_model_example2();
prove_example1();
prove_example2();
push_pop_example1();
quantifier_example1();
array_example1();
array_example2();
array_example3();
tuple_example1();
bitvector_example1();
bitvector_example2();
eval_example1();
two_contexts_example1();
error_code_example1();
error_code_example2();
parser_example2();
parser_example3();
parser_example5();
numeral_example();
ite_example();
list_example();
tree_example();
forest_example();
binary_tree_example();
enum_example();
unsat_core_and_proof_example();
incremental_example1();
reference_counter_example();
smt2parser_example();
substitute_example();
substitute_vars_example();
fpa_example();
mk_model_example();
return 0;
}
|
e84fa0150a374aaf1fdb7222e78bd39d0f5dbb8c
|
6528b705959d99fdd395c1e06fca826108a40769
|
/hcxpmktool.c
|
7cfe60817ed7dff7cc224c616eec55d9328de0dc
|
[
"MIT"
] |
permissive
|
ZerBea/hcxtools
|
832c52610ef3139960ffb823390411c03bbc76a4
|
937c2efcae975b2e7398a24c4d836f36cf5fdcc6
|
refs/heads/master
| 2023-08-31T06:07:17.128533
| 2023-08-28T12:27:30
| 2023-08-28T12:27:30
| 87,620,707
| 1,760
| 390
|
MIT
| 2023-09-07T06:09:39
| 2017-04-08T08:47:44
|
C
|
UTF-8
|
C
| false
| false
| 26,305
|
c
|
hcxpmktool.c
|
#define _GNU_SOURCE
#include <getopt.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <openssl/core.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/params.h>
#include <openssl/types.h>
#include "include/hcxpmktool.h"
#include "include/ieee80211.h"
/*===========================================================================*/
/* global variable */
static uint16_t status;
static int exitcode;
static EVP_MAC *hmac;
static EVP_MAC *cmac;
static EVP_MAC_CTX *ctxhmac;
static EVP_MAC_CTX *ctxcmac;
static OSSL_PARAM paramsmd5[3];
static OSSL_PARAM paramssha1[3];
static OSSL_PARAM paramssha256[3];
static OSSL_PARAM paramsaes128[3];
static uint8_t pmkcalculated[128];
static uint8_t pmkidcalculated[128];
static uint8_t ptkcalculated[256];
static uint8_t miccalculated[128];
static size_t psklen;
static char *pskstring;
static size_t essidlen;
static uint8_t essid[34];
static uint8_t macap[8];
static uint8_t macclient[8];
static uint8_t pmkid[18];
static uint8_t mic[18];
static uint8_t anonce[34];
static size_t eapollen;
static uint8_t eapol[1024];
static eapauth_t *eapptr;
static size_t eapauthlen;
static wpakey_t *wpak;
static int keyversion;
/*===========================================================================*/
static void showresult(void)
{
fprintf(stdout, "\n");
if((status & HAS_PMKID_LINE) == HAS_PMKID_LINE)
{
fprintf(stdout, "HASH FORMAT.: PMKID (WPA*01)\n");
}
if((status & HAS_EAPOL_LINE) == HAS_EAPOL_LINE)
{
fprintf(stdout, "HASH FORMAT.: EAPOL (WPA*02)\n");
}
if((status & HAS_ESSID) == HAS_ESSID)
{
fprintf(stdout, "ESSID.......: %s\n", essid);
}
if((status & HAS_MACAP) == HAS_MACAP)
{
fprintf(stdout, "MAC_AP......: %02x%02x%02x%02x%02x%02x\n",
macap[0], macap[1], macap[2], macap[3], macap[4], macap[5]);
}
if((status & HAS_MACCLIENT) == HAS_MACCLIENT)
{
fprintf(stdout, "MAC_CLIENT..: %02x%02x%02x%02x%02x%02x\n",
macclient[0], macclient[1], macclient[2], macclient[3], macclient[4], macclient[5]);
}
if((status & HAS_PSK) == HAS_PSK)
{
fprintf(stdout, "PSK.........: %s\n", pskstring);
}
if((status & HAS_PMK_CALC) == HAS_PMK_CALC)
{
fprintf(stdout, "PMK.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x (calculated)\n",
pmkcalculated[0], pmkcalculated[1], pmkcalculated[2], pmkcalculated[3], pmkcalculated[4], pmkcalculated[5], pmkcalculated[6], pmkcalculated[7], pmkcalculated[8], pmkcalculated[9], pmkcalculated[10], pmkcalculated[11], pmkcalculated[12], pmkcalculated[13], pmkcalculated[14], pmkcalculated[15],
pmkcalculated[16], pmkcalculated[17], pmkcalculated[18], pmkcalculated[19], pmkcalculated[20], pmkcalculated[21], pmkcalculated[22], pmkcalculated[23], pmkcalculated[24], pmkcalculated[25], pmkcalculated[26], pmkcalculated[27], pmkcalculated[28], pmkcalculated[29], pmkcalculated[30], pmkcalculated[31]);
}
if((status & HAS_PMK) == HAS_PMK)
{
fprintf(stdout, "PMK.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
pmkcalculated[0], pmkcalculated[1], pmkcalculated[2], pmkcalculated[3], pmkcalculated[4], pmkcalculated[5], pmkcalculated[6], pmkcalculated[7], pmkcalculated[8], pmkcalculated[9], pmkcalculated[10], pmkcalculated[11], pmkcalculated[12], pmkcalculated[13], pmkcalculated[14], pmkcalculated[15],
pmkcalculated[16], pmkcalculated[17], pmkcalculated[18], pmkcalculated[19], pmkcalculated[20], pmkcalculated[21], pmkcalculated[22], pmkcalculated[23], pmkcalculated[24], pmkcalculated[25], pmkcalculated[26], pmkcalculated[27], pmkcalculated[28], pmkcalculated[29], pmkcalculated[30], pmkcalculated[31]);
}
if((status & HAS_PMKID) == HAS_PMKID)
{
fprintf(stdout, "PMKID.......: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
pmkid[0], pmkid[1], pmkid[2], pmkid[3], pmkid[4], pmkid[5], pmkid[6], pmkid[7], pmkid[8], pmkid[9], pmkid[10], pmkid[11], pmkid[12], pmkid[13], pmkid[14], pmkid[15]);
if(((status & HAS_PMKID_CALC) == HAS_PMKID_CALC) || ((status & HAS_PMK) == HAS_PMK))
{
if(memcmp(pmkid, pmkidcalculated, 16) == 0)
{
exitcode = EXIT_SUCCESS_CONFIRMED;
fprintf(stdout, " (confirmed)\n");
}
else fprintf(stdout, " (not confirmed)\n");
}
else fprintf(stdout, " (not confirmed)\n");
}
if((status & HAS_MIC) == HAS_MIC)
{
if(keyversion == 2) fprintf(stdout, "KEY VERSION.: WPA2\n");
else if(keyversion == 1) fprintf(stdout, "KEY VERSION.: WPA1\n");
else if(keyversion == 3) fprintf(stdout, "KEY VERSION.: WPA2 KEY VERSION 3\n");
fprintf(stdout, "NONCE AP....: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
anonce[0], anonce[1], anonce[2], anonce[3], anonce[4], anonce[5], anonce[6], anonce[7], anonce[8], anonce[9], anonce[10], anonce[11], anonce[12], anonce[13], anonce[14], anonce[15],
anonce[16], anonce[17], anonce[18], anonce[19], anonce[20], anonce[21], anonce[22], anonce[23], anonce[24], anonce[25], anonce[26], anonce[27], anonce[28], anonce[29], anonce[30], anonce[31]);
fprintf(stdout, "NONCE CLIENT: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
wpak->nonce[0], wpak->nonce[1], wpak->nonce[2], wpak->nonce[3], wpak->nonce[4], wpak->nonce[5], wpak->nonce[6], wpak->nonce[7], wpak->nonce[8], wpak->nonce[9], wpak->nonce[10], wpak->nonce[11], wpak->nonce[12], wpak->nonce[13], wpak->nonce[14], wpak->nonce[15],
wpak->nonce[16], wpak->nonce[17], wpak->nonce[18], wpak->nonce[19], wpak->nonce[20], wpak->nonce[21], wpak->nonce[22], wpak->nonce[23], wpak->nonce[24], wpak->nonce[25], wpak->nonce[26], wpak->nonce[27], wpak->nonce[28], wpak->nonce[29], wpak->nonce[30], wpak->nonce[31]);
if((status & HAS_PTK_CALC) == HAS_PTK_CALC)
{
fprintf(stdout, "PTK.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x (calculated)\n",
ptkcalculated[0], ptkcalculated[1], ptkcalculated[2], ptkcalculated[3], ptkcalculated[4], ptkcalculated[5], ptkcalculated[6], ptkcalculated[7], ptkcalculated[8], ptkcalculated[9], ptkcalculated[10], ptkcalculated[11], ptkcalculated[12], ptkcalculated[13], ptkcalculated[14], ptkcalculated[15],
ptkcalculated[16], ptkcalculated[17], ptkcalculated[18], ptkcalculated[19], ptkcalculated[20], ptkcalculated[21], ptkcalculated[22], ptkcalculated[23], ptkcalculated[24], ptkcalculated[25], ptkcalculated[26], ptkcalculated[27], ptkcalculated[28], ptkcalculated[29], ptkcalculated[30], ptkcalculated[31]);
fprintf(stdout, "KCK.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x (calculated)\n",
ptkcalculated[0], ptkcalculated[1], ptkcalculated[2], ptkcalculated[3], ptkcalculated[4], ptkcalculated[5], ptkcalculated[6], ptkcalculated[7], ptkcalculated[8], ptkcalculated[9], ptkcalculated[10], ptkcalculated[11], ptkcalculated[12], ptkcalculated[13], ptkcalculated[14], ptkcalculated[15]);
fprintf(stdout, "KEK.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x (calculated)\n",
ptkcalculated[16], ptkcalculated[17], ptkcalculated[18], ptkcalculated[19], ptkcalculated[20], ptkcalculated[21], ptkcalculated[22], ptkcalculated[23], ptkcalculated[24], ptkcalculated[25], ptkcalculated[26], ptkcalculated[27], ptkcalculated[28], ptkcalculated[29], ptkcalculated[30], ptkcalculated[31]);
}
fprintf(stdout, "MIC.........: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
mic[0], mic[1], mic[2], mic[3], mic[4], mic[5], mic[6], mic[7], mic[8], mic[9], mic[10], mic[11], mic[12], mic[13], mic[14], mic[15]);
if(memcmp(mic, miccalculated, 16) == 0)
{
fprintf(stdout, " (confirmed)\n");
if(status & HAS_PMKID_CALC)
{
fprintf(stdout, "PMKID.......: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x (calculated)\n",
pmkidcalculated[0], pmkidcalculated[1], pmkidcalculated[2], pmkidcalculated[3], pmkidcalculated[4], pmkidcalculated[5], pmkidcalculated[6], pmkidcalculated[7], pmkidcalculated[8], pmkidcalculated[9], pmkidcalculated[10], pmkidcalculated[11], pmkidcalculated[12], pmkidcalculated[13], pmkidcalculated[14], pmkidcalculated[15]);
}
exitcode = EXIT_SUCCESS_CONFIRMED;
}
else fprintf(stdout, " (not confirmed)\n");
}
fprintf(stdout, "\n");
return;
}
/*===========================================================================*/
static bool genmicwpa2kv3(void)
{
static uint8_t eapoltmp[1024];
memset(eapoltmp, 0, 1024);
memcpy(eapoltmp, eapol, eapollen);
if(!EVP_MAC_init(ctxcmac, ptkcalculated, 16, paramsaes128)) return false;
if(!EVP_MAC_update(ctxcmac, eapoltmp, eapollen)) return false;
if(!EVP_MAC_final(ctxcmac, eapoltmp, NULL, eapollen)) return false;
memcpy(miccalculated, eapoltmp, 16);
return true;
}
/*===========================================================================*/
static bool genmicwpa1(void)
{
static uint8_t eapoltmp[1024];
memset(eapoltmp, 0, 1024);
memcpy(eapoltmp, eapol, eapollen);
if(!EVP_MAC_init(ctxhmac, ptkcalculated, 16, paramsmd5)) return false;
if(!EVP_MAC_update(ctxhmac, eapoltmp, eapollen)) return false;
if(!EVP_MAC_final(ctxhmac, eapoltmp, NULL, eapollen)) return false;
memcpy(miccalculated, eapoltmp, 16);
return true;
}
/*===========================================================================*/
static bool genmicwpa2(void)
{
static uint8_t eapoltmp[1024];
memset(eapoltmp, 0, 1024);
memcpy(eapoltmp, eapol, eapollen);
if(!EVP_MAC_init(ctxhmac, ptkcalculated, 16, paramssha1)) return false;
if(!EVP_MAC_update(ctxhmac, eapoltmp, eapollen)) return false;
if(!EVP_MAC_final(ctxhmac, eapoltmp, NULL, eapollen)) return false;
memcpy(miccalculated, eapoltmp, 16);
return true;
}
/*===========================================================================*/
static bool genptkwpa2kv3(void)
{
static uint8_t *pkeptr;
memset(&ptkcalculated, 0, 128);
pkeptr = ptkcalculated;
pkeptr[0] = 1;
pkeptr[1] = 0;
pkeptr += 2;
memcpy(pkeptr, "Pairwise key expansion", 22);
if(memcmp(macap, macclient, 6) < 0)
{
memcpy(pkeptr +22, macap, 6);
memcpy(pkeptr +28, macclient, 6);
}
else
{
memcpy(pkeptr +22, macclient, 6);
memcpy(pkeptr +28, macap, 6);
}
if(memcmp(anonce, wpak->nonce, 32) < 0)
{
memcpy (pkeptr +34, anonce, 32);
memcpy (pkeptr +66, wpak->nonce, 32);
}
else
{
memcpy (pkeptr +34, wpak->nonce, 32);
memcpy (pkeptr +66, anonce, 32);
}
ptkcalculated[100] = 0x80;
ptkcalculated[101] = 1;
if(!EVP_MAC_init(ctxhmac, pmkcalculated, 32, paramssha256)) return false;
if(!EVP_MAC_update(ctxhmac, ptkcalculated, 102)) return false;
if(!EVP_MAC_final(ctxhmac, ptkcalculated, NULL, 128)) return false;
return true;
}
/*===========================================================================*/
static bool genptkwpa12(void)
{
static uint8_t *pkeptr;
pkeptr = ptkcalculated;
memcpy(pkeptr, "Pairwise key expansion", 23);
if(memcmp(macap, macclient, 6) < 0)
{
memcpy(pkeptr +23, macap, 6);
memcpy(pkeptr +29, macclient, 6);
}
else
{
memcpy(pkeptr +23, macclient, 6);
memcpy(pkeptr +29, macap, 6);
}
if(memcmp(anonce, wpak->nonce, 32) < 0)
{
memcpy (pkeptr +35, anonce, 32);
memcpy (pkeptr +67, wpak->nonce, 32);
}
else
{
memcpy (pkeptr +35, wpak->nonce, 32);
memcpy (pkeptr +67, anonce, 32);
}
if(!EVP_MAC_init(ctxhmac, pmkcalculated, 32, paramssha1)) return false;
if(!EVP_MAC_update(ctxhmac, ptkcalculated, 100)) return false;
if(!EVP_MAC_final(ctxhmac, ptkcalculated, NULL, 128)) return false;
return true;
}
/*===========================================================================*/
static bool genpmkid(void)
{
static const char *pmkname = "PMK Name";
memcpy(pmkidcalculated, pmkname, 8);
memcpy(pmkidcalculated +8, macap, 6);
memcpy(pmkidcalculated +14, macclient, 6);
if(!EVP_MAC_init(ctxhmac, pmkcalculated, 32, paramssha1)) return false;
if(!EVP_MAC_update(ctxhmac, pmkidcalculated, 20)) return false;
if(!EVP_MAC_final(ctxhmac, pmkidcalculated, NULL, 20)) return false;
status |= HAS_PMKID_CALC;
return true;
}
/*===========================================================================*/
static bool genpmk(char *psk)
{
memset(pmkcalculated, 0, 32);
if(PKCS5_PBKDF2_HMAC_SHA1(psk, psklen, essid, essidlen, 4096, 32, pmkcalculated) == 0) return false;
status |= HAS_PMK_CALC;
return true;
}
/*===========================================================================*/
static size_t hex2bin(const char *str, uint8_t *bytes, size_t blen)
{
size_t pos;
uint8_t idx0;
uint8_t idx1;
uint8_t hashmap[] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567
0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>?
0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // HIJKLMNO
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // PQRSTUVW
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // XYZ[\]^_
0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // `abcdefg
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // hijklmno
};
memset(bytes, 0, blen);
pos = 0;
while(str[pos+0] != 0)
{
if(str[pos+0] < '0') return 0;
if(str[pos+0] > 'f') return 0;
if((str[pos+0] > '9') && (str[pos+0] < 'A')) return 0;
if((str[pos+0] > 'F') && (str[pos+0] < 'a')) return 0;
if(str[pos+1] < '0') return 0;
if(str[pos+1] > 'f') return 0;
if((str[pos+1] > '9') && (str[pos+1] < 'A')) return 0;
if((str[pos+1] > 'F') && (str[pos+1] < 'a')) return 0;
idx0 = ((uint8_t)str[pos+0] & 0x1F) ^ 0x10;
idx1 = ((uint8_t)str[pos+1] & 0x1F) ^ 0x10;
bytes[pos/2] = (uint8_t)(hashmap[idx0] << 4) | hashmap[idx1];
pos += 2;
if(str[pos+0] == '*') return pos/2;
if(pos/2 > blen) return 0;
};
if((pos %2) != 0) return 0;
return pos/2;
}
/*===========================================================================*/
static bool parsehashlinestring(char *hashlinestring)
{
static size_t hlen;
static size_t plen;
static size_t flen;
static const char *wpa1 = "WPA*01*";
static const char *wpa2 = "WPA*02*";
hlen = strlen(hashlinestring);
if(hlen < 71) return false;
plen = 7;
if(memcmp(wpa1, hashlinestring, 7) == 0)
{
flen = hex2bin(&hashlinestring[plen], pmkid, 16);
if(flen != 16) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
flen = hex2bin(&hashlinestring[plen], macap, 6);
if(flen != 6) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
flen = hex2bin(&hashlinestring[plen], macclient, 6);
if(flen != 6) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
essidlen = 0;
essidlen = hex2bin(&hashlinestring[plen], essid, 34);
if((essidlen == 0) || (essidlen > 32)) return false;
plen += essidlen *2;
if(hashlinestring[plen++] != '*') return false;
status |= HAS_PMKID_LINE;
status |= HAS_PMKID;
status |= HAS_ESSID;
status |= HAS_MACAP;
status |= HAS_MACCLIENT;
return true;
}
if(memcmp(wpa2, hashlinestring, 7) == 0)
{
flen = hex2bin(&hashlinestring[plen], mic, 16);
if(flen != 16) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
flen = hex2bin(&hashlinestring[plen], macap, 6);
if(flen != 6) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
flen = hex2bin(&hashlinestring[plen], macclient, 6);
if(flen != 6) return false;
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
essidlen = 0;
essidlen = hex2bin(&hashlinestring[plen], essid, 34);
if((essidlen == 0) || (essidlen > 32)) return false;
plen += essidlen *2;
if(hashlinestring[plen++] != '*') return false;
flen = hex2bin(&hashlinestring[plen], anonce, 32);
plen += flen *2;
if(hashlinestring[plen++] != '*') return false;
eapollen = 0;
eapollen = hex2bin(&hashlinestring[plen], eapol, 1024);
eapptr = (eapauth_t*)eapol;
eapauthlen = ntohs(eapptr->len);
if(eapollen < eapauthlen +4) return false;
plen += eapollen *2;
if(hashlinestring[plen++] != '*') return false;
wpak = (wpakey_t*)(eapol +EAPAUTH_SIZE);
keyversion = ntohs(wpak->keyinfo) & WPA_KEY_INFO_TYPE_MASK;
status |= HAS_EAPOL_LINE;
status |= HAS_MIC;
status |= HAS_ESSID;
status |= HAS_MACAP;
status |= HAS_MACCLIENT;
return true;
}
return false;
}
/*===========================================================================*/
static size_t chop(char *buffer, size_t len)
{
static char *ptr;
ptr = buffer +len -1;
while(len)
{
if (*ptr != '\n') break;
*ptr-- = 0;
len--;
}
while(len)
{
if (*ptr != '\r') break;
*ptr-- = 0;
len--;
}
return len;
}
/*---------------------------------------------------------------------------*/
static size_t fgetline(FILE *inputstream, size_t size, char *buffer)
{
static size_t len;
static char *buffptr;
if(feof(inputstream)) return 0;
buffptr = fgets (buffer, size, inputstream);
if(buffptr == NULL) return 0;
len = strlen(buffptr);
len = chop(buffptr, len);
return len;
}
/*===========================================================================*/
static bool evpdeinitwpa(void)
{
if(ctxhmac != NULL)
{
EVP_MAC_CTX_free(ctxhmac);
EVP_MAC_free(hmac);
}
if(ctxcmac != NULL)
{
EVP_MAC_CTX_free(ctxcmac);
EVP_MAC_free(cmac);
}
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
return true;
}
/*===========================================================================*/
static bool evpinitwpa(void)
{
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
hmac = NULL;
ctxhmac = NULL;
cmac = NULL;
ctxcmac = NULL;
hmac = EVP_MAC_fetch(NULL, "hmac", NULL);
if(hmac == NULL) return false;
cmac = EVP_MAC_fetch(NULL, "cmac", NULL);
if(cmac == NULL) return false;
char md5[] = "md5";
paramsmd5[0] = OSSL_PARAM_construct_utf8_string("digest", md5, 0);
paramsmd5[1] = OSSL_PARAM_construct_end();
char sha1[] = "sha1";
paramssha1[0] = OSSL_PARAM_construct_utf8_string("digest", sha1, 0);
paramssha1[1] = OSSL_PARAM_construct_end();
char sha256[] = "sha256";
paramssha256[0] = OSSL_PARAM_construct_utf8_string("digest", sha256, 0);
paramssha256[1] = OSSL_PARAM_construct_end();
char aes[] = "aes-1280-cbc";
paramsaes128[0] = OSSL_PARAM_construct_utf8_string("cipher", aes, 0);
paramsaes128[1] = OSSL_PARAM_construct_end();
ctxhmac = EVP_MAC_CTX_new(hmac);
if(ctxhmac == NULL) return false;
ctxcmac = EVP_MAC_CTX_new(cmac);
if(ctxcmac == NULL) return false;
return true;
}
/*===========================================================================*/
__attribute__ ((noreturn))
static inline void version(char *eigenname)
{
fprintf(stdout, "%s %s (C) %s ZeroBeat\n", eigenname, VERSION_TAG, VERSION_YEAR);
exit(EXIT_SUCCESS);
}
/*---------------------------------------------------------------------------*/
__attribute__ ((noreturn))
static inline void usage(char *eigenname)
{
fprintf(stdout, "%s %s (C) %s ZeroBeat\n"
"usage : %s <options>\n"
"\n"
"short options:\n"
"-l <hash line> : input hashcat hash line (-m 22000)\n"
"-e <ESSID> : input Network Name (ESSID)\n"
"-p <PSK> : input Pre Shared Key (PSK) or Plain Master Key (PMK)\n"
"-p - : read Pre Shared Key (PSK) from stdin\n"
" : small lists only\n"
"\n"
"long options:\n"
"--help : show this help\n"
"--version : show version\n\n"
"exit codes:\n"
"0 = PSK/PMK confirmed\n"
"1 = ERROR occurred\n"
"2 = PSK/PMK unconfirmed\n"
"\n"
"Important notice:\n"
"%s does not do NONCE ERROR CORRECTIONS\n"
"in case of a packet loss, you get a wrong PTK\n"
"\n",
eigenname, VERSION_TAG, VERSION_YEAR, eigenname, eigenname);
exit(EXIT_SUCCESS);
}
/*---------------------------------------------------------------------------*/
__attribute__ ((noreturn))
static inline void usageerror(char *eigenname)
{
fprintf(stdout, "%s %s (C) %s by ZeroBeat\n"
"usage: %s -h for help\n", eigenname, VERSION_TAG, VERSION_YEAR, eigenname);
exit(EXIT_FAILURE);
}
/*===========================================================================*/
int main(int argc, char *argv[])
{
static int auswahl;
static int index;
static char *hashlinestring;
static char pskbuffer[128];
static const char *short_options = "l:e:p:m:a:c:hv";
static const struct option long_options[] =
{
{"version", no_argument, NULL, HCX_VERSION},
{"help", no_argument, NULL, HCX_HELP},
{NULL, 0, NULL, 0}
};
auswahl = -1;
index = 0;
optind = 1;
optopt = 0;
exitcode = EXIT_SUCCESS_UNCONFIRMED;
status = 0;
essidlen = 0;
hashlinestring = NULL;
pskstring = NULL;
while((auswahl = getopt_long(argc, argv, short_options, long_options, &index)) != -1)
{
switch (auswahl)
{
case HCX_HASHLINE:
hashlinestring = optarg;
break;
case HCX_PSK:
pskstring = optarg;
break;
case HCX_HELP:
usage(basename(argv[0]));
break;
case HCX_VERSION:
version(basename(argv[0]));
break;
case '?':
usageerror(basename(argv[0]));
break;
}
}
if(argc < 2)
{
fprintf(stderr, "no option selected\nrun %s --help to get more information\n", (basename(argv[0])));
exit(EXIT_FAILURE);
}
if(evpinitwpa() == false)
{
fprintf(stderr, "\nEVP API error\n");
return EXIT_FAILURE;
}
if(hashlinestring != NULL)
{
if(parsehashlinestring(hashlinestring) == false)
{
fprintf(stdout, "hash line error\n");
return EXIT_FAILURE;
}
}
if(pskstring != NULL)
{
psklen = strlen(pskstring);
if((psklen >= 8) &&(psklen < 63))
{
status |= HAS_PSK;
if((status & HAS_ESSID) == HAS_ESSID)
{
if(genpmk(pskstring) == false)
{
fprintf(stderr, "\nPMK error\n");
return EXIT_FAILURE;
}
}
}
else if(psklen == 64)
{
if(hex2bin(pskstring, pmkcalculated, 32) != 32)
{
fprintf(stderr, "\nPMK error\n");
return EXIT_FAILURE;
}
status |= HAS_PMK;
}
else if(strncmp(pskstring, "-", 1) == 0)
{
if((status & HAS_ESSID) == HAS_ESSID)
{
if((status & HAS_PMKID) == HAS_PMKID)
{
while(1)
{
if((psklen = fgetline(stdin, 128, pskbuffer)) == 0) break;
if((psklen < 8) || (psklen > 63)) continue;
{
if(genpmk(pskbuffer) == false)
{
fprintf(stderr, "\nPMK error\n");
exit(EXIT_FAILURE);
}
if(genpmkid() == false)
{
fprintf(stderr, "\nPMK error\n");
exit(EXIT_FAILURE);
}
if(memcmp(pmkid, pmkidcalculated, 16) == 0)
{
pskstring = pskbuffer;
status |= HAS_PSK;
showresult();
exit(EXIT_SUCCESS_CONFIRMED);
}
}
}
if(evpdeinitwpa() == false)
{
fprintf(stdout, "EVP API error\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
if((status & HAS_MIC) == HAS_MIC)
{
if(keyversion == 2)
{
while(1)
{
if((psklen = fgetline(stdin, 128, pskbuffer)) == 0) break;
if((psklen < 8) || (psklen > 63)) continue;
if(genpmk(pskbuffer) == false) exit(EXIT_FAILURE);
if(genptkwpa12() == false) exit(EXIT_FAILURE);
if(genmicwpa2() == false) exit(EXIT_FAILURE);
if(memcmp(mic, miccalculated, 16) == 0)
{
if(genpmkid() == false) exit(EXIT_FAILURE);
pskstring = pskbuffer;
status |= HAS_PSK;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
showresult();
exit(EXIT_SUCCESS_CONFIRMED);
}
}
if(evpdeinitwpa() == false) exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
if(keyversion == 1)
{
while(1)
{
if((psklen = fgetline(stdin, 128, pskbuffer)) == 0) break;
if((psklen < 8) || (psklen > 63)) continue;
if(genpmk(pskbuffer) == false) exit(EXIT_FAILURE);
if(genptkwpa12() == false) exit(EXIT_FAILURE);
if(genmicwpa1() == false) exit(EXIT_FAILURE);
if(memcmp(mic, miccalculated, 16) == 0)
{
if(genpmkid() == false) exit(EXIT_FAILURE);
pskstring = pskbuffer;
status |= HAS_PSK;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
showresult();
exit(EXIT_SUCCESS_CONFIRMED);
}
}
if(evpdeinitwpa() == false) exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
if(keyversion == 3)
{
while(1)
{
if((psklen = fgetline(stdin, 128, pskbuffer)) == 0) break;
if((psklen < 8) || (psklen > 63)) continue;
if(genpmk(pskbuffer) == false) exit(EXIT_FAILURE);
if(genptkwpa2kv3() == false) exit(EXIT_FAILURE);
if(genmicwpa2kv3() == false) exit(EXIT_FAILURE);
if(memcmp(mic, miccalculated, 16) == 0)
{
if(genpmkid() == false) exit(EXIT_FAILURE);
pskstring = pskbuffer;
status |= HAS_PSK;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
showresult();
exit(EXIT_SUCCESS_CONFIRMED);
}
}
if(evpdeinitwpa() == false) exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
if(evpdeinitwpa() == false) exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
}
}
}
if((((status & HAS_PMK_CALC) == HAS_PMK_CALC) || ((status & HAS_PMK) == HAS_PMK)) && ((status & HAS_PMKID) == HAS_PMKID))
{
if(genpmkid() == false)
{
fprintf(stderr, "\nPMKID error\n");
return EXIT_FAILURE;
}
}
if((status & HAS_EAPOL_LINE) == HAS_EAPOL_LINE)
{
if((keyversion == 0) || (keyversion > 3))
{
fprintf(stderr, "\nkey version error\n");
return EXIT_FAILURE;
}
if(((status & HAS_PMK_CALC) == HAS_PMK_CALC) || ((status & HAS_PMK) == HAS_PMK))
{
if(keyversion < 3)
{
if(genptkwpa12() == false) return false;
if(keyversion == 2)
{
if(genmicwpa2() == false) return false;
if(genpmkid() == false) return false;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
}
if(keyversion == 1)
{
if(genmicwpa1() == false) return false;
if(genpmkid() == false) return false;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
}
}
else
{
if(genptkwpa2kv3() == false) return false;
if(genmicwpa2kv3() == false) return false;
if(genpmkid() == false) return false;
status |= HAS_PTK_CALC;
status |= HAS_PMKID_CALC;
}
}
}
showresult();
if(evpdeinitwpa() == false)
{
fprintf(stdout, "EVP API error\n");
exit(EXIT_FAILURE);
}
exit(exitcode);
}
/*===========================================================================*/
|
445d4dd66c5c76654372271b15f774b2abe6768d
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/graphics/p5-OpenGL/files/patch-gl_util.c
|
e7224d17dbd39b6f79434ffc961886e250883cee
|
[
"BSD-2-Clause"
] |
permissive
|
freebsd/freebsd-ports
|
86f2e89d43913412c4f6b2be3e255bc0945eac12
|
605a2983f245ac63f5420e023e7dce56898ad801
|
refs/heads/main
| 2023-08-30T21:46:28.720924
| 2023-08-30T19:33:44
| 2023-08-30T19:33:44
| 1,803,961
| 916
| 918
|
NOASSERTION
| 2023-09-08T04:06:26
| 2011-05-26T11:15:35
| null |
UTF-8
|
C
| false
| false
| 372
|
c
|
patch-gl_util.c
|
--- gl_util.c.orig 2011-07-07 08:39:22.000000000 -0500
+++ gl_util.c 2011-10-12 22:09:31.520959086 -0500
@@ -756,6 +756,12 @@ int gl_component_count(GLenum format, GL
/* 18 */
#ifdef GL_EXT_cmyka
+# ifndef GL_CMYK
+# define GL_CMYK GL_CMYK_EXT
+# endif
+# ifndef GL_CMYKA
+# define GL_CMYKA GL_CMYKA_EXT
+# endif
case GL_CMYK:
n = 4; break;
case GL_CMYKA:
|
9cbbefa7f21d3b055cb29258e9796571e4920301
|
591045a1915d1f2c0f13174fb1dfee9043e50d17
|
/src/platform.c
|
5a00e57392e6b9ecd9c91619ac48fe01ec885ba2
|
[
"ISC"
] |
permissive
|
Tangent128/luasdl2
|
d599e8c04ce7f14833e2ce13217973913a2bddc2
|
5dbcdc70869e50b4e53bdc894f587eacd34a9010
|
refs/heads/master
| 2023-08-18T16:07:22.799736
| 2022-06-08T15:53:27
| 2022-06-08T15:53:27
| 27,103,407
| 404
| 103
|
ISC
| 2022-11-08T05:06:58
| 2014-11-25T01:26:14
|
C
|
UTF-8
|
C
| false
| false
| 1,146
|
c
|
platform.c
|
/*
* platform.c -- platform management
*
* Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
*
* 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 <SDL.h>
#include "platform.h"
/*
* SDL.getPlatform()
*
* Returns:
* The platform
*/
static int
l_getPlatform(lua_State *L)
{
return commonPush(L, "s", SDL_GetPlatform());
}
const struct luaL_Reg PlatformFunctions[] = {
{ "getPlatform", l_getPlatform },
{ NULL, NULL }
};
|
88816d5055b9d8f000ab6bc6405560b448a5e7df
|
8403fe1593ebaf78dec56af7706637b3ceee4da2
|
/macaw-aarch32/tests/arm/test-conditional-mixed.c
|
1a42563ff0ed0e11a2fa6a41943473e5d13716d8
|
[
"BSD-3-Clause"
] |
permissive
|
GaloisInc/macaw
|
0bc8c952c5b91f2b28b313c766b5b1f07ebae4ce
|
299c227a77cbad480175e64f8ef2ae27070eb7ad
|
refs/heads/master
| 2023-08-25T07:31:17.289316
| 2023-08-08T20:04:25
| 2023-08-21T12:16:10
| 105,173,883
| 188
| 20
|
BSD-3-Clause
| 2023-09-11T17:26:33
| 2017-09-28T16:42:26
|
Haskell
|
UTF-8
|
C
| false
| false
| 250
|
c
|
test-conditional-mixed.c
|
#include "util.h"
int g = -11;
void __attribute__((noinline, target("thumb"))) f() {
if(g > 0) {
g = g + 1;
}
g = g - 1090;
}
void _start() {
// Making this into a call to ensure that the conditional is thumb-ified
f();
EXIT();
}
|
675511c15d839a04a4a9b7378adddebcca842d1a
|
d8c8f4148940cd9c93bb0692af8c5004f47af05e
|
/xUSL/DF/DfX/DfCmn2Rev4.c
|
d2742005fe9bdcf3bb358c825b8c5d789e15cd27
|
[
"MIT"
] |
permissive
|
openSIL/openSIL
|
92213cc94dd4c6d6c43fedeaedd96537001e182f
|
0f39fbc2454af9a67fc84a88093bcd2f2c8dd887
|
refs/heads/main
| 2023-08-19T11:48:14.911453
| 2023-08-07T20:50:54
| 2023-08-07T20:50:54
| 652,124,068
| 233
| 14
| null | 2023-06-28T15:55:29
| 2023-06-11T06:54:24
|
C
|
UTF-8
|
C
| false
| false
| 1,621
|
c
|
DfCmn2Rev4.c
|
/**
* @file DfCmn2Rev4.c
* @brief Declaration of DfX Cmn2Rev transfer block
*/
/* Copyright 2023 Advanced Micro Devices, Inc. All rights reserved. */
// SPDX-License-Identifier: MIT
#include <DF/Common/DfCmn2Rev.h>
#include "DfXBaseFabricTopology.h"
#include "DfXFabricRegisterAcc.h"
#include "FabricAcpiDomain/FabricAcpiDomainInfo.h"
DF_COMMON_2_REV_XFER_BLOCK DfCmn2Rev4Xfer = {
.DfFabricRegisterAccRead = DfXFabricRegisterAccRead,
.DfFabricRegisterAccWrite = DfXFabricRegisterAccWrite,
.DfGetNumberOfProcessorsPresent = DfXGetNumberOfProcessorsPresent,
.DfGetNumberOfSystemDies = DfXGetNumberOfSystemDies,
.DfGetNumberOfSystemRootBridges = DfXGetNumberOfSystemRootBridges,
.DfGetNumberOfRootBridgesOnSocket = DfXGetNumberOfRootBridgesOnSocket,
.DfGetNumberOfRootBridgesOnDie = DfXGetNumberOfRootBridgesOnDie,
.DfGetDieSystemOffset = DfXGetDieSystemOffset,
.DfGetDeviceMapOnDie = DfXGetDeviceMapOnDie,
.DfGetHostBridgeBusBase = DfXGetHostBridgeBusBase,
.DfGetHostBridgeBusLimit = DfXGetHostBridgeBusLimit,
.DfGetPhysRootBridgeNumber = DfXGetPhysRootBridgeNumber,
.DfFindComponentLocationMap = DfXFindComponentLocationMap,
.DfBaseFabricTopologyConstructor = DfXBaseFabricTopologyConstructor,
.DfBuildDomainInfo = DfXBuildDomainInfo
};
|
6139d67a5edc389a34c63e693b07cbeaecf7d732
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/net/wireless/iwlwifi/mvm/utils.c
|
0d9e08160fec3836e5275648859536f63137cb2d
|
[
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 15,106
|
c
|
utils.c
|
/******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <net/mac80211.h>
#include "iwl-debug.h"
#include "iwl-io.h"
#include "mvm.h"
#include "fw-api-rs.h"
/*
* Will return 0 even if the cmd failed when RFKILL is asserted unless
* CMD_WANT_SKB is set in cmd->flags.
*/
int iwl_mvm_send_cmd(struct iwl_mvm *mvm, struct iwl_host_cmd *cmd)
{
int ret;
/*
* Synchronous commands from this op-mode must hold
* the mutex, this ensures we don't try to send two
* (or more) synchronous commands at a time.
*/
if (!(cmd->flags & CMD_ASYNC))
lockdep_assert_held(&mvm->mutex);
ret = iwl_trans_send_cmd(mvm->trans, cmd);
/*
* If the caller wants the SKB, then don't hide any problems, the
* caller might access the response buffer which will be NULL if
* the command failed.
*/
if (cmd->flags & CMD_WANT_SKB)
return ret;
/* Silently ignore failures if RFKILL is asserted */
if (!ret || ret == -ERFKILL)
return 0;
return ret;
}
int iwl_mvm_send_cmd_pdu(struct iwl_mvm *mvm, u8 id,
u32 flags, u16 len, const void *data)
{
struct iwl_host_cmd cmd = {
.id = id,
.len = { len, },
.data = { data, },
.flags = flags,
};
return iwl_mvm_send_cmd(mvm, &cmd);
}
/*
* We assume that the caller set the status to the sucess value
*/
int iwl_mvm_send_cmd_status(struct iwl_mvm *mvm, struct iwl_host_cmd *cmd,
u32 *status)
{
struct iwl_rx_packet *pkt;
struct iwl_cmd_response *resp;
int ret, resp_len;
lockdep_assert_held(&mvm->mutex);
/*
* Only synchronous commands can wait for status,
* we use WANT_SKB so the caller can't.
*/
if (WARN_ONCE(cmd->flags & (CMD_ASYNC | CMD_WANT_SKB),
"cmd flags %x", cmd->flags))
return -EINVAL;
cmd->flags |= CMD_SYNC | CMD_WANT_SKB;
ret = iwl_trans_send_cmd(mvm->trans, cmd);
if (ret == -ERFKILL) {
/*
* The command failed because of RFKILL, don't update
* the status, leave it as success and return 0.
*/
return 0;
} else if (ret) {
return ret;
}
pkt = cmd->resp_pkt;
/* Can happen if RFKILL is asserted */
if (!pkt) {
ret = 0;
goto out_free_resp;
}
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
ret = -EIO;
goto out_free_resp;
}
resp_len = le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK;
if (WARN_ON_ONCE(resp_len != sizeof(pkt->hdr) + sizeof(*resp))) {
ret = -EIO;
goto out_free_resp;
}
resp = (void *)pkt->data;
*status = le32_to_cpu(resp->status);
out_free_resp:
iwl_free_resp(cmd);
return ret;
}
/*
* We assume that the caller set the status to the sucess value
*/
int iwl_mvm_send_cmd_pdu_status(struct iwl_mvm *mvm, u8 id, u16 len,
const void *data, u32 *status)
{
struct iwl_host_cmd cmd = {
.id = id,
.len = { len, },
.data = { data, },
};
return iwl_mvm_send_cmd_status(mvm, &cmd, status);
}
#define IWL_DECLARE_RATE_INFO(r) \
[IWL_RATE_##r##M_INDEX] = IWL_RATE_##r##M_PLCP
/*
* Translate from fw_rate_index (IWL_RATE_XXM_INDEX) to PLCP
*/
static const u8 fw_rate_idx_to_plcp[IWL_RATE_COUNT] = {
IWL_DECLARE_RATE_INFO(1),
IWL_DECLARE_RATE_INFO(2),
IWL_DECLARE_RATE_INFO(5),
IWL_DECLARE_RATE_INFO(11),
IWL_DECLARE_RATE_INFO(6),
IWL_DECLARE_RATE_INFO(9),
IWL_DECLARE_RATE_INFO(12),
IWL_DECLARE_RATE_INFO(18),
IWL_DECLARE_RATE_INFO(24),
IWL_DECLARE_RATE_INFO(36),
IWL_DECLARE_RATE_INFO(48),
IWL_DECLARE_RATE_INFO(54),
};
int iwl_mvm_legacy_rate_to_mac80211_idx(u32 rate_n_flags,
enum ieee80211_band band)
{
int rate = rate_n_flags & RATE_LEGACY_RATE_MSK;
int idx;
int band_offset = 0;
/* Legacy rate format, search for match in table */
if (band == IEEE80211_BAND_5GHZ)
band_offset = IWL_FIRST_OFDM_RATE;
for (idx = band_offset; idx < IWL_RATE_COUNT_LEGACY; idx++)
if (fw_rate_idx_to_plcp[idx] == rate)
return idx - band_offset;
return -1;
}
u8 iwl_mvm_mac80211_idx_to_hwrate(int rate_idx)
{
/* Get PLCP rate for tx_cmd->rate_n_flags */
return fw_rate_idx_to_plcp[rate_idx];
}
int iwl_mvm_rx_fw_error(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_error_resp *err_resp = (void *)pkt->data;
IWL_ERR(mvm, "FW Error notification: type 0x%08X cmd_id 0x%02X\n",
le32_to_cpu(err_resp->error_type), err_resp->cmd_id);
IWL_ERR(mvm, "FW Error notification: seq 0x%04X service 0x%08X\n",
le16_to_cpu(err_resp->bad_cmd_seq_num),
le32_to_cpu(err_resp->error_service));
IWL_ERR(mvm, "FW Error notification: timestamp 0x%16llX\n",
le64_to_cpu(err_resp->timestamp));
return 0;
}
/*
* Returns the first antenna as ANT_[ABC], as defined in iwl-config.h.
* The parameter should also be a combination of ANT_[ABC].
*/
u8 first_antenna(u8 mask)
{
BUILD_BUG_ON(ANT_A != BIT(0)); /* using ffs is wrong if not */
if (WARN_ON_ONCE(!mask)) /* ffs will return 0 if mask is zeroed */
return BIT(0);
return BIT(ffs(mask) - 1);
}
/*
* Toggles between TX antennas to send the probe request on.
* Receives the bitmask of valid TX antennas and the *index* used
* for the last TX, and returns the next valid *index* to use.
* In order to set it in the tx_cmd, must do BIT(idx).
*/
u8 iwl_mvm_next_antenna(struct iwl_mvm *mvm, u8 valid, u8 last_idx)
{
u8 ind = last_idx;
int i;
for (i = 0; i < RATE_MCS_ANT_NUM; i++) {
ind = (ind + 1) % RATE_MCS_ANT_NUM;
if (valid & BIT(ind))
return ind;
}
WARN_ONCE(1, "Failed to toggle between antennas 0x%x", valid);
return last_idx;
}
static struct {
char *name;
u8 num;
} advanced_lookup[] = {
{ "NMI_INTERRUPT_WDG", 0x34 },
{ "SYSASSERT", 0x35 },
{ "UCODE_VERSION_MISMATCH", 0x37 },
{ "BAD_COMMAND", 0x38 },
{ "NMI_INTERRUPT_DATA_ACTION_PT", 0x3C },
{ "FATAL_ERROR", 0x3D },
{ "NMI_TRM_HW_ERR", 0x46 },
{ "NMI_INTERRUPT_TRM", 0x4C },
{ "NMI_INTERRUPT_BREAK_POINT", 0x54 },
{ "NMI_INTERRUPT_WDG_RXF_FULL", 0x5C },
{ "NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64 },
{ "NMI_INTERRUPT_HOST", 0x66 },
{ "NMI_INTERRUPT_ACTION_PT", 0x7C },
{ "NMI_INTERRUPT_UNKNOWN", 0x84 },
{ "NMI_INTERRUPT_INST_ACTION_PT", 0x86 },
{ "ADVANCED_SYSASSERT", 0 },
};
static const char *desc_lookup(u32 num)
{
int i;
for (i = 0; i < ARRAY_SIZE(advanced_lookup) - 1; i++)
if (advanced_lookup[i].num == num)
return advanced_lookup[i].name;
/* No entry matches 'num', so it is the last: ADVANCED_SYSASSERT */
return advanced_lookup[i].name;
}
/*
* Note: This structure is read from the device with IO accesses,
* and the reading already does the endian conversion. As it is
* read with u32-sized accesses, any members with a different size
* need to be ordered correctly though!
*/
struct iwl_error_event_table {
u32 valid; /* (nonzero) valid, (0) log is empty */
u32 error_id; /* type of error */
u32 pc; /* program counter */
u32 blink1; /* branch link */
u32 blink2; /* branch link */
u32 ilink1; /* interrupt link */
u32 ilink2; /* interrupt link */
u32 data1; /* error-specific data */
u32 data2; /* error-specific data */
u32 data3; /* error-specific data */
u32 bcon_time; /* beacon timer */
u32 tsf_low; /* network timestamp function timer */
u32 tsf_hi; /* network timestamp function timer */
u32 gp1; /* GP1 timer register */
u32 gp2; /* GP2 timer register */
u32 gp3; /* GP3 timer register */
u32 ucode_ver; /* uCode version */
u32 hw_ver; /* HW Silicon version */
u32 brd_ver; /* HW board version */
u32 log_pc; /* log program counter */
u32 frame_ptr; /* frame pointer */
u32 stack_ptr; /* stack pointer */
u32 hcmd; /* last host command header */
u32 isr0; /* isr status register LMPM_NIC_ISR0:
* rxtx_flag */
u32 isr1; /* isr status register LMPM_NIC_ISR1:
* host_flag */
u32 isr2; /* isr status register LMPM_NIC_ISR2:
* enc_flag */
u32 isr3; /* isr status register LMPM_NIC_ISR3:
* time_flag */
u32 isr4; /* isr status register LMPM_NIC_ISR4:
* wico interrupt */
u32 isr_pref; /* isr status register LMPM_NIC_PREF_STAT */
u32 wait_event; /* wait event() caller address */
u32 l2p_control; /* L2pControlField */
u32 l2p_duration; /* L2pDurationField */
u32 l2p_mhvalid; /* L2pMhValidBits */
u32 l2p_addr_match; /* L2pAddrMatchStat */
u32 lmpm_pmg_sel; /* indicate which clocks are turned on
* (LMPM_PMG_SEL) */
u32 u_timestamp; /* indicate when the date and time of the
* compilation */
u32 flow_handler; /* FH read/write pointers, RX credit */
} __packed;
#define ERROR_START_OFFSET (1 * sizeof(u32))
#define ERROR_ELEM_SIZE (7 * sizeof(u32))
void iwl_mvm_dump_nic_error_log(struct iwl_mvm *mvm)
{
struct iwl_trans *trans = mvm->trans;
struct iwl_error_event_table table;
u32 base;
base = mvm->error_event_table;
if (mvm->cur_ucode == IWL_UCODE_INIT) {
if (!base)
base = mvm->fw->init_errlog_ptr;
} else {
if (!base)
base = mvm->fw->inst_errlog_ptr;
}
if (base < 0x800000 || base >= 0x80C000) {
IWL_ERR(mvm,
"Not valid error log pointer 0x%08X for %s uCode\n",
base,
(mvm->cur_ucode == IWL_UCODE_INIT)
? "Init" : "RT");
return;
}
iwl_trans_read_mem_bytes(trans, base, &table, sizeof(table));
if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
IWL_ERR(trans, "Start IWL Error Log Dump:\n");
IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
mvm->status, table.valid);
}
IWL_ERR(mvm, "Loaded firmware version: %s\n", mvm->fw->fw_version);
trace_iwlwifi_dev_ucode_error(trans->dev, table.error_id, table.tsf_low,
table.data1, table.data2, table.data3,
table.blink1, table.blink2, table.ilink1,
table.ilink2, table.bcon_time, table.gp1,
table.gp2, table.gp3, table.ucode_ver,
table.hw_ver, table.brd_ver);
IWL_ERR(mvm, "0x%08X | %-28s\n", table.error_id,
desc_lookup(table.error_id));
IWL_ERR(mvm, "0x%08X | uPc\n", table.pc);
IWL_ERR(mvm, "0x%08X | branchlink1\n", table.blink1);
IWL_ERR(mvm, "0x%08X | branchlink2\n", table.blink2);
IWL_ERR(mvm, "0x%08X | interruptlink1\n", table.ilink1);
IWL_ERR(mvm, "0x%08X | interruptlink2\n", table.ilink2);
IWL_ERR(mvm, "0x%08X | data1\n", table.data1);
IWL_ERR(mvm, "0x%08X | data2\n", table.data2);
IWL_ERR(mvm, "0x%08X | data3\n", table.data3);
IWL_ERR(mvm, "0x%08X | beacon time\n", table.bcon_time);
IWL_ERR(mvm, "0x%08X | tsf low\n", table.tsf_low);
IWL_ERR(mvm, "0x%08X | tsf hi\n", table.tsf_hi);
IWL_ERR(mvm, "0x%08X | time gp1\n", table.gp1);
IWL_ERR(mvm, "0x%08X | time gp2\n", table.gp2);
IWL_ERR(mvm, "0x%08X | time gp3\n", table.gp3);
IWL_ERR(mvm, "0x%08X | uCode version\n", table.ucode_ver);
IWL_ERR(mvm, "0x%08X | hw version\n", table.hw_ver);
IWL_ERR(mvm, "0x%08X | board version\n", table.brd_ver);
IWL_ERR(mvm, "0x%08X | hcmd\n", table.hcmd);
IWL_ERR(mvm, "0x%08X | isr0\n", table.isr0);
IWL_ERR(mvm, "0x%08X | isr1\n", table.isr1);
IWL_ERR(mvm, "0x%08X | isr2\n", table.isr2);
IWL_ERR(mvm, "0x%08X | isr3\n", table.isr3);
IWL_ERR(mvm, "0x%08X | isr4\n", table.isr4);
IWL_ERR(mvm, "0x%08X | isr_pref\n", table.isr_pref);
IWL_ERR(mvm, "0x%08X | wait_event\n", table.wait_event);
IWL_ERR(mvm, "0x%08X | l2p_control\n", table.l2p_control);
IWL_ERR(mvm, "0x%08X | l2p_duration\n", table.l2p_duration);
IWL_ERR(mvm, "0x%08X | l2p_mhvalid\n", table.l2p_mhvalid);
IWL_ERR(mvm, "0x%08X | l2p_addr_match\n", table.l2p_addr_match);
IWL_ERR(mvm, "0x%08X | lmpm_pmg_sel\n", table.lmpm_pmg_sel);
IWL_ERR(mvm, "0x%08X | timestamp\n", table.u_timestamp);
IWL_ERR(mvm, "0x%08X | flow_handler\n", table.flow_handler);
}
/**
* iwl_mvm_send_lq_cmd() - Send link quality command
* @init: This command is sent as part of station initialization right
* after station has been added.
*
* The link quality command is sent as the last step of station creation.
* This is the special case in which init is set and we call a callback in
* this case to clear the state indicating that station creation is in
* progress.
*/
int iwl_mvm_send_lq_cmd(struct iwl_mvm *mvm, struct iwl_lq_cmd *lq,
u8 flags, bool init)
{
struct iwl_host_cmd cmd = {
.id = LQ_CMD,
.len = { sizeof(struct iwl_lq_cmd), },
.flags = flags,
.data = { lq, },
};
if (WARN_ON(lq->sta_id == IWL_MVM_STATION_COUNT))
return -EINVAL;
if (WARN_ON(init && (cmd.flags & CMD_ASYNC)))
return -EINVAL;
return iwl_mvm_send_cmd(mvm, &cmd);
}
|
ac60ac0c2859b4d501dbd845339bae836a2669a1
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/area_kpa/kpa_112/kpa_112_0_header.c
|
85011add4a0be4650bef68c63a001249c12db806
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 348
|
c
|
kpa_112_0_header.c
|
#include "kpa_112.h"
EntryList N(Entrances) = {
[kpa_112_ENTRY_0] { -150.0, 0.0, 110.0, 0.0 },
[kpa_112_ENTRY_1] { 473.0, 0.0, 112.0, 270.0 },
};
MapSettings N(settings) = {
.main = &N(EVS_Main),
.entryList = &N(Entrances),
.entryCount = ENTRY_COUNT(N(Entrances)),
.tattle = { MSG_MapTattle_kpa_112 },
};
|
d8e2bdb1eb713bdf7a5ca527d8da957788caea75
|
a5e8d99c1852ee93743e86cfb109835bbe73a49b
|
/runtimes/native/src/window.h
|
4862387833f7f0b62cd186a29ec26d76f4eef3a0
|
[
"ISC"
] |
permissive
|
aduros/wasm4
|
5cc114dff2bac17373259c2fe36540c138733e8e
|
700c2929d1fc9512cf7705ceebb130fb72a29892
|
refs/heads/main
| 2023-09-06T00:44:00.487354
| 2023-08-21T13:09:51
| 2023-08-21T13:09:51
| 393,196,822
| 952
| 190
|
ISC
| 2023-08-21T12:45:07
| 2021-08-05T23:48:23
|
TypeScript
|
UTF-8
|
C
| false
| false
| 155
|
h
|
window.h
|
#pragma once
#include <stdint.h>
void w4_windowBoot (const char* title);
void w4_windowComposite (const uint32_t* palette, const uint8_t* framebuffer);
|
2a2f04ac48d33304f6719c673fb8f5d81521ae73
|
b732361d6b3405c3e79ac0a7d8361cf5b329b015
|
/ext/phalcon/html/helper/style.zep.c
|
43d6670b4c225f9de51b67d9f2c6a968ccf075a3
|
[
"BSD-3-Clause"
] |
permissive
|
phalcon/cphalcon
|
4a5b26f47b5c2a4107541d7fd73c595c0d90ed73
|
fc183e11e8b96c43daf7d893244846206dc2aa73
|
refs/heads/master
| 2023-03-07T22:09:48.814291
| 2023-02-28T16:45:15
| 2023-02-28T16:45:15
| 2,854,337
| 8,135
| 2,343
|
BSD-3-Clause
| 2023-09-12T12:41:13
| 2011-11-26T05:52:50
|
PHP
|
UTF-8
|
C
| false
| true
| 5,424
|
c
|
style.zep.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/array.h"
#include "kernel/fcall.h"
#include "kernel/object.h"
#include "kernel/operators.h"
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalcon.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Class Style
*/
ZEPHIR_INIT_CLASS(Phalcon_Html_Helper_Style)
{
ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Html\\Helper, Style, phalcon, html_helper_style, phalcon_html_helper_abstractseries_ce, phalcon_html_helper_style_method_entry, 0);
/**
* @var bool
*/
zend_declare_property_bool(phalcon_html_helper_style_ce, SL("isStyle"), 0, ZEND_ACC_PRIVATE);
return SUCCESS;
}
/**
* Add an element to the list
*
* @param string $url
* @param array $attributes
*
* @return $this
* @throws Exception
*/
PHP_METHOD(Phalcon_Html_Helper_Style, add)
{
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval attributes, _0, _2;
zval *url_param = NULL, *attributes_param = NULL, _1, _3;
zval url;
zval *this_ptr = getThis();
ZVAL_UNDEF(&url);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_3);
ZVAL_UNDEF(&attributes);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_2);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STR(url)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY(attributes)
ZEND_PARSE_PARAMETERS_END();
#endif
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 1, &url_param, &attributes_param);
zephir_get_strval(&url, url_param);
if (!attributes_param) {
ZEPHIR_INIT_VAR(&attributes);
array_init(&attributes);
} else {
zephir_get_arrval(&attributes, attributes_param);
}
ZEPHIR_INIT_VAR(&_0);
zephir_create_array(&_0, 3, 0);
ZEPHIR_INIT_VAR(&_1);
ZVAL_STRING(&_1, "renderTag");
zephir_array_fast_append(&_0, &_1);
ZEPHIR_INIT_VAR(&_2);
zephir_create_array(&_2, 3, 0);
ZEPHIR_CALL_METHOD(&_3, this_ptr, "gettag", NULL, 0);
zephir_check_call_status();
zephir_array_fast_append(&_2, &_3);
ZEPHIR_CALL_METHOD(&_3, this_ptr, "getattributes", NULL, 0, &url, &attributes);
zephir_check_call_status();
zephir_array_fast_append(&_2, &_3);
ZEPHIR_INIT_NVAR(&_1);
ZVAL_STRING(&_1, "/");
zephir_array_fast_append(&_2, &_1);
zephir_array_fast_append(&_0, &_2);
ZEPHIR_CALL_METHOD(&_3, this_ptr, "indent", NULL, 0);
zephir_check_call_status();
zephir_array_fast_append(&_0, &_3);
zephir_update_property_array_append(this_ptr, SL("store"), &_0);
RETURN_THIS();
}
/**
* Sets if this is a style or link tag
*
* @param bool $flag
*/
PHP_METHOD(Phalcon_Html_Helper_Style, setStyle)
{
zval *flag_param = NULL, __$true, __$false;
zend_bool flag;
zval *this_ptr = getThis();
ZVAL_BOOL(&__$true, 1);
ZVAL_BOOL(&__$false, 0);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_BOOL(flag)
ZEND_PARSE_PARAMETERS_END();
#endif
zephir_fetch_params_without_memory_grow(1, 0, &flag_param);
flag = zephir_get_boolval(flag_param);
if (flag) {
zephir_update_property_zval(this_ptr, ZEND_STRL("isStyle"), &__$true);
} else {
zephir_update_property_zval(this_ptr, ZEND_STRL("isStyle"), &__$false);
}
RETURN_THISW();
}
/**
* Returns the necessary attributes
*
* @param string $url
* @param array $attributes
*
* @return array
*/
PHP_METHOD(Phalcon_Html_Helper_Style, getAttributes)
{
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zval attributes, required;
zval *url_param = NULL, *attributes_param = NULL, _0;
zval url;
zval *this_ptr = getThis();
ZVAL_UNDEF(&url);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&attributes);
ZVAL_UNDEF(&required);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(url)
Z_PARAM_ARRAY(attributes)
ZEND_PARSE_PARAMETERS_END();
#endif
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &url_param, &attributes_param);
zephir_get_strval(&url, url_param);
zephir_get_arrval(&attributes, attributes_param);
ZEPHIR_INIT_VAR(&required);
zephir_create_array(&required, 4, 0);
add_assoc_stringl_ex(&required, SL("rel"), SL("stylesheet"));
zephir_array_update_string(&required, SL("href"), &url, PH_COPY | PH_SEPARATE);
add_assoc_stringl_ex(&required, SL("type"), SL("text/css"));
add_assoc_stringl_ex(&required, SL("media"), SL("screen"));
zephir_read_property(&_0, this_ptr, ZEND_STRL("isStyle"), PH_NOISY_CC | PH_READONLY);
if (ZEPHIR_IS_TRUE_IDENTICAL(&_0)) {
zephir_array_unset_string(&required, SL("rel"), PH_SEPARATE);
}
zephir_array_unset_string(&attributes, SL("href"), PH_SEPARATE);
zephir_fast_array_merge(return_value, &required, &attributes);
RETURN_MM();
}
/**
* @return string
*/
PHP_METHOD(Phalcon_Html_Helper_Style, getTag)
{
zval _0, _1;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZEPHIR_MM_GROW();
ZEPHIR_INIT_VAR(&_0);
zephir_read_property(&_1, this_ptr, ZEND_STRL("isStyle"), PH_NOISY_CC | PH_READONLY);
if (ZEPHIR_IS_TRUE_IDENTICAL(&_1)) {
ZVAL_STRING(&_0, "style");
} else {
ZVAL_STRING(&_0, "link");
}
RETURN_CCTOR(&_0);
}
|
63e7f224f32e3c68f58e0f3e15113671997885cb
|
675d31c0346323f7e2b0ac2438d4b7cb352d414a
|
/kernel/tkernel/sysmgr.h
|
7c6b34f872a3549b1e2f417eb7eb3a3ab6d820c3
|
[] |
no_license
|
tron-forum/mtkernel_3
|
04688868b7c20605407ee65e1204c177abd4fb39
|
308092c361b6f91621874083fad637ebcac7466a
|
refs/heads/master
| 2023-04-07T13:01:44.475830
| 2022-10-17T08:40:05
| 2022-10-17T08:40:05
| 227,035,186
| 145
| 30
| null | 2023-03-14T05:28:39
| 2019-12-10T05:20:05
|
C
|
UTF-8
|
C
| false
| false
| 3,970
|
h
|
sysmgr.h
|
/*
*----------------------------------------------------------------------
* micro T-Kernel 3.00.00
*
* Copyright (C) 2006-2019 by Ken Sakamura.
* This software is distributed under the T-License 2.1.
*----------------------------------------------------------------------
*
* Released by TRON Forum(http://www.tron.org) at 2019/12/11.
*
*----------------------------------------------------------------------
*/
/*
* sysmgr.h
* micro T-Kernel/SM(System Maneger) Definition
*/
#ifndef _SYSMGR_
#define _SYSMGR_
#include <tk/tkernel.h>
#include <sys/queue.h>
#include "kernel.h"
/* ------------------------------------------------------------------------ */
/*
* Device management function
*/
/*
* Lock for device management exclusive control
*/
IMPORT FastMLock knl_DevMgrLock;
#define LockDM() MLock(&knl_DevMgrLock, 0)
#define UnlockDM() MUnlock(&knl_DevMgrLock, 0)
/*
* Lock for device registration exclusive control
*/
#define LockREG() MLock(&knl_DevMgrLock, 1)
#define UnlockREG() MUnlock(&knl_DevMgrLock, 1)
/*
* Device registration information
*/
typedef struct DeviceControlBlock {
QUEUE q;
UB devnm[L_DEVNM+1]; /* Device name */
T_DDEV ddev; /* Registration information */
QUEUE openq; /* Open device management queue */
} DevCB;
IMPORT DevCB knl_DevCBtbl[]; /* Device registration information
table */
IMPORT QUEUE knl_UsedDevCB; /* In-use queue */
#define DID(devcb) ( ((devcb) - knl_DevCBtbl + 1) << 8 )
#define DEVID(devcb, unitno) ( DID(devcb) + (unitno) )
#define DEVCB(devid) ( knl_DevCBtbl + (((devid) >> 8) - 1) )
#define UNITNO(devid) ( (devid) & 0xff )
/*
* Open management information
*/
typedef struct OpenControlBlock {
QUEUE q;
QUEUE resq; /* For connection from resource
management */
ID resid; /* Section resource ID */
DevCB *devcb; /* Target device */
INT unitno; /* Subunit number
(0: Physical device) */
UINT omode; /* Open mode */
QUEUE requestq; /* Request management queue */
UH waitone; /* Number of individual request
waits */
T_DEVREQ *waireqlst; /* List of multiple request waits */
INT nwaireq; /* Number of multiple request waits */
ID abort_tskid; /* Abort completion wait task */
INT abort_cnt; /* Number of abort completion wait
requests */
ID abort_semid; /* Semaphore for abort completion wait */
} OpnCB;
#define RESQ_OPNCB(rq) ( (OpnCB*)((B*)(rq) - offsetof(OpnCB, resq)) )
/*
* Request management information
*/
typedef struct RequestControlBlock {
QUEUE q;
OpnCB *opncb; /* Open device */
ID tskid; /* Processing task */
T_DEVREQ req; /* Request packet */
} ReqCB;
/*
* Resource management information
*/
typedef struct ResourceControlBlock {
QUEUE openq; /* Open device management queue */
INT dissus; /* Suspend disable request count */
} ResCB;
/*
* Request function types
*/
typedef ER (*OPNFN)( ID devid, UINT omode, void *exinf );
typedef ER (*ABTFN)( ID tskid, T_DEVREQ *devreq, INT nreq, void *exinf );
typedef INT (*WAIFN)( T_DEVREQ *devreq, INT nreq, TMO tmout, void *exinf );
typedef INT (*EVTFN)( INT evttyp, void *evtinf, void *exinf );
typedef ER (*CLSFN)( ID devid, UINT option, void *exinf );
typedef ER (*EXCFN)( T_DEVREQ *devreq, TMO tmout, void *exinf );
/* ------------------------------------------------------------------------ */
#define IMPORT_DEFINE 1
#if IMPORT_DEFINE
/* device.c */
IMPORT FastMLock knl_DevMgrLock;
IMPORT DevCB knl_DevCBtbl[];
IMPORT QUEUE knl_UsedDevCB;
IMPORT DevCB* knl_searchDevCB( CONST UB *devnm );
IMPORT INT knl_phydevnm( UB *pdevnm, CONST UB *ldevnm );
IMPORT ER knl_initialize_devmgr( void );
IMPORT ER knl_finish_devmgr( void );
/* deviceio.c */
IMPORT ER knl_check_devdesc( ID dd, UINT mode, OpnCB **p_opncb );
IMPORT void knl_devmgr_startup( void );
IMPORT void knl_devmgr_cleanup( void );
IMPORT ER knl_initDevIO( void );
IMPORT ER knl_finishDevIO( void );
#endif
#endif /* _SYSMGR_ */
|
f8009462952bcf8af25f349e9cc5297ea75c0bf4
|
321d11eaee885ceb3a74db0a062f9bbdf282148c
|
/crypto/rsa/rsa_gen.c
|
4acaa515f77423ceb53c1dacbb8c8af039295873
|
[
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
openssl/openssl
|
75691ebaae957793f2ff0673f77545277dfb3988
|
5318c012885a5382eadbf95aa9c1d35664bca819
|
refs/heads/master
| 2023-09-03T15:22:52.727123
| 2023-09-01T07:10:49
| 2023-09-02T14:30:01
| 7,634,677
| 24,148
| 11,569
|
Apache-2.0
| 2023-09-14T19:48:11
| 2013-01-15T22:34:48
|
C
|
UTF-8
|
C
| false
| false
| 17,017
|
c
|
rsa_gen.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* NB: these functions have been "upgraded", the deprecated versions (which
* are compatibility wrappers using these functions) are in rsa_depr.c. -
* Geoff
*/
/*
* RSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/self_test.h>
#include "prov/providercommon.h"
#include "rsa_local.h"
static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg);
static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
BIGNUM *e_value, BN_GENCB *cb, int pairwise_test);
/*
* NB: this wrapper would normally be placed in rsa_lib.c and the static
* implementation would probably be in rsa_eay.c. Nonetheless, is kept here
* so that we don't introduce a new linker dependency. Eg. any application
* that wasn't previously linking object code related to key-generation won't
* have to now just because key-generation is part of RSA_METHOD.
*/
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
{
if (rsa->meth->rsa_keygen != NULL)
return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
e_value, cb);
}
int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
BIGNUM *e_value, BN_GENCB *cb)
{
#ifndef FIPS_MODULE
/* multi-prime is only supported with the builtin key generation */
if (rsa->meth->rsa_multi_prime_keygen != NULL) {
return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
e_value, cb);
} else if (rsa->meth->rsa_keygen != NULL) {
/*
* However, if rsa->meth implements only rsa_keygen, then we
* have to honour it in 2-prime case and assume that it wouldn't
* know what to do with multi-prime key generated by builtin
* subroutine...
*/
if (primes == 2)
return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
else
return 0;
}
#endif /* FIPS_MODULE */
return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0);
}
#ifndef FIPS_MODULE
static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
BIGNUM *e_value, BN_GENCB *cb)
{
BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
RSA_PRIME_INFO *pinfo = NULL;
STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
BN_CTX *ctx = NULL;
BN_ULONG bitst = 0;
unsigned long error = 0;
int ok = -1;
if (bits < RSA_MIN_MODULUS_BITS) {
ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
return 0;
}
if (e_value == NULL) {
ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
return 0;
}
/* A bad value for e can cause infinite loops */
if (!ossl_rsa_check_public_exponent(e_value)) {
ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
return 0;
}
if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
return 0;
}
ctx = BN_CTX_new_ex(rsa->libctx);
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
if (r2 == NULL)
goto err;
/* divide bits into 'primes' pieces evenly */
quo = bits / primes;
rmd = bits % primes;
for (i = 0; i < primes; i++)
bitsr[i] = (i < rmd) ? quo + 1 : quo;
rsa->dirty_cnt++;
/* We need the RSA components non-NULL */
if (!rsa->n && ((rsa->n = BN_new()) == NULL))
goto err;
if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
if (!rsa->e && ((rsa->e = BN_new()) == NULL))
goto err;
if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
goto err;
BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
/* initialize multi-prime components */
if (primes > RSA_DEFAULT_PRIME_NUM) {
rsa->version = RSA_ASN1_VERSION_MULTI;
prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
if (prime_infos == NULL)
goto err;
if (rsa->prime_infos != NULL) {
/* could this happen? */
sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
ossl_rsa_multip_info_free);
}
rsa->prime_infos = prime_infos;
/* prime_info from 2 to |primes| -1 */
for (i = 2; i < primes; i++) {
pinfo = ossl_rsa_multip_info_new();
if (pinfo == NULL)
goto err;
(void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
}
}
if (BN_copy(rsa->e, e_value) == NULL)
goto err;
/* generate p, q and other primes (if any) */
for (i = 0; i < primes; i++) {
adj = 0;
retries = 0;
if (i == 0) {
prime = rsa->p;
} else if (i == 1) {
prime = rsa->q;
} else {
pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
prime = pinfo->r;
}
BN_set_flags(prime, BN_FLG_CONSTTIME);
for (;;) {
redo:
if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
cb, ctx))
goto err;
/*
* prime should not be equal to p, q, r_3...
* (those primes prior to this one)
*/
{
int j;
for (j = 0; j < i; j++) {
BIGNUM *prev_prime;
if (j == 0)
prev_prime = rsa->p;
else if (j == 1)
prev_prime = rsa->q;
else
prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
j - 2)->r;
if (!BN_cmp(prime, prev_prime)) {
goto redo;
}
}
}
if (!BN_sub(r2, prime, BN_value_one()))
goto err;
ERR_set_mark();
BN_set_flags(r2, BN_FLG_CONSTTIME);
if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
/* GCD == 1 since inverse exists */
break;
}
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) == ERR_LIB_BN
&& ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
/* GCD != 1 */
ERR_pop_to_mark();
} else {
goto err;
}
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
bitse += bitsr[i];
/* calculate n immediately to see if it's sufficient */
if (i == 1) {
/* we get at least 2 primes */
if (!BN_mul(r1, rsa->p, rsa->q, ctx))
goto err;
} else if (i != 0) {
/* modulus n = p * q * r_3 * r_4 ... */
if (!BN_mul(r1, rsa->n, prime, ctx))
goto err;
} else {
/* i == 0, do nothing */
if (!BN_GENCB_call(cb, 3, i))
goto err;
continue;
}
/*
* if |r1|, product of factors so far, is not as long as expected
* (by checking the first 4 bits are less than 0x9 or greater than
* 0xF). If so, re-generate the last prime.
*
* NOTE: This actually can't happen in two-prime case, because of
* the way factors are generated.
*
* Besides, another consideration is, for multi-prime case, even the
* length modulus is as long as expected, the modulus could start at
* 0x8, which could be utilized to distinguish a multi-prime private
* key by using the modulus in a certificate. This is also covered
* by checking the length should not be less than 0x9.
*/
if (!BN_rshift(r2, r1, bitse - 4))
goto err;
bitst = BN_get_word(r2);
if (bitst < 0x9 || bitst > 0xF) {
/*
* For keys with more than 4 primes, we attempt longer factor to
* meet length requirement.
*
* Otherwise, we just re-generate the prime with the same length.
*
* This strategy has the following goals:
*
* 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
* 2. stay the same logic with normal 2-prime key
*/
bitse -= bitsr[i];
if (!BN_GENCB_call(cb, 2, n++))
goto err;
if (primes > 4) {
if (bitst < 0x9)
adj++;
else
adj--;
} else if (retries == 4) {
/*
* re-generate all primes from scratch, mainly used
* in 4 prime case to avoid long loop. Max retry times
* is set to 4.
*/
i = -1;
bitse = 0;
continue;
}
retries++;
goto redo;
}
/* save product of primes for further use, for multi-prime only */
if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
goto err;
if (BN_copy(rsa->n, r1) == NULL)
goto err;
if (!BN_GENCB_call(cb, 3, i))
goto err;
}
if (BN_cmp(rsa->p, rsa->q) < 0) {
tmp = rsa->p;
rsa->p = rsa->q;
rsa->q = tmp;
}
/* calculate d */
/* p - 1 */
if (!BN_sub(r1, rsa->p, BN_value_one()))
goto err;
/* q - 1 */
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err;
/* (p - 1)(q - 1) */
if (!BN_mul(r0, r1, r2, ctx))
goto err;
/* multi-prime */
for (i = 2; i < primes; i++) {
pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
/* save r_i - 1 to pinfo->d temporarily */
if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
goto err;
if (!BN_mul(r0, r0, pinfo->d, ctx))
goto err;
}
{
BIGNUM *pr0 = BN_new();
if (pr0 == NULL)
goto err;
BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
BN_free(pr0);
goto err; /* d */
}
/* We MUST free pr0 before any further use of r0 */
BN_free(pr0);
}
{
BIGNUM *d = BN_new();
if (d == NULL)
goto err;
BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
/* calculate d mod (p-1) and d mod (q - 1) */
if (!BN_mod(rsa->dmp1, d, r1, ctx)
|| !BN_mod(rsa->dmq1, d, r2, ctx)) {
BN_free(d);
goto err;
}
/* calculate CRT exponents */
for (i = 2; i < primes; i++) {
pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
/* pinfo->d == r_i - 1 */
if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
BN_free(d);
goto err;
}
}
/* We MUST free d before any further use of rsa->d */
BN_free(d);
}
{
BIGNUM *p = BN_new();
if (p == NULL)
goto err;
BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
/* calculate inverse of q mod p */
if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
BN_free(p);
goto err;
}
/* calculate CRT coefficient for other primes */
for (i = 2; i < primes; i++) {
pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
BN_free(p);
goto err;
}
}
/* We MUST free p before any further use of rsa->p */
BN_free(p);
}
ok = 1;
err:
if (ok == -1) {
ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
ok = 0;
}
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ok;
}
#endif /* FIPS_MODULE */
static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
{
int ok = 0;
#ifdef FIPS_MODULE
ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
#else
/*
* Only multi-prime keys or insecure keys with a small key length or a
* public exponent <= 2^16 will use the older rsa_multiprime_keygen().
*/
if (primes == 2
&& bits >= 2048
&& (e_value == NULL || BN_num_bits(e_value) > 16))
ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
else
ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
#endif /* FIPS_MODULE */
if (pairwise_test && ok > 0) {
OSSL_CALLBACK *stcb = NULL;
void *stcbarg = NULL;
OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
if (!ok) {
ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
/* Clear intermediate results */
BN_clear_free(rsa->d);
BN_clear_free(rsa->p);
BN_clear_free(rsa->q);
BN_clear_free(rsa->dmp1);
BN_clear_free(rsa->dmq1);
BN_clear_free(rsa->iqmp);
rsa->d = NULL;
rsa->p = NULL;
rsa->q = NULL;
rsa->dmp1 = NULL;
rsa->dmq1 = NULL;
rsa->iqmp = NULL;
}
}
return ok;
}
/*
* For RSA key generation it is not known whether the key pair will be used
* for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
* either a signature verification OR an encryption operation may be used to
* perform the pairwise consistency check. The simpler encrypt/decrypt operation
* has been chosen for this case.
*/
static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
{
int ret = 0;
unsigned int ciphertxt_len;
unsigned char *ciphertxt = NULL;
const unsigned char plaintxt[16] = {0};
unsigned char *decoded = NULL;
unsigned int decoded_len;
unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
int padding = RSA_PKCS1_PADDING;
OSSL_SELF_TEST *st = NULL;
st = OSSL_SELF_TEST_new(cb, cbarg);
if (st == NULL)
goto err;
OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
ciphertxt_len = RSA_size(rsa);
/*
* RSA_private_encrypt() and RSA_private_decrypt() requires the 'to'
* parameter to be a maximum of RSA_size() - allocate space for both.
*/
ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
if (ciphertxt == NULL)
goto err;
decoded = ciphertxt + ciphertxt_len;
ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
padding);
if (ciphertxt_len <= 0)
goto err;
if (ciphertxt_len == plaintxt_len
&& memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
goto err;
OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
padding);
if (decoded_len != plaintxt_len
|| memcmp(decoded, plaintxt, decoded_len) != 0)
goto err;
ret = 1;
err:
OSSL_SELF_TEST_onend(st, ret);
OSSL_SELF_TEST_free(st);
OPENSSL_free(ciphertxt);
return ret;
}
|
2b82ca9f2bb63d47c48f1ae0bcad583b1d44ff2f
|
25146d3cc79fd1fbb6578d2c64249fdbd6bfac65
|
/embedded/tls-sock-server.c
|
505a1fcc3729c24ebe9af60c74d64b5dc7ded4f3
|
[] |
no_license
|
wolfSSL/wolfssl-examples
|
5bb55c47be03bf55dfa1552f6b391557b6b31d90
|
7d373b14fe9a4283f9d70818fafab8b5ff863de1
|
refs/heads/master
| 2023-08-17T07:09:39.061991
| 2023-08-15T15:13:27
| 2023-08-15T15:13:27
| 21,290,295
| 237
| 191
| null | 2023-09-12T22:57:33
| 2014-06-27T21:50:12
|
C
|
UTF-8
|
C
| false
| false
| 7,330
|
c
|
tls-sock-server.c
|
/* tls-sock-server.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL. (formerly known as CyaSSL)
*
* wolfSSL 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.
*
* wolfSSL 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 WOLFSSL_USER_SETTINGS
#include <wolfssl/options.h>
#endif
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/ssl.h>
#include "sockets.h"
#include "tls-info.h"
#include "certs.h"
#if !defined(NO_WOLFSSL_SERVER)
/* Application data to send. */
static const char msgHTTPIndex[] =
"HTTP/1.1 200 OK\n"
"Content-Type: text/html\n"
"Connection: close\n"
"\n"
"<html>\n"
"<head>\n"
"<title>Welcome to wolfSSL!</title>\n"
"</head>\n"
"<body>\n"
"<p>wolfSSL has successfully performed handshake!</p>\n"
"</body>\n"
"</html>\n";
/* Create a new wolfSSL CTX server with a certificate for authentication. */
static int wolfssl_server_ctx_new(WOLFSSL_CTX** ctx)
{
int ret = 0;
WOLFSSL_CTX* server_ctx = NULL;
/* Create and initialize WOLFSSL_CTX */
if ((server_ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) {
printf("ERROR: failed to create WOLFSSL_CTX\n");
ret = -1;
}
if (ret == 0) {
/* Load client certificates into WOLFSSL_CTX */
if (wolfSSL_CTX_use_certificate_buffer(server_ctx, SERVER_CERT,
SERVER_CERT_LEN, WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
printf("ERROR: failed to load server certificate\n");
ret = -1;
}
}
if (ret == 0) {
/* Load client certificates into WOLFSSL_CTX */
if (wolfSSL_CTX_use_PrivateKey_buffer(server_ctx, SERVER_KEY,
SERVER_KEY_LEN, WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
printf("ERROR: failed to load server key\n");
ret = -1;
}
}
if (ret == 0) {
/* Return newly created wolfSSL context */
*ctx = server_ctx;
}
else {
if (server_ctx != NULL)
wolfSSL_CTX_free(server_ctx);
}
return ret;
}
/* Create a new wolfSSL server with a certificate for authentication. */
static int wolfssl_server_ssl_new(WOLFSSL_CTX* ctx, WOLFSSL** ssl)
{
int ret = 0;
WOLFSSL* server_ssl = NULL;
if (ret == 0) {
/* Create a WOLFSSL object */
if ((server_ssl = wolfSSL_new(ctx)) == NULL) {
printf("ERROR: failed to create WOLFSSL object\n");
ret = -1;
}
}
if (ret == 0) {
/* Return newly created wolfSSL context and object */
*ssl = server_ssl;
}
else {
if (server_ssl != NULL)
wolfSSL_free(server_ssl);
}
return ret;
}
/* Server accepting a client using TLS */
static int wolfssl_server_accept(WOLFSSL* ssl)
{
int ret = 0;
if (wolfSSL_accept(ssl) != WOLFSSL_SUCCESS) {
ret = wolfSSL_get_error(ssl, 0);
if (ret == WOLFSSL_ERROR_WANT_READ)
ret = 0;
else if (ret > 0)
ret = -1;
}
return ret;
}
/* Send application data. */
static int wolfssl_send(WOLFSSL* ssl, const char* msg)
{
int ret = 0;
int len;
printf("Sending:\n%s\n", msg);
len = wolfSSL_write(ssl, msg, XSTRLEN(msg));
if (len < 0)
ret = len;
else if (len != XSTRLEN(msg))
ret = -1;
return ret;
}
/* Receive application data. */
static int wolfssl_recv(WOLFSSL* ssl)
{
int ret;
int err = 0;
byte reply[80];
int total = 0;
printf("Receive:\n");
do {
ret = wolfSSL_read(ssl, reply, sizeof(reply)-1);
if (ret > 0) {
reply[ret] = '\0';
printf("%s", reply);
total += ret;
err = 0;
}
else if (ret == -1)
err = wolfSSL_get_error(ssl, 0);
}
while (err == 0 || (total == 0 && err == WOLFSSL_ERROR_WANT_READ));
if (total > 0 && err == WOLFSSL_ERROR_WANT_READ)
ret = 0;
return ret;
}
/* Establish a socket to listen on. */
static int wolfssl_server_listen_tcp(SOCKET_T* fd)
{
word16 port = wolfSSLPort;
return tcp_listen(fd, &port, 1, 0, 0);
}
/* Accept the TCP connection from the client. */
static int wolfssl_server_accept_tcp(WOLFSSL* ssl, SOCKET_T fd,
SOCKET_T* acceptfd)
{
int ret = 0;
SOCKET_T clientfd = WOLFSSL_SOCKET_INVALID;
ret = tcp_accept(&fd, &clientfd);
if (ret == 0) {
*acceptfd = clientfd;
ret = tcp_set_nonblocking(&clientfd);
}
if (ret == 0) {
if (wolfSSL_set_fd(ssl, clientfd) != WOLFSSL_SUCCESS)
ret = -1;
}
return ret;
}
/* Server operations. */
static int server(WOLFSSL_CTX* server_ctx, SOCKET_T sockfd)
{
int ret;
WOLFSSL* server_ssl = NULL;
SOCKET_T clientfd = WOLFSSL_SOCKET_INVALID;
do {
ret = wolfssl_server_ssl_new(server_ctx, &server_ssl);
if (ret == 0)
ret = wolfssl_server_accept_tcp(server_ssl, sockfd, &clientfd);
while (ret == 0) {
ret = wolfssl_server_accept(server_ssl);
if (ret == 0 && wolfSSL_is_init_finished(server_ssl))
break;
}
if (ret == 0)
showPeerEx(server_ssl, 0);
/* Receive HTTP request */
if (ret == 0)
ret = wolfssl_recv(server_ssl);
/* Send HTTP response */
if (ret == 0)
ret = wolfssl_send(server_ssl, msgHTTPIndex);
if (server_ssl != NULL)
wolfSSL_free(server_ssl);
if (clientfd != WOLFSSL_SOCKET_INVALID)
CloseSocket(clientfd);
}
while (ret == 0);
return ret;
}
/* Main entry point. */
int main(int argc, char* argv[])
{
int ret = 0;
WOLFSSL_CTX* server_ctx = NULL;
SOCKET_T sockfd = WOLFSSL_SOCKET_INVALID;
#if defined(DEBUG_WOLFSSL)
wolfSSL_Debugging_ON();
#endif
/* Initialise wolfSSL library */
wolfSSL_Init();
ret = wolfssl_server_ctx_new(&server_ctx);
if (ret == 0)
ret = wolfssl_server_listen_tcp(&sockfd);
/* Do server */
ret = server(server_ctx, sockfd);
if (server_ctx != NULL)
wolfSSL_CTX_free(server_ctx);
if (sockfd != WOLFSSL_SOCKET_INVALID)
CloseSocket(sockfd);
/* Cleanup wolfSSL library */
wolfSSL_Cleanup();
if (ret == 0)
printf("Done\n");
else {
char buffer[80];
printf("Error: %d, %s\n", ret, wolfSSL_ERR_error_string(ret, buffer));
}
return (ret == 0) ? 0 : 1;
}
#else
int main(int argc, char* argv[])
{
(void)argc;
(void)argv;
printf("Must build wolfSSL with server enabled for this example\n");
return 0;
}
#endif
|
0760415af014bf97cb03e08bc91340c8547e04de
|
5efe877bf5ebc9da1e7edb8efabb66b88a78cee4
|
/DcpmPkg/driver/Core/Diagnostics/ConfigDiagnostic.h
|
2cee28c394b996138cb855a8a089a2225973eda8
|
[
"BSD-3-Clause"
] |
permissive
|
intel/ipmctl
|
342996a882ea7f4d3abf06fd175ec5d5673829b3
|
c75bd840ea7820c8f93a5488fcff75d08beedd51
|
refs/heads/master
| 2023-08-11T03:49:16.000607
| 2023-05-05T02:26:49
| 2023-05-05T02:26:49
| 133,425,750
| 176
| 64
|
BSD-3-Clause
| 2023-03-20T23:15:23
| 2018-05-14T21:53:46
|
C
|
UTF-8
|
C
| false
| false
| 1,077
|
h
|
ConfigDiagnostic.h
|
/*
* Copyright (c) 2018, Intel Corporation.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef CONFIG_DIAGNOSTICS_H_
#define CONFIG_DIAGNOSTICS_H_
#include "CoreDiagnostics.h"
typedef struct _BROKEN_IS
{
UINT16 InterleaveSetIndex;
DIMM_UNIQUE_IDENTIFIER MissingDimmIdentifier[MAX_DIMMS];
DIMM_LOCATION CurrentDimmLocations[MAX_DIMMS];
DIMM_LOCATION MisplacedDimmLocations[MAX_DIMMS];
UINT16 MissingDimmCount;
} BROKEN_IS;
/**
Run platform configuration diagnostics for the list of DIMMs, and
appropriately populate the result messages, and test-state.
@param[in] ppDimms The DIMM pointers list
@param[in] DimmCount DIMMs count
@param[in] DimmIdPreference Preference for Dimm ID display (UID/Handle)
@param[out] pResult Pointer of structure with diagnostics test result
@retval EFI_SUCCESS Test executed correctly
@retval EFI_INVALID_PARAMETER if any of the parameters is a NULL.
**/
EFI_STATUS
RunConfigDiagnostics(
IN DIMM **ppDimms,
IN CONST UINT16 DimmCount,
IN UINT8 DimmIdPreference,
OUT DIAG_INFO *pResult
);
#endif
|
2e8f488d011adfc486944a02af515a046071585b
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/cmd/test.c
|
b782df7612129092a183b73d2cc624395c4e399d
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 5,813
|
c
|
test.c
|
/*
* POSIX standard
* test expression
* [ expression ]
*
* Plan 9 additions:
* -A file exists and is append-only
* -L file exists and is exclusive-use
* -T file exists and is temporary
*/
#include <u.h>
#include <libc.h>
#define isatty plan9_isatty
#define EQ(a,b) ((tmp=a)==0?0:(strcmp(tmp,b)==0))
int ap;
int ac;
char **av;
char *tmp;
void synbad(char *, char *);
int fsizep(char *);
int isdir(char *);
int isreg(char *);
int isatty(int);
int isint(char *, int *);
int isolder(char *, char *);
int isolderthan(char *, char *);
int isnewerthan(char *, char *);
int hasmode(char *, ulong);
int tio(char *, int);
int e(void), e1(void), e2(void), e3(void);
char *nxtarg(int);
void
main(int argc, char *argv[])
{
int r;
char *c;
ac = argc; av = argv; ap = 1;
if(EQ(argv[0],"[")) {
if(!EQ(argv[--ac],"]"))
synbad("] missing","");
}
argv[ac] = 0;
if (ac<=1)
exits("usage");
r = e();
/*
* nice idea but short-circuit -o and -a operators may have
* not consumed their right-hand sides.
*/
if(0 && (c = nxtarg(1)) != nil)
synbad("unexpected operator/operand: ", c);
exits(r?0:"false");
}
char *
nxtarg(int mt)
{
if(ap>=ac){
if(mt){
ap++;
return(0);
}
synbad("argument expected","");
}
return(av[ap++]);
}
int
nxtintarg(int *pans)
{
if(ap<ac && isint(av[ap], pans)){
ap++;
return 1;
}
return 0;
}
int
e(void)
{
int p1;
p1 = e1();
if (EQ(nxtarg(1), "-o"))
return(p1 || e());
ap--;
return(p1);
}
int
e1(void)
{
int p1;
p1 = e2();
if (EQ(nxtarg(1), "-a"))
return (p1 && e1());
ap--;
return(p1);
}
int
e2(void)
{
if (EQ(nxtarg(0), "!"))
return(!e2());
ap--;
return(e3());
}
int
e3(void)
{
int p1, int1, int2;
char *a, *p2;
a = nxtarg(0);
if(EQ(a, "(")) {
p1 = e();
if(!EQ(nxtarg(0), ")"))
synbad(") expected","");
return(p1);
}
if(EQ(a, "-A"))
return(hasmode(nxtarg(0), DMAPPEND));
if(EQ(a, "-L"))
return(hasmode(nxtarg(0), DMEXCL));
if(EQ(a, "-T"))
return(hasmode(nxtarg(0), DMTMP));
if(EQ(a, "-f"))
return(isreg(nxtarg(0)));
if(EQ(a, "-d"))
return(isdir(nxtarg(0)));
if(EQ(a, "-r"))
return(tio(nxtarg(0), 4));
if(EQ(a, "-w"))
return(tio(nxtarg(0), 2));
if(EQ(a, "-x"))
return(tio(nxtarg(0), 1));
if(EQ(a, "-e"))
return(tio(nxtarg(0), 0));
if(EQ(a, "-c"))
return(0);
if(EQ(a, "-b"))
return(0);
if(EQ(a, "-u"))
return(0);
if(EQ(a, "-g"))
return(0);
if(EQ(a, "-s"))
return(fsizep(nxtarg(0)));
if(EQ(a, "-t"))
if(ap>=ac)
return(isatty(1));
else if(nxtintarg(&int1))
return(isatty(int1));
else
synbad("not a valid file descriptor number ", "");
if(EQ(a, "-n"))
return(!EQ(nxtarg(0), ""));
if(EQ(a, "-z"))
return(EQ(nxtarg(0), ""));
p2 = nxtarg(1);
if (p2==0)
return(!EQ(a,""));
if(EQ(p2, "="))
return(EQ(nxtarg(0), a));
if(EQ(p2, "!="))
return(!EQ(nxtarg(0), a));
if(EQ(p2, "-older"))
return(isolder(nxtarg(0), a));
if(EQ(p2, "-ot"))
return(isolderthan(nxtarg(0), a));
if(EQ(p2, "-nt"))
return(isnewerthan(nxtarg(0), a));
if(!isint(a, &int1))
synbad("unexpected operator/operand: ", p2);
if(nxtintarg(&int2)){
if(EQ(p2, "-eq"))
return(int1==int2);
if(EQ(p2, "-ne"))
return(int1!=int2);
if(EQ(p2, "-gt"))
return(int1>int2);
if(EQ(p2, "-lt"))
return(int1<int2);
if(EQ(p2, "-ge"))
return(int1>=int2);
if(EQ(p2, "-le"))
return(int1<=int2);
}
synbad("unknown operator ",p2);
return 0; /* to shut ken up */
}
int
tio(char *a, int f)
{
return access (a, f) >= 0;
}
/*
* note that the name strings pointed to by Dir members are
* allocated with the Dir itself (by the same call to malloc),
* but are not included in sizeof(Dir), so copying a Dir won't
* copy the strings it points to.
*/
int
hasmode(char *f, ulong m)
{
int r;
Dir *dir;
dir = dirstat(f);
if (dir == nil)
return 0;
r = (dir->mode & m) != 0;
free(dir);
return r;
}
int
isdir(char *f)
{
return hasmode(f, DMDIR);
}
int
isreg(char *f)
{
int r;
Dir *dir;
dir = dirstat(f);
if (dir == nil)
return 0;
r = (dir->mode & DMDIR) == 0;
free(dir);
return r;
}
int
isatty(int fd)
{
int r;
Dir *d1, *d2;
d1 = dirfstat(fd);
d2 = dirstat("/dev/cons");
if (d1 == nil || d2 == nil)
r = 0;
else
r = d1->type == d2->type && d1->dev == d2->dev &&
d1->qid.path == d2->qid.path;
free(d1);
free(d2);
return r;
}
int
fsizep(char *f)
{
int r;
Dir *dir;
dir = dirstat(f);
if (dir == nil)
return 0;
r = dir->length > 0;
free(dir);
return r;
}
void
synbad(char *s1, char *s2)
{
int len;
write(2, "test: ", 6);
if ((len = strlen(s1)) != 0)
write(2, s1, len);
if ((len = strlen(s2)) != 0)
write(2, s2, len);
write(2, "\n", 1);
exits("bad syntax");
}
int
isint(char *s, int *pans)
{
char *ep;
*pans = strtol(s, &ep, 0);
return (*ep == 0);
}
int
isolder(char *pin, char *f)
{
int r;
ulong n, m;
char *p = pin;
Dir *dir;
dir = dirstat(f);
if (dir == nil)
return 0;
/* parse time */
n = 0;
while(*p){
m = strtoul(p, &p, 0);
switch(*p){
case 0:
n = m;
break;
case 'y':
m *= 12;
/* fall through */
case 'M':
m *= 30;
/* fall through */
case 'd':
m *= 24;
/* fall through */
case 'h':
m *= 60;
/* fall through */
case 'm':
m *= 60;
/* fall through */
case 's':
n += m;
p++;
break;
default:
synbad("bad time syntax, ", pin);
}
}
r = dir->mtime + n < time(0);
free(dir);
return r;
}
int
isolderthan(char *a, char *b)
{
int r;
Dir *ad, *bd;
ad = dirstat(a);
bd = dirstat(b);
if (ad == nil || bd == nil)
r = 0;
else
r = ad->mtime > bd->mtime;
free(ad);
free(bd);
return r;
}
int
isnewerthan(char *a, char *b)
{
int r;
Dir *ad, *bd;
ad = dirstat(a);
bd = dirstat(b);
if (ad == nil || bd == nil)
r = 0;
else
r = ad->mtime < bd->mtime;
free(ad);
free(bd);
return r;
}
|
99a4bdbf3ca0980dfd4210e5cc4d0c33b1bad287
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/src/vec/vec/impls/seq/ftn-kernels/faypx.h
|
564672f3f698b361a8d4d071e39accf4a893434e
|
[
"BSD-2-Clause"
] |
permissive
|
petsc/petsc
|
3b1a04fea71858e0292f9fd4d04ea11618c50969
|
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
|
refs/heads/main
| 2023-08-17T20:51:16.507070
| 2023-08-17T16:08:06
| 2023-08-17T16:08:06
| 8,691,401
| 341
| 169
|
NOASSERTION
| 2023-03-29T11:02:58
| 2013-03-10T20:55:21
|
C
|
UTF-8
|
C
| false
| false
| 394
|
h
|
faypx.h
|
#ifndef __FAYPX_H
#define __FAYPX_H
#include <petscsys.h>
#if defined(PETSC_USE_FORTRAN_KERNEL_AYPX)
#if defined(PETSC_HAVE_FORTRAN_CAPS)
#define fortranaypx_ FORTRANAYPX
#elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
#define fortranaypx_ fortranaypx
#endif
PETSC_EXTERN void fortranaypx_(const PetscInt *, const PetscScalar *, const PetscScalar *, PetscScalar *);
#endif
#endif
|
9b3f962da2cb7d18a0829b6d4007d9bb019423f0
|
011e552512f45ca313615e428924d001a427e8e6
|
/vm/page-nommu.c
|
af5b3af085e22834b8385b0f7e1b9d669be03a74
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
phoenix-rtos/phoenix-rtos-kernel
|
3d4c1d0e7703ea5ce50c2642d35fbb79c1f2afd6
|
e15898bac82e168f7e6aaea60d413790a282f389
|
refs/heads/master
| 2023-09-01T15:04:26.226958
| 2023-09-01T09:21:17
| 2023-09-01T09:45:00
| 125,823,596
| 115
| 39
|
BSD-3-Clause
| 2023-09-14T13:34:22
| 2018-03-19T08:14:43
|
C
|
UTF-8
|
C
| false
| false
| 3,537
|
c
|
page-nommu.c
|
/*
* Phoenix-RTOS
*
* Operating system kernel
*
* Virtual memory manager - page allocator
*
* Copyright 2012, 2016, 2017 Phoenix Systems
* Copyright 2001, 2005-2006 Pawel Pisarczyk
* Author: Pawel Pisarczyk
*
* This file is part of Phoenix-RTOS.
*
* %LICENSE%
*/
#include "../hal/hal.h"
#include "page.h"
#include "../include/errno.h"
#include "../lib/lib.h"
#include "map.h"
#include "../proc/proc.h"
#include "../syspage.h"
extern unsigned int __bss_start;
struct {
size_t allocsz;
size_t bootsz;
size_t freesz;
page_t *freeq;
size_t freeqsz;
lock_t lock;
} pages;
page_t *_page_alloc(size_t size, u8 flags)
{
page_t *lh = pages.freeq;
if (lh == NULL)
return NULL;
pages.freeq = lh->next;
lh->next = NULL;
lh->idx = hal_cpuGetLastBit(size);
if (hal_cpuGetFirstBit(size) < lh->idx)
lh->idx++;
pages.freesz -= (1 << lh->idx);
pages.allocsz += (1 << lh->idx);
return lh;
}
page_t *vm_pageAlloc(size_t size, u8 flags)
{
page_t *p;
proc_lockSet(&pages.lock);
p = _page_alloc(size, flags);
proc_lockClear(&pages.lock);
return p;
}
void _page_free(page_t *lh)
{
lh->next = pages.freeq;
pages.freeq = lh;
pages.freesz += (1 << lh->idx);
pages.allocsz -= (1 << lh->idx);
return;
}
void vm_pageFree(page_t *lh)
{
proc_lockSet(&pages.lock);
_page_free(lh);
proc_lockClear(&pages.lock);
return;
}
void _page_showPages(void)
{
return;
}
int page_map(pmap_t *pmap, void *vaddr, addr_t pa, int attr)
{
page_t *ap;
proc_lockSet(&pages.lock);
if (pmap_enter(pmap, pa, vaddr, attr, NULL) < 0) {
if ((ap = _page_alloc(SIZE_PAGE, PAGE_OWNER_KERNEL | PAGE_KERNEL_PTABLE)) == NULL) {
proc_lockClear(&pages.lock);
return -ENOMEM;
}
pmap_enter(pmap, pa, vaddr, attr, ap);
}
proc_lockClear(&pages.lock);
return EOK;
}
page_t *_page_get(addr_t addr)
{
return NULL;
}
void vm_pageFreeAt(pmap_t *pmap, void *vaddr)
{
}
int _page_sbrk(pmap_t *pmap, void **start, void **end)
{
page_t *np;
if ((np = _page_alloc(SIZE_PAGE, PAGE_OWNER_KERNEL | PAGE_KERNEL_HEAP)) == NULL)
return -ENOMEM;
if (page_map(pmap, (*end), PGHD_PRESENT | PGHD_WRITE, (addr_t)np) < 0)
return -ENOMEM;
(*end) += SIZE_PAGE;
return EOK;
}
void vm_pageGetStats(size_t *freesz)
{
*freesz = pages.freesz;
}
void vm_pageinfo(meminfo_t *info)
{
proc_lockSet(&pages.lock);
info->page.alloc = pages.allocsz;
info->page.free = pages.freesz;
info->page.boot = pages.bootsz;
info->page.sz = sizeof(page_t);
info->page.mapsz = -1;
proc_lockClear(&pages.lock);
}
void _page_init(pmap_t *pmap, void **bss, void **top)
{
page_t *p;
const syspage_map_t *map;
unsigned int i;
proc_lockInit(&pages.lock, "page.nommu");
/* TODO: handle error */
if ((map = syspage_mapAddrResolve((addr_t)&__bss_start)) == NULL)
return;
pages.freesz = map->end - (unsigned int)(*bss);
pages.bootsz = 0;
pages.freeq = (*bss);
pages.freeqsz = pages.freesz / SIZE_PAGE;
(*bss) += pages.freeqsz * sizeof(page_t);
(*top) = max((*top), (*bss));
/* Prepare memory hash */
pages.allocsz = (unsigned int)(*bss) - (unsigned int)&__bss_start;
pages.freesz -= pages.freeqsz * sizeof(page_t);
/* Show statistics one the console */
lib_printf("vm: Initializing page allocator %d/%d KB, page_t=%d\n", (pages.allocsz - pages.bootsz) / 1024,
(pages.freesz + pages.allocsz ) / 1024, sizeof(page_t));
/* Prepare allocation queue */
for (p = pages.freeq, i = 0; i < pages.freeqsz; i++) {
p->next = p + 1;
p = p->next;
}
(pages.freeq + pages.freeqsz - 1)->next = NULL;
return;
}
|
d576b319260848bfde9b337806b186a238f1fee2
|
1126985fc98d13356a45ed3fd7717afcb490db3f
|
/lib/xnvme_be_ramdisk_admin.c
|
cfe323101211e51ecbc88e04124dc49aaeae07ae
|
[
"BSD-3-Clause"
] |
permissive
|
OpenMPDK/xNVMe
|
feac321adc84e91f3e05c020146757737fe94874
|
5198563801b14d21d801a7224af63b9e85d798a3
|
refs/heads/main
| 2023-08-21T20:18:09.969516
| 2023-06-16T07:39:33
| 2023-06-20T11:04:54
| 252,368,391
| 168
| 57
|
NOASSERTION
| 2023-09-13T14:23:19
| 2020-04-02T05:57:13
|
C
|
UTF-8
|
C
| false
| false
| 3,543
|
c
|
xnvme_be_ramdisk_admin.c
|
// SPDX-FileCopyrightText: Samsung Electronics Co., Ltd
//
// SPDX-License-Identifier: BSD-3-Clause
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#endif
#include <libxnvme.h>
#include <xnvme_be.h>
#include <xnvme_be_nosys.h>
#ifdef XNVME_BE_RAMDISK_ENABLED
#include <errno.h>
#include <unistd.h>
#include <xnvme_be_ramdisk.h>
#include <xnvme_dev.h>
static int
_idfy_ctrlr_iocs_fs(struct xnvme_dev *XNVME_UNUSED(dev), void *dbuf)
{
struct xnvme_spec_fs_idfy_ctrlr *ctrlr = dbuf;
ctrlr->caps.direct = 1;
ctrlr->iosizes.min = 1;
ctrlr->iosizes.max = 1024 * 1024 * 128;
ctrlr->iosizes.opt = 1024 * 64;
ctrlr->limits.file_data_size = 1;
ctrlr->ac = 0xAC;
ctrlr->dc = 0xDC;
return 0;
}
static int
_idfy_ns_iocs_fs(struct xnvme_dev *dev, void *dbuf)
{
struct xnvme_spec_fs_idfy_ns *ns = dbuf;
size_t ramdisk_size = _xnvme_be_ramdisk_dev_get_size(dev);
if (!ramdisk_size) {
return -1;
}
ns->nsze = ramdisk_size;
ns->ncap = ramdisk_size;
ns->nuse = ramdisk_size;
ns->ac = 0xAC;
ns->dc = 0xDC;
return 0;
}
static int
_idfy_ctrlr(struct xnvme_dev *XNVME_UNUSED(dev), void *dbuf)
{
struct xnvme_spec_idfy_ctrlr *ctrlr = dbuf;
ctrlr->mdts = 0;
return 0;
}
static int
_idfy_ns(struct xnvme_dev *dev, void *dbuf)
{
struct xnvme_spec_idfy_ns *ns = dbuf;
size_t ramdisk_size;
const size_t lba_size = 512;
ramdisk_size = _xnvme_be_ramdisk_dev_get_size(dev);
if (!ramdisk_size) {
return -1;
}
ns->nsze = ramdisk_size / lba_size;
ns->ncap = ramdisk_size / lba_size;
ns->nuse = ramdisk_size / lba_size;
ns->nlbaf = 0; ///< This means that there is only one
ns->flbas.format = 0; ///< using the first one
ns->lbaf[0].ms = 0;
ns->lbaf[0].ds = XNVME_ILOG2(lba_size);
ns->lbaf[0].rp = 0;
return 0;
}
static int
_idfy(struct xnvme_cmd_ctx *ctx, void *dbuf)
{
switch (ctx->cmd.idfy.cns) {
case XNVME_SPEC_IDFY_NS:
return _idfy_ns(ctx->dev, dbuf);
case XNVME_SPEC_IDFY_CTRLR:
return _idfy_ctrlr(ctx->dev, dbuf);
case XNVME_SPEC_IDFY_NS_IOCS:
switch (ctx->cmd.idfy.csi) {
case XNVME_SPEC_CSI_FS:
return _idfy_ns_iocs_fs(ctx->dev, dbuf);
default:
break;
}
break;
case XNVME_SPEC_IDFY_CTRLR_IOCS:
switch (ctx->cmd.idfy.csi) {
case XNVME_SPEC_CSI_FS:
return _idfy_ctrlr_iocs_fs(ctx->dev, dbuf);
default:
break;
}
break;
default:
break;
}
/* ///< TODO: set some appropriate status-code for other idfy-cmds */
/* ctx->cpl.status.sc = 0x3; */
/* ctx->cpl.status.sct = 0x3; */
return 1;
}
int
_ramdisk_gfeat(struct xnvme_cmd_ctx *ctx, void *XNVME_UNUSED(dbuf))
{
struct xnvme_spec_feat feat = {0};
switch (ctx->cmd.gfeat.cdw10.fid) {
case XNVME_SPEC_FEAT_NQUEUES:
feat.nqueues.nsqa = 63;
feat.nqueues.ncqa = 63;
ctx->cpl.cdw0 = feat.val;
break;
default:
XNVME_DEBUG("FAILED: unsupported fid: %d", ctx->cmd.gfeat.cdw10.fid);
return -ENOSYS;
}
return 0;
}
int
_xnvme_be_ramdisk_admin_cmd_admin(struct xnvme_cmd_ctx *ctx, void *dbuf,
size_t XNVME_UNUSED(dbuf_nbytes), void *XNVME_UNUSED(mbuf),
size_t XNVME_UNUSED(mbuf_nbytes))
{
switch (ctx->cmd.common.opcode) {
case XNVME_SPEC_ADM_OPC_IDFY:
return _idfy(ctx, dbuf);
case XNVME_SPEC_ADM_OPC_GFEAT:
return _ramdisk_gfeat(ctx, dbuf);
default:
XNVME_DEBUG("FAILED: ENOSYS opcode: %d", ctx->cmd.common.opcode);
return -ENOSYS;
}
}
#endif
struct xnvme_be_admin g_xnvme_be_ramdisk_admin = {
.id = "ramdisk_as_ns",
#ifdef XNVME_BE_RAMDISK_ENABLED
.cmd_admin = _xnvme_be_ramdisk_admin_cmd_admin,
#else
.cmd_admin = xnvme_be_nosys_sync_cmd_admin,
#endif
};
|
c3b073511e649ab2c2143b3c1fbf2871fdac2b91
|
3eb3c4046b17e265930aaf89fa93f41896f243cb
|
/neural_modelling/src/neuron/plasticity/stdp/post_events.h
|
172741394bc2429b92a899acf6253d514ba80b31
|
[
"Apache-2.0"
] |
permissive
|
SpiNNakerManchester/sPyNNaker
|
b177613a114cfc7e7687ec36c1f72a2f07f66977
|
891cfb3046f66185fd8df52d270380fa94c32eab
|
refs/heads/master
| 2023-09-01T11:28:21.252266
| 2023-08-17T08:07:43
| 2023-08-17T08:07:43
| 20,801,613
| 101
| 53
|
Apache-2.0
| 2023-09-14T18:39:29
| 2014-06-13T11:07:19
|
Python
|
UTF-8
|
C
| false
| false
| 7,813
|
h
|
post_events.h
|
/*
* Copyright (c) 2015 The University of Manchester
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! \file
//! \brief Post-synaptic events
#ifndef _POST_EVENTS_H_
#define _POST_EVENTS_H_
// Standard includes
#include <stdbool.h>
#include <stdint.h>
// Include debug header for log_info etc
#include <debug.h>
//---------------------------------------
// Macros
//---------------------------------------
//! Maximum number of post-synaptic events supported
#define MAX_POST_SYNAPTIC_EVENTS 16
//---------------------------------------
// Structures
//---------------------------------------
//! Trace history of post-synaptic events
typedef struct {
//! Number of events stored (minus one)
uint32_t count_minus_one;
//! Event times
uint32_t times[MAX_POST_SYNAPTIC_EVENTS];
//! Event traces
post_trace_t traces[MAX_POST_SYNAPTIC_EVENTS];
} post_event_history_t;
//! Post event window description
typedef struct {
//! The previous post-synaptic event trace
post_trace_t prev_trace;
//! The previous post-synaptic event time
uint32_t prev_time;
//! The next post-synaptic event trace
const post_trace_t *next_trace;
//! The next post-synaptic event time
const uint32_t *next_time;
//! The number of events
uint32_t num_events;
//! Whether the previous post-synaptic event is valid (based on time)
uint32_t prev_time_valid;
} post_event_window_t;
//---------------------------------------
// Inline functions
//---------------------------------------
#if LOG_LEVEL >= LOG_DEBUG
//! \brief Print a post-synaptic event history
//! \param[in] events: The history
static inline void print_event_history(const post_event_history_t *events) {
log_debug(" ## printing entire post event history ##");
for (uint32_t i = 0; i <= events->count_minus_one; i++) {
log_debug("post event: %u, time: %u, trace: %u",
i, events->times[i], events->traces[i]);
}
}
#endif
//! \brief Initialise an array of post-synaptic event histories
//! \param[in] n_neurons: Number of neurons
//! \return The array
static inline post_event_history_t *post_events_init_buffers(
uint32_t n_neurons) {
post_event_history_t *post_event_history =
spin1_malloc(n_neurons * sizeof(post_event_history_t));
// Check allocations succeeded
if (post_event_history == NULL) {
log_error("Unable to allocate global STDP structures - Out of DTCM: Try "
"reducing the number of neurons per core to fix this problem ");
return NULL;
}
// Loop through neurons
for (uint32_t n = 0; n < n_neurons; n++) {
// Add initial placeholder entry to buffer
post_event_history[n].times[0] = 0;
post_event_history[n].traces[0] = timing_get_initial_post_trace();
post_event_history[n].count_minus_one = 0;
}
return post_event_history;
}
//---------------------------------------
//! \brief Get the post-synaptic event window
//! \param[in] events: The post-synaptic event history
//! \param[in] begin_time: The start of the window
//! \param[in] end_time: The end of the window
//! \return The window
static inline post_event_window_t post_events_get_window_delayed(
const post_event_history_t *events, uint32_t begin_time,
uint32_t end_time) {
// Start at end event - beyond end of post-event history
const uint32_t count = events->count_minus_one + 1;
const uint32_t *end_event_time = events->times + count;
const uint32_t *event_time = end_event_time;
const post_trace_t *event_trace = events->traces + count;
post_event_window_t window;
do {
// If this event is still in the future, set it as the end
if (*event_time > end_time) {
end_event_time = event_time;
}
// Cache pointer to this event as potential next event and go back one
// event.
// **NOTE** next_time can be invalid
window.next_time = event_time--;
window.next_trace = event_trace--;
// Keep looping while event occurred after start of window and we
// haven't hit beginning of array...
} while (*event_time > begin_time && event_time != events->times);
// Deference event to use as previous
window.prev_time = *event_time;
window.prev_trace = *event_trace;
window.prev_time_valid = event_time != events->times;
// Calculate number of events
window.num_events = (end_event_time - window.next_time);
// Return window
return window;
}
//---------------------------------------
//! \brief Advance a post-synaptic event window to the next event
//! \param[in] window: The window to advance
//! \return the advanced window
static inline post_event_window_t post_events_next(
post_event_window_t window) {
// Update previous time and increment next time
window.prev_time = *window.next_time++;
window.prev_trace = *window.next_trace++;
// Time will now be valid for sure!
window.prev_time_valid = 1;
// Decrement remaining events
window.num_events--;
return window;
}
//---------------------------------------
//! \brief Add a post-synaptic event to the history
//! \param[in] time: the time of the event
//! \param[in,out] events: the history to add to
//! \param[in] trace: the trace of the event
static inline void post_events_add(
uint32_t time, post_event_history_t *events, post_trace_t trace) {
if (events->count_minus_one < MAX_POST_SYNAPTIC_EVENTS - 1) {
// If there's still space, store time at current end
// and increment count minus 1
const uint32_t new_index = ++events->count_minus_one;
events->times[new_index] = time;
events->traces[new_index] = trace;
} else {
// Otherwise Shuffle down elements
// **NOTE** 1st element is always an entry at time 0
for (uint32_t e = 2; e < MAX_POST_SYNAPTIC_EVENTS; e++) {
events->times[e - 1] = events->times[e];
events->traces[e - 1] = events->traces[e];
}
// Stick new time at end
events->times[MAX_POST_SYNAPTIC_EVENTS - 1] = time;
events->traces[MAX_POST_SYNAPTIC_EVENTS - 1] = trace;
}
}
#if LOG_LEVEL >= LOG_DEBUG
//! \brief Print the post-synaptic event history
//! \param[in] post_event_history: the history
//! \param[in] begin_time: The start time of the history
//! \param[in] end_time: The end time of the history
//! \param[in] delay_dendritic: The amount of dendritic delay
static inline void print_delayed_window_events(
const post_event_history_t *post_event_history,
uint32_t begin_time, uint32_t end_time, uint32_t delay_dendritic) {
log_info(" ## printing post window ##");
post_event_window_t post_window = post_events_get_window_delayed(
post_event_history, begin_time, end_time);
while (post_window.num_events > 0) {
const uint32_t delayed_post_time =
*post_window.next_time + delay_dendritic;
log_info("post spike: %u, time: %u, trace: %u",
post_window.num_events, delayed_post_time,
*post_window.next_trace);
post_window = post_events_next(post_window);
}
}
#endif
#endif // _POST_EVENTS_H_
|
18c9eccbd6fe51181250542d47ac02b400597b49
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/include/mapfs/mgm_03_hit.h
|
f71921d48b52d4a97abcafafd23997bc9a79ab8c
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 448
|
h
|
mgm_03_hit.h
|
#define COLLIDER_Root 0x8
#define COLLIDER_Default 0x7
#define COLLIDER_o93 0x6
#define COLLIDER_o92 0x5
#define COLLIDER_24kaku 0x4
#define COLLIDER_18kaku 0x3
#define COLLIDER_16kaku 0x2
#define COLLIDER_12kaku 0x1
#define COLLIDER_o82 0x0
#define ZONE_Root 0x2
#define ZONE_Default 0x1
#define ZONE_o82 0x0
|
32e8aaf8547fd4564c469e4fad754a3da33bde46
|
76f7459a09acb9be2d52407132f5ff8955627da2
|
/frame/include/level0/bli_scalcjs.h
|
5619415cdda28e4a21742d256c6d79b01648f56e
|
[
"BSD-3-Clause"
] |
permissive
|
flame/blis
|
448bc0ad139b726188129c5627c304274b41c3c1
|
6dcf7666eff14348e82fbc2750be4b199321e1b9
|
refs/heads/master
| 2023-09-01T14:56:11.920485
| 2023-08-27T19:18:57
| 2023-08-27T19:18:57
| 16,143,904
| 1,696
| 361
|
NOASSERTION
| 2023-08-27T19:18:58
| 2014-01-22T15:58:24
|
C
|
UTF-8
|
C
| false
| false
| 4,699
|
h
|
bli_scalcjs.h
|
/*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
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(s) of the copyright holder(s) 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.
*/
#ifndef BLIS_SCALCJS_H
#define BLIS_SCALCJS_H
// scalcjs
// Notes:
// - The first char encodes the type of x.
// - The second char encodes the type of y.
#define bli_ssscalcjs( conjx, x, y ) bli_sscalcjris( conjx, bli_sreal(x), bli_simag(x), bli_sreal(y), bli_simag(y) )
#define bli_dsscalcjs( conjx, x, y ) bli_sscalcjris( conjx, bli_dreal(x), bli_dimag(x), bli_sreal(y), bli_simag(y) )
#define bli_csscalcjs( conjx, x, y ) bli_sscalcjris( conjx, bli_creal(x), bli_cimag(x), bli_sreal(y), bli_simag(y) )
#define bli_zsscalcjs( conjx, x, y ) bli_sscalcjris( conjx, bli_zreal(x), bli_zimag(x), bli_sreal(y), bli_simag(y) )
#define bli_sdscalcjs( conjx, x, y ) bli_dscalcjris( conjx, bli_sreal(x), bli_simag(x), bli_dreal(y), bli_dimag(y) )
#define bli_ddscalcjs( conjx, x, y ) bli_dscalcjris( conjx, bli_dreal(x), bli_dimag(x), bli_dreal(y), bli_dimag(y) )
#define bli_cdscalcjs( conjx, x, y ) bli_dscalcjris( conjx, bli_creal(x), bli_cimag(x), bli_dreal(y), bli_dimag(y) )
#define bli_zdscalcjs( conjx, x, y ) bli_dscalcjris( conjx, bli_zreal(x), bli_zimag(x), bli_dreal(y), bli_dimag(y) )
#ifndef BLIS_ENABLE_C99_COMPLEX
#define bli_scscalcjs( conjx, x, y ) bli_scscalcjris( conjx, bli_sreal(x), bli_simag(x), bli_creal(y), bli_cimag(y) )
#define bli_dcscalcjs( conjx, x, y ) bli_scscalcjris( conjx, bli_dreal(x), bli_dimag(x), bli_creal(y), bli_cimag(y) )
#define bli_ccscalcjs( conjx, x, y ) bli_cscalcjris( conjx, bli_creal(x), bli_cimag(x), bli_creal(y), bli_cimag(y) )
#define bli_zcscalcjs( conjx, x, y ) bli_cscalcjris( conjx, bli_zreal(x), bli_zimag(x), bli_creal(y), bli_cimag(y) )
#define bli_szscalcjs( conjx, x, y ) bli_dzscalcjris( conjx, bli_sreal(x), bli_simag(x), bli_zreal(y), bli_zimag(y) )
#define bli_dzscalcjs( conjx, x, y ) bli_dzscalcjris( conjx, bli_dreal(x), bli_dimag(x), bli_zreal(y), bli_zimag(y) )
#define bli_czscalcjs( conjx, x, y ) bli_zscalcjris( conjx, bli_creal(x), bli_cimag(x), bli_zreal(y), bli_zimag(y) )
#define bli_zzscalcjs( conjx, x, y ) bli_zscalcjris( conjx, bli_zreal(x), bli_zimag(x), bli_zreal(y), bli_zimag(y) )
#else // ifdef BLIS_ENABLE_C99_COMPLEX
#define bli_scscalcjs( conjx, x, y ) { (y) *= (x); }
#define bli_dcscalcjs( conjx, x, y ) { (y) *= (x); }
#define bli_ccscalcjs( conjx, x, y ) { (y) *= ( bli_is_conj( conjx ) ? conjf(x) : (x) ); }
#define bli_zcscalcjs( conjx, x, y ) { (y) *= ( bli_is_conj( conjx ) ? conj (x) : (x) ); }
#define bli_szscalcjs( conjx, x, y ) { (y) *= (x); }
#define bli_dzscalcjs( conjx, x, y ) { (y) *= (x); }
#define bli_czscalcjs( conjx, x, y ) { (y) *= ( bli_is_conj( conjx ) ? conjf(x) : (x) ); }
#define bli_zzscalcjs( conjx, x, y ) { (y) *= ( bli_is_conj( conjx ) ? conj (x) : (x) ); }
#endif // BLIS_ENABLE_C99_COMPLEX
#define bli_sscalcjs( conjx, x, y ) bli_ssscalcjs( conjx, x, y )
#define bli_dscalcjs( conjx, x, y ) bli_ddscalcjs( conjx, x, y )
#define bli_cscalcjs( conjx, x, y ) bli_ccscalcjs( conjx, x, y )
#define bli_zscalcjs( conjx, x, y ) bli_zzscalcjs( conjx, x, y )
#endif
|
d0b63a117db90302d6fa7c49c17dfaeb68f7906f
|
6a78f00818827dbcaa42628e556c50e34558138c
|
/lib/datastruct/patricia.h
|
697b905522cbd1ff4aa423a102ab06dfc47eb423
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
Tarsnap/tarsnap
|
54abaa9ce37e8cad088eb37f3609eaa37d947323
|
00c9231e784c25d519b679668707e8ce644003cb
|
refs/heads/master
| 2023-09-03T01:25:06.886320
| 2023-08-26T18:52:09
| 2023-08-26T18:52:09
| 35,801,306
| 905
| 80
|
NOASSERTION
| 2023-08-29T18:55:34
| 2015-05-18T06:44:50
|
C
|
UTF-8
|
C
| false
| false
| 1,873
|
h
|
patricia.h
|
#ifndef PATRICIA_H_
#define PATRICIA_H_
#include <stddef.h> /* size_t */
#include <stdint.h> /* uint8_t */
/**
* Structure used to store Patricia tree.
*/
typedef struct patricia_internal PATRICIA;
/**
* patricia_init(void):
* Create a Patricia tree to be used for mapping arbitrary-length keys to
* records. Return NULL on failure.
*/
PATRICIA * patricia_init(void);
/**
* patricia_insert(tree, key, keylen, rec):
* Associate the provided ${key} of length ${keylen} bytes with the pointer
* ${rec}, which must be non-NULL. Return (-1) on error, 0 on success, and 1
* if the key already exists.
*/
int patricia_insert(PATRICIA *, const uint8_t *, size_t, void *);
/**
* patricia_lookup(tree, key, keylen):
* Look up the provided ${key} of length ${keylen} bytes. Return a pointer to
* the associated _record pointer_ if the key is present in the tree (this can
* be used to change the record pointer associated with the key); or NULL
* otherwise.
*
* Note that a record can be deleted from a Patricia tree as follows:
* void ** recp = patricia_lookup(tree, key, keylen);
* if (recp != NULL)
* *recp = NULL;
* but this does not reduce the memory used by the tree as one might expect
* from reducing its size.
*/
void ** patricia_lookup(PATRICIA *, const uint8_t *, size_t);
/**
* patricia_foreach(tree, func, cookie):
* Traverse the ${tree} in lexicographical order of stored keys, and call
* ${func(cookie, key, keylen, rec)} for each (key, record) pair. Stop the
* traversal early if ${func} returns a non-zero value; return zero, the
* non-zero value returned by ${func}, or (-1) if an error occurs in the
* tree traversal.
*/
int patricia_foreach(PATRICIA *, int(void *, uint8_t *, size_t, void *),
void *);
/**
* patricia_free(tree):
* Free the ${tree}.
*/
void patricia_free(PATRICIA *);
#endif /* !PATRICIA_H_ */
|
2e544acd0e50b3428af2c353a16531267d25c3e9
|
3afd7229cfff2da1b504cf33869f0397e7d72535
|
/src/include/globalsymbols.h
|
d0eb30124099833910d44629ca1ca4b6988726b3
|
[
"MIT"
] |
permissive
|
ptitSeb/box64
|
ed62db37d8dd328316fef259be24ff95b9d785e7
|
7cba83231a0ca05a18bb6a07735ba8d5f0a216b6
|
refs/heads/main
| 2023-08-31T06:25:22.053788
| 2023-08-30T19:53:29
| 2023-08-30T19:53:29
| 317,493,442
| 2,317
| 197
|
MIT
| 2023-09-13T13:51:23
| 2020-12-01T09:42:50
|
C
|
UTF-8
|
C
| false
| false
| 451
|
h
|
globalsymbols.h
|
#ifndef _GLOBAL_SYMBOLS_H_
#define _GLOBAL_SYMBOLS_H_
//GTK stuff
void my_checkGlobalGdkDisplay(void);
void my_setGlobalGThreadsInit(void);
//void** my_GetGTKDisplay(void);
void** my_GetGthreadsGotInitialized(void); // defined in wrappedgthread2
// NCurse / TInfo
void my_checkGlobalTInfo(void);
void my_updateGlobalTInfo(void);
// getopt
void my_checkGlobalOpt(void);
void my_updateGlobalOpt(void);
#endif //_GLOBAL_SYMBOLS_H_
|
51232c408988ea873f811cb26bb7f23f1d711a05
|
f8cc1dd4b1378490386def2e0571561fab10b275
|
/src/include/skalibs/buffer.h
|
fe38120b388d040f21fe5c9b1f3c40d49d4a2126
|
[
"ISC"
] |
permissive
|
skarnet/skalibs
|
b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d
|
1f2d5f95684e93f8523e369ef1fed7a75c444082
|
refs/heads/master
| 2023-08-23T07:33:20.996016
| 2023-08-08T09:39:15
| 2023-08-08T09:39:15
| 31,461,366
| 104
| 32
|
ISC
| 2021-04-11T10:10:54
| 2015-02-28T12:01:41
|
C
|
UTF-8
|
C
| false
| false
| 4,037
|
h
|
buffer.h
|
/* ISC license. */
#ifndef SKALIBS_BUFFER_H
#define SKALIBS_BUFFER_H
#include <sys/uio.h>
#include <skalibs/gccattributes.h>
#include <skalibs/allreadwrite.h>
#include <skalibs/cbuffer.h>
#include <skalibs/functypes.h>
typedef struct buffer_s buffer, *buffer_ref ;
struct buffer_s
{
iov_func_ref op ;
int fd ;
cbuffer c ;
} ;
#define BUFFER_ZERO { 0, -1, CBUFFER_ZERO }
/*
Circular buffers need to be 1 char bigger than the storage space,
so that the head == tail case is nonambiguous (empty, not full).
*/
#define BUFFER_INSIZE 8192
#define BUFFER_OUTSIZE 8192
#define BUFFER_ERRSIZE 1024
#define BUFFER_INSIZE_SMALL 512
#define BUFFER_OUTSIZE_SMALL 512
#define BUFFER_INIT(f, d, buf, len) { (f), (d), CBUFFER_INIT(buf, len) }
extern int buffer_init (buffer *, iov_func_ref, int, char *, size_t) ;
/* Writing */
extern int buffer_flush (buffer *) ;
#define buffer_putnoflush(b, s, len) cbuffer_put(&(b)->c, s, len)
#define buffer_putvnoflush(b, v, n) cbuffer_putv(&(b)->c, v, n)
extern size_t buffer_putsnoflush (buffer *, char const *) ;
extern int buffer_putallnoflush (buffer *, char const *, size_t) ;
extern int buffer_putvallnoflush (buffer *, struct iovec const *, unsigned int) ;
extern int buffer_putsallnoflush (buffer *, char const *) ;
extern int buffer_putall (buffer *, char const *, size_t, size_t *) ;
extern int buffer_putvall (buffer *, struct iovec const *, unsigned int, size_t *) ;
extern int buffer_putsall (buffer *, char const *, size_t *) ;
#define buffer_putallflush(b, s, len, w) (buffer_putall(b, s, len, w) && buffer_flush(b))
#define buffer_putvallflush(b, v, n, w) (buffer_putvall(b, v, n, w) && buffer_flush(b))
extern int buffer_putsallflush (buffer *, char const *, size_t *) ;
extern ssize_t buffer_put (buffer *, char const *, size_t) ;
extern ssize_t buffer_putv (buffer *, struct iovec const *, unsigned int) ;
extern ssize_t buffer_puts (buffer *, char const *) ;
extern ssize_t buffer_putflush (buffer *, char const *, size_t) ;
extern ssize_t buffer_putvflush (buffer *, struct iovec const *, unsigned int) ;
extern ssize_t buffer_putsflush (buffer *, char const *) ;
#define buffer_unput(b, n) cbuffer_unput(&(b)->c, n)
#define buffer_wpeek(b, v) cbuffer_wpeek(&(b)->c, v)
#define buffer_wseek(b, n) cbuffer_wseek(&(b)->c, n)
/* Reading */
extern ssize_t buffer_fill (buffer *) ;
#define buffer_getnofill(b, s, len) cbuffer_get(&(b)->c, s, len)
#define buffer_getvnofill(b, v, n) cbuffer_getv(&(b)->c, v, n)
extern int buffer_getallnofill (buffer *, char *, size_t) ;
extern int buffer_getvallnofill (buffer *, struct iovec const *, unsigned int) ;
extern int buffer_getall (buffer *, char *, size_t, size_t *) ;
extern int buffer_getvall (buffer *, struct iovec const *, unsigned int, size_t *) ;
extern ssize_t buffer_get (buffer *, char *, size_t) ;
extern ssize_t buffer_getv (buffer *, struct iovec const *, unsigned int) ;
#define buffer_unget(b, n) cbuffer_unget(&(b)->c, n)
#define buffer_rpeek(b, v) cbuffer_rpeek(&(b)->c, v)
#define buffer_rseek(b, n) cbuffer_rseek(&(b)->c, n)
/* Utility */
#define buffer_len(b) cbuffer_len(&(b)->c)
extern size_t buffer_getlen (buffer const *) gccattr_pure ;
#define buffer_available(b) cbuffer_available(&(b)->c)
#define buffer_isempty(b) cbuffer_isempty(&(b)->c)
#define buffer_isfull(b) cbuffer_isfull(&(b)->c)
#define buffer_fd(b) ((b)->fd)
extern int buffer_getfd (buffer const *) gccattr_pure ;
#define buffer_isreadable(b) (!buffer_isfull(b))
#define buffer_iswritable(b) (!buffer_isempty(b))
/* Globals */
#define buffer_read fd_readv
#define buffer_write fd_writev
extern iov_func buffer_flush1read ;
extern buffer buffer_0_ ;
#define buffer_0 (&buffer_0_)
extern buffer buffer_0small_ ;
#define buffer_0small (&buffer_0small_)
extern buffer buffer_0f1_ ;
#define buffer_0f1 (&buffer_0f1_)
extern buffer buffer_1_ ;
#define buffer_1 (&buffer_1_)
extern buffer buffer_1small_ ;
#define buffer_1small (&buffer_1small_)
extern buffer buffer_2_ ;
#define buffer_2 (&buffer_2_)
#endif
|
99257693cc421193b9585486225d5af6d6a0dc23
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/libaom/source/libaom/av1/encoder/ratectrl.h
|
256faed201f03ab50d8a45e1184559b8a73e9c49
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 24,517
|
h
|
ratectrl.h
|
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#ifndef AOM_AV1_ENCODER_RATECTRL_H_
#define AOM_AV1_ENCODER_RATECTRL_H_
#include "aom/aom_codec.h"
#include "aom/aom_integer.h"
#include "aom_ports/mem.h"
#include "av1/common/av1_common_int.h"
#include "av1/common/blockd.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!\cond */
// Bits Per MB at different Q (Multiplied by 512)
#define BPER_MB_NORMBITS 9
// Use this macro to turn on/off use of alt-refs in one-pass mode.
#define USE_ALTREF_FOR_ONE_PASS 1
// Threshold used to define if a KF group is static (e.g. a slide show).
// Essentially, this means that no frame in the group has more than 1% of MBs
// that are not marked as coded with 0,0 motion in the first pass.
#define STATIC_KF_GROUP_THRESH 99
#define STATIC_KF_GROUP_FLOAT_THRESH 0.99
// The maximum duration of a GF group that is static (e.g. a slide show).
#define MAX_STATIC_GF_GROUP_LENGTH 250
#define MIN_GF_INTERVAL 4
#define MAX_GF_INTERVAL 32
#define FIXED_GF_INTERVAL 16
#define MAX_GF_LENGTH_LAP 16
#define FIXED_GF_INTERVAL_RT 80
#define MAX_GF_INTERVAL_RT 160
#define MAX_NUM_GF_INTERVALS 15
#define MAX_ARF_LAYERS 6
// #define STRICT_RC
#define DEFAULT_KF_BOOST_RT 2300
#define DEFAULT_GF_BOOST_RT 2000
// A passive rate control strategy for screen content type in real-time mode.
// When it is turned on, the compression performance is improved by
// 7.8% (overall_psnr), 5.0% (VMAF) on average. Some clips see gains
// over 20% on metric.
// The downside is that it does not guarantee frame size.
// Since RT mode has a tight restriction on buffer overflow control, we
// turn it off by default.
#define RT_PASSIVE_STRATEGY 0
#define MAX_Q_HISTORY 1000
typedef struct {
int resize_width;
int resize_height;
uint8_t superres_denom;
} size_params_type;
enum {
INTER_NORMAL,
GF_ARF_LOW,
GF_ARF_STD,
KF_STD,
RATE_FACTOR_LEVELS
} UENUM1BYTE(RATE_FACTOR_LEVEL);
enum {
KF_UPDATE,
LF_UPDATE,
GF_UPDATE,
ARF_UPDATE,
OVERLAY_UPDATE,
INTNL_OVERLAY_UPDATE, // Internal Overlay Frame
INTNL_ARF_UPDATE, // Internal Altref Frame
FRAME_UPDATE_TYPES
} UENUM1BYTE(FRAME_UPDATE_TYPE);
enum {
REFBUF_RESET, // Clear reference frame buffer
REFBUF_UPDATE, // Refresh reference frame buffer
REFBUF_STATES
} UENUM1BYTE(REFBUF_STATE);
typedef enum {
NO_RESIZE = 0,
DOWN_THREEFOUR = 1, // From orig to 3/4.
DOWN_ONEHALF = 2, // From orig or 3/4 to 1/2.
UP_THREEFOUR = -1, // From 1/2 to 3/4.
UP_ORIG = -2, // From 1/2 or 3/4 to orig.
} RESIZE_ACTION;
typedef enum { ORIG = 0, THREE_QUARTER = 1, ONE_HALF = 2 } RESIZE_STATE;
#define MAX_FIRSTPASS_ANALYSIS_FRAMES 150
typedef enum region_types {
STABLE_REGION = 0,
HIGH_VAR_REGION = 1,
SCENECUT_REGION = 2,
BLENDING_REGION = 3,
} REGION_TYPES;
typedef struct regions {
int start;
int last;
double avg_noise_var;
double avg_cor_coeff;
double avg_sr_fr_ratio;
double avg_intra_err;
double avg_coded_err;
REGION_TYPES type;
} REGIONS;
/*!\endcond */
/*!
* \brief Rate Control parameters and status
*/
typedef struct {
// Rate targetting variables
/*!
* Baseline target rate for frame before adjustment for previous under or
* over shoot.
*/
int base_frame_target;
/*!
* Target rate for frame after adjustment for previous under or over shoot.
*/
int this_frame_target; // Actual frame target after rc adjustment.
/*!
* Projected size for current frame
*/
int projected_frame_size;
/*!
* Bit size of transform coefficient for current frame.
*/
int coefficient_size;
/*!
* Super block rate target used with some adaptive quantization strategies.
*/
int sb64_target_rate;
/*!
* Number of frames since the last ARF / GF.
*/
int frames_since_golden;
/*!
* Number of frames till the next ARF / GF is due.
*/
int frames_till_gf_update_due;
/*!
* Number of determined gf groups left
*/
int intervals_till_gf_calculate_due;
/*!\cond */
int min_gf_interval;
int max_gf_interval;
int static_scene_max_gf_interval;
/*!\endcond */
/*!
* Frames before the next key frame
*/
int frames_to_key;
/*!\cond */
int frames_since_key;
int frames_to_fwd_kf;
int is_src_frame_alt_ref;
int sframe_due;
int high_source_sad;
uint64_t avg_source_sad;
uint64_t prev_avg_source_sad;
uint64_t frame_source_sad;
int avg_frame_bandwidth; // Average frame size target for clip
int min_frame_bandwidth; // Minimum allocation used for any frame
int max_frame_bandwidth; // Maximum burst rate allowed for a frame.
int prev_avg_frame_bandwidth;
int ni_av_qi;
int ni_tot_qi;
int decimation_factor;
int decimation_count;
/*!\endcond */
/*!
* User specified maximum Q allowed for current frame
*/
int worst_quality;
/*!
* User specified minimum Q allowed for current frame
*/
int best_quality;
/*!\cond */
// rate control history for last frame(1) and the frame before(2).
// -1: overshoot
// 1: undershoot
// 0: not initialized.
int rc_1_frame;
int rc_2_frame;
int q_1_frame;
int q_2_frame;
/*!\endcond */
/*!
* Proposed maximum allowed Q for current frame
*/
int active_worst_quality;
/*!\cond */
// Track amount of low motion in scene
int avg_frame_low_motion;
int cnt_zeromv;
// signals if number of blocks with motion is high
int percent_blocks_with_motion;
// Maximum value of source sad across all blocks of frame.
uint64_t max_block_source_sad;
// For dynamic resize, 1 pass cbr.
RESIZE_STATE resize_state;
int resize_avg_qp;
int resize_buffer_underflow;
int resize_count;
// Flag to disable content related qp adjustment.
int rtc_external_ratectrl;
// Stores fast_extra_bits of the current frame.
int frame_level_fast_extra_bits;
double frame_level_rate_correction_factors[RATE_FACTOR_LEVELS];
int frame_num_last_gf_refresh;
int prev_coded_width;
int prev_coded_height;
// The ratio used for inter frames in bit estimation.
// TODO(yunqing): if golden frame is treated differently (e.g. gf_cbr_boost_
// pct > THR), consider to add bit_est_ratio_g for golden frames.
int bit_est_ratio;
// Whether to use a fixed qp for the frame, bypassing internal rate control.
// This flag will reset to 0 after every frame.
int use_external_qp_one_pass;
/*!\endcond */
} RATE_CONTROL;
/*!
* \brief Primary Rate Control parameters and status
*/
typedef struct {
// Sub-gop level Rate targetting variables
/*!
* Target bit budget for the current GF / ARF group of frame.
*/
int64_t gf_group_bits;
/*!
* Boost factor used to calculate the extra bits allocated to the key frame
*/
int kf_boost;
/*!
* Boost factor used to calculate the extra bits allocated to ARFs and GFs
*/
int gfu_boost;
/*!
* Stores the determined gf group lengths for a set of gf groups
*/
int gf_intervals[MAX_NUM_GF_INTERVALS];
/*!
* The current group's index into gf_intervals[]
*/
int cur_gf_index;
/*!\cond */
int num_regions;
REGIONS regions[MAX_FIRSTPASS_ANALYSIS_FRAMES];
int regions_offset; // offset of regions from the last keyframe
int frames_till_regions_update;
int baseline_gf_interval;
int constrained_gf_group;
int this_key_frame_forced;
int next_key_frame_forced;
/*!\endcond */
/*!
* Initial buffuer level in ms for CBR / low delay encoding
*/
int64_t starting_buffer_level;
/*!
* Optimum / target buffuer level in ms for CBR / low delay encoding
*/
int64_t optimal_buffer_level;
/*!
* Maximum target buffuer level in ms for CBR / low delay encoding
*/
int64_t maximum_buffer_size;
/*!
* Q index used for ALT frame
*/
int arf_q;
/*!\cond */
float_t arf_boost_factor;
int base_layer_qp;
// Total number of stats used only for kf_boost calculation.
int num_stats_used_for_kf_boost;
// Total number of stats used only for gfu_boost calculation.
int num_stats_used_for_gfu_boost;
// Total number of stats required by gfu_boost calculation.
int num_stats_required_for_gfu_boost;
int enable_scenecut_detection;
int use_arf_in_this_kf_group;
int ni_frames;
double tot_q;
/*!\endcond */
/*!
* Q used for last boosted (non leaf) frame
*/
int last_kf_qindex;
/*!
* Average of q index of previous encoded frames in a sequence.
*/
int avg_frame_qindex[FRAME_TYPES];
#if CONFIG_FPMT_TEST
/*!
* Temporary variable used in simulating the delayed update of
* active_best_quality.
*/
int temp_active_best_quality[MAX_ARF_LAYERS + 1];
/*!
* Temporary variable used in simulating the delayed update of
* last_boosted_qindex.
*/
int temp_last_boosted_qindex;
/*!
* Temporary variable used in simulating the delayed update of
* avg_q.
*/
double temp_avg_q;
/*!
* Temporary variable used in simulating the delayed update of
* last_q.
*/
int temp_last_q[FRAME_TYPES];
/*!
* Temporary variable used in simulating the delayed update of
* projected_frame_size.
*/
int temp_projected_frame_size;
/*!
* Temporary variable used in simulating the delayed update of
* total_actual_bits.
*/
int64_t temp_total_actual_bits;
/*!
* Temporary variable used in simulating the delayed update of
* buffer_level.
*/
int64_t temp_buffer_level;
/*!
* Temporary variable used in simulating the delayed update of
* vbr_bits_off_target.
*/
int64_t temp_vbr_bits_off_target;
/*!
* Temporary variable used in simulating the delayed update of
* vbr_bits_off_target_fast.
*/
int64_t temp_vbr_bits_off_target_fast;
/*!
* Temporary variable used in simulating the delayed update of
* rate_correction_factors.
*/
double temp_rate_correction_factors[RATE_FACTOR_LEVELS];
/*!
* Temporary variable used in simulating the delayed update of
* rate_error_estimate.
*/
int temp_rate_error_estimate;
/*!
* Temporary variable used in simulating the delayed update of
* rolling_arf_group_target_bits.
*/
int temp_rolling_arf_group_target_bits;
/*!
* Temporary variable used in simulating the delayed update of
* rolling_arf_group_actual_bits;.
*/
int temp_rolling_arf_group_actual_bits;
/*!
* Temporary variable used in simulating the delayed update of
* bits_left;.
*/
int64_t temp_bits_left;
/*!
* Temporary variable used in simulating the delayed update of
* extend_minq.
*/
int temp_extend_minq;
/*!
* Temporary variable used in simulating the delayed update of
* extend_maxq.
*/
int temp_extend_maxq;
/*!
* Temporary variable used in simulating the delayed update of
* extend_minq_fast.
*/
int temp_extend_minq_fast;
#endif
/*!
* Proposed minimum allowed Q different layers in a coding pyramid
*/
int active_best_quality[MAX_ARF_LAYERS + 1];
/*!
* Q used for last boosted (non leaf) frame (GF/KF/ARF)
*/
int last_boosted_qindex;
/*!
* Average Q value of previous inter frames
*/
double avg_q;
/*!
* Q used on last encoded frame of the given type.
*/
int last_q[FRAME_TYPES];
/*!
* Correction factors used to adjust the q estimate for a given target rate
* in the encode loop.
*/
double rate_correction_factors[RATE_FACTOR_LEVELS];
/*!
* Current total consumed bits.
*/
int64_t total_actual_bits;
/*!
* Current total target bits.
*/
int64_t total_target_bits;
/*!
* Current buffer level.
*/
int64_t buffer_level;
/*!
* PCT rc error.
*/
int rate_error_estimate;
/*!
* Error bits available from previously encoded frames.
*/
int64_t vbr_bits_off_target;
/*!
* Error bits available from previously encoded frames undershoot.
*/
int64_t vbr_bits_off_target_fast;
/*!
* Total bits deviated from the average frame target, from previously
* encoded frames.
*/
int64_t bits_off_target;
/*!
* Rolling monitor target bits updated based on current frame target size.
*/
int rolling_target_bits;
/*!
* Rolling monitor actual bits updated based on current frame final projected
* size.
*/
int rolling_actual_bits;
/*!
* The history of qindex for each frame.
* Only used when RT_PASSIVE_STRATEGY = 1.
*/
int q_history[MAX_Q_HISTORY];
} PRIMARY_RATE_CONTROL;
/*!\cond */
struct AV1_COMP;
struct AV1EncoderConfig;
struct GF_GROUP;
void av1_primary_rc_init(const struct AV1EncoderConfig *oxcf,
PRIMARY_RATE_CONTROL *p_rc);
void av1_rc_init(const struct AV1EncoderConfig *oxcf, RATE_CONTROL *rc);
int av1_estimate_bits_at_q(const struct AV1_COMP *cpi, int q,
double correction_factor);
double av1_convert_qindex_to_q(int qindex, aom_bit_depth_t bit_depth);
void av1_rc_init_minq_luts(void);
int av1_rc_get_default_min_gf_interval(int width, int height, double framerate);
// Note av1_rc_get_default_max_gf_interval() requires the min_gf_interval to
// be passed in to ensure that the max_gf_interval returned is at least as bis
// as that.
int av1_rc_get_default_max_gf_interval(double framerate, int min_gf_interval);
// Generally at the high level, the following flow is expected
// to be enforced for rate control:
// First call per frame, one of:
// av1_get_one_pass_rt_params()
// av1_get_second_pass_params()
// depending on the usage to set the rate control encode parameters desired.
//
// Then, call encode_frame_to_data_rate() to perform the
// actual encode. This function will in turn call encode_frame()
// one or more times, followed by:
// av1_rc_postencode_update_drop_frame()
//
// The majority of rate control parameters are only expected
// to be set in the av1_get_..._params() functions and
// updated during the av1_rc_postencode_update...() functions.
// The only exceptions are av1_rc_drop_frame() and
// av1_rc_update_rate_correction_factors() functions.
// Functions to set parameters for encoding before the actual
// encode_frame_to_data_rate() function.
struct EncodeFrameInput;
// Post encode update of the rate control parameters based
// on bytes used
void av1_rc_postencode_update(struct AV1_COMP *cpi, uint64_t bytes_used);
// Post encode update of the rate control parameters for dropped frames
void av1_rc_postencode_update_drop_frame(struct AV1_COMP *cpi);
/*!\endcond */
/*!\brief Updates the rate correction factor linking Q to output bits
*
* This function updates the Q rate correction factor after an encode
* cycle depending on whether we overshot or undershot the target rate.
*
* \ingroup rate_control
* \param[in] cpi Top level encoder instance structure
* \param[in] is_encode_stage Indicates if recode loop or post-encode
* \param[in] width Frame width
* \param[in] height Frame height
*
* \remark Updates the relevant rate correction factor in cpi->rc
*/
void av1_rc_update_rate_correction_factors(struct AV1_COMP *cpi,
int is_encode_stage, int width,
int height);
/*!\cond */
// Decide if we should drop this frame: For 1-pass CBR.
// Changes only the decimation count in the rate control structure
int av1_rc_drop_frame(struct AV1_COMP *cpi);
// Computes frame size bounds.
void av1_rc_compute_frame_size_bounds(const struct AV1_COMP *cpi,
int this_frame_target,
int *frame_under_shoot_limit,
int *frame_over_shoot_limit);
/*!\endcond */
/*!\brief Picks q and q bounds given the rate control parameters in \c cpi->rc.
*
* \ingroup rate_control
* \param[in] cpi Top level encoder structure
* \param[in] width Coded frame width
* \param[in] height Coded frame height
* \param[in] gf_index Index of this frame in the golden frame group
* \param[out] bottom_index Bottom bound for q index (best quality)
* \param[out] top_index Top bound for q index (worst quality)
* \return Returns selected q index to be used for encoding this frame.
* Also, updates \c rc->arf_q.
*/
int av1_rc_pick_q_and_bounds(struct AV1_COMP *cpi, int width, int height,
int gf_index, int *bottom_index, int *top_index);
/*!\brief Estimates q to achieve a target bits per frame
*
* \ingroup rate_control
* \param[in] cpi Top level encoder instance structure
* \param[in] target_bits_per_frame Frame rate target
* \param[in] active_worst_quality Max Q allowed
* \param[in] active_best_quality Min Q allowed
* \param[in] width Frame width
* \param[in] height Frame height
*
* \return Returns a q index value
*/
int av1_rc_regulate_q(const struct AV1_COMP *cpi, int target_bits_per_frame,
int active_best_quality, int active_worst_quality,
int width, int height);
/*!\cond */
// Gets the appropriate bpmb ennumerator based on the frame and content type
int av1_get_bpmb_enumerator(FRAME_TYPE frame_type,
const int is_screen_content_type);
// Estimates bits per mb for a given qindex and correction factor.
int av1_rc_bits_per_mb(const struct AV1_COMP *cpi, FRAME_TYPE frame_type,
int qindex, double correction_factor,
int accurate_estimate);
// Clamping utilities for bitrate targets for iframes and pframes.
int av1_rc_clamp_iframe_target_size(const struct AV1_COMP *const cpi,
int64_t target);
int av1_rc_clamp_pframe_target_size(const struct AV1_COMP *const cpi,
int target, uint8_t frame_update_type);
// Find q_index corresponding to desired_q, within [best_qindex, worst_qindex].
// To be precise, 'q_index' is the smallest integer, for which the corresponding
// q >= desired_q.
// If no such q index is found, returns 'worst_qindex'.
int av1_find_qindex(double desired_q, aom_bit_depth_t bit_depth,
int best_qindex, int worst_qindex);
// Computes a q delta (in "q index" terms) to get from a starting q value
// to a target q value
int av1_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
aom_bit_depth_t bit_depth);
// Computes a q delta (in "q index" terms) to get from a starting q value
// to a value that should equate to the given rate ratio.
int av1_compute_qdelta_by_rate(const struct AV1_COMP *cpi,
FRAME_TYPE frame_type, int qindex,
double rate_target_ratio);
int av1_frame_type_qdelta(const struct AV1_COMP *cpi, int q);
void av1_rc_update_framerate(struct AV1_COMP *cpi, int width, int height);
void av1_rc_set_gf_interval_range(const struct AV1_COMP *const cpi,
RATE_CONTROL *const rc);
void av1_set_target_rate(struct AV1_COMP *cpi, int width, int height);
int av1_resize_one_pass_cbr(struct AV1_COMP *cpi);
void av1_rc_set_frame_target(struct AV1_COMP *cpi, int target, int width,
int height);
void av1_adjust_gf_refresh_qp_one_pass_rt(struct AV1_COMP *cpi);
void av1_set_rtc_reference_structure_one_layer(struct AV1_COMP *cpi,
int gf_update);
/*!\endcond */
/*!\brief Calculates how many bits to use for a P frame in one pass vbr
*
* \ingroup rate_control
* \callgraph
* \callergraph
*
* \param[in] cpi Top level encoder structure
* \param[in] frame_update_type Type of frame
*
* \return Returns the target number of bits for this frame.
*/
int av1_calc_pframe_target_size_one_pass_vbr(
const struct AV1_COMP *const cpi, FRAME_UPDATE_TYPE frame_update_type);
/*!\brief Calculates how many bits to use for an i frame in one pass vbr
*
* \ingroup rate_control
* \callgraph
* \callergraph
*
* \param[in] cpi Top level encoder structure
*
* \return Returns the target number of bits for this frame.
*/
int av1_calc_iframe_target_size_one_pass_vbr(const struct AV1_COMP *const cpi);
/*!\brief Calculates how many bits to use for a P frame in one pass cbr
*
* \ingroup rate_control
* \callgraph
* \callergraph
*
* \param[in] cpi Top level encoder structure
* \param[in] frame_update_type Type of frame
*
* \return Returns the target number of bits for this frame.
*/
int av1_calc_pframe_target_size_one_pass_cbr(
const struct AV1_COMP *cpi, FRAME_UPDATE_TYPE frame_update_type);
/*!\brief Calculates how many bits to use for an i frame in one pass cbr
*
* \ingroup rate_control
* \callgraph
* \callergraph
*
* \param[in] cpi Top level encoder structure
*
* \return Returns the target number of bits for this frame.
*/
int av1_calc_iframe_target_size_one_pass_cbr(const struct AV1_COMP *cpi);
/*!\brief Setup the rate control parameters for 1 pass real-time mode.
*
* - Sets the frame type and target frame size.
* - Sets the GF update.
* - Checks for scene change.
* - Sets the reference prediction structure for 1 layers (non-SVC).
* - Resets and updates are done for SVC.
*
* \ingroup rate_control
* \param[in] cpi Top level encoder structure
* \param[in] frame_type Encoder frame type
* \param[in] frame_input Current and last input source frames
* \param[in] frame_flags Encoder frame flags
*
* \remark Nothing is returned. Instead the settings computed in this
* function are set in: \c frame_params, \c cpi->common, \c cpi->rc,
* \c cpi->svc.
*/
void av1_get_one_pass_rt_params(struct AV1_COMP *cpi,
FRAME_TYPE *const frame_type,
const struct EncodeFrameInput *frame_input,
unsigned int frame_flags);
/*!\brief Increase q on expected encoder overshoot, for CBR mode.
*
* Handles the case when encoder is expected to create a large frame:
* - q is increased to value closer to \c cpi->rc.worst_quality
* - avg_frame_qindex is reset
* - buffer levels are reset
* - rate correction factor is adjusted
*
* \ingroup rate_control
* \param[in] cpi Top level encoder structure
* \param[in] q Current q index
*
* \return q is returned, and updates are done to \c cpi->rc.
*/
int av1_encodedframe_overshoot_cbr(struct AV1_COMP *cpi, int *q);
/*!\brief Compute the q_indices for a single frame.
*
* Intended to be used with AOM_Q mode.
*
* \param[in] base_q_index Base q index
* \param[in] gf_update_type GOP update type
* \param[in] gf_pyramid_level GOP level of the current frame
* \param[in] arf_q ARF q_index
*
* \return Returns the q_index for the current frame.
*/
int av1_q_mode_get_q_index(int base_q_index, int gf_update_type,
int gf_pyramid_level, int arf_q);
/*!\brief Compute the q_indices for the ARF of a GOP.
*
* \param[in] base_q_index Base q index
* \param[in] gfu_boost GFU boost
* \param[in] bit_depth Bit depth
* \param[in] arf_boost_factor ARF boost factor
*
* \return Returns the q_index for the ARF frame.
*/
int av1_get_arf_q_index(int base_q_index, int gfu_boost, int bit_depth,
double arf_boost_factor);
#if !CONFIG_REALTIME_ONLY
struct TplDepFrame;
/*!\brief Compute the q_indices for the ARF of a GOP in Q mode.
*
* \param[in] cpi Top level encoder structure
* \param[in] tpl_frame Tpl Frame stats
*
* \return Returns the q_index for the ARF frame.
*/
int av1_get_arf_q_index_q_mode(struct AV1_COMP *cpi,
struct TplDepFrame *tpl_frame);
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif // AOM_AV1_ENCODER_RATECTRL_H_
|
b397de0bd584c90397476f2fefd624db3aa14083
|
407d194b52fe9cf75cca9d6f3c162a565549a1ae
|
/AzureEnhancedMonitor/clib/src/apmetric.c
|
562ceb3baf9784a2db69e45a3e06c24838aa826f
|
[
"Apache-2.0"
] |
permissive
|
Azure/azure-linux-extensions
|
808761f927045f00548aa68e38d4bec8651c0eba
|
3cea1567fc4f4eb5beea9884153e92d70610394d
|
refs/heads/master
| 2023-08-27T14:06:05.775617
| 2023-08-23T01:56:05
| 2023-08-23T01:56:05
| 19,841,123
| 300
| 314
|
Apache-2.0
| 2023-09-14T04:21:26
| 2014-05-16T01:38:49
|
Python
|
UTF-8
|
C
| false
| false
| 10,707
|
c
|
apmetric.c
|
//
// Copyright 2014 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// This file is auto-generated, don't modify it directly.
//
#include <stdlib.h>
#include <azureperf.h>
int ap_metric_config_cloud_provider(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Cloud Provider", size);
}
int ap_metric_config_cpu_over_provisioning(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "CPU Over-Provisioning", size);
}
int ap_metric_config_memory_over_provisioning(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Memory Over-Provisioning", size);
}
int ap_metric_config_data_provider_version(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Data Provider Version", size);
}
int ap_metric_config_data_sources(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Data Sources", size);
}
int ap_metric_config_instance_type(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Instance Type", size);
}
int ap_metric_config_virtualization_solution(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Virtualization Solution", size);
}
int ap_metric_config_virtualization_solution_version(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Virtualization Solution Version", size);
}
int ap_metric_cpu_current_hw_frequency(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Current Hw Frequency", size);
}
int ap_metric_cpu_max_hw_frequency(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Max Hw Frequency", size);
}
int ap_metric_cpu_current_vm_processing_power(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Current VM Processing Power", size);
}
int ap_metric_cpu_guaranteed_vm_processing_power(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Guaranteed VM Processing Power", size);
}
int ap_metric_cpu_max_vm_processing_power(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Max. VM Processing Power", size);
}
int ap_metric_cpu_number_of_cores_per_cpu(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Number of Cores per CPU", size);
}
int ap_metric_cpu_number_of_threads_per_core(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Number of Threads per Core", size);
}
int ap_metric_cpu_phys_processing_power_per_vcpu(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Phys. Processing Power per vCPU", size);
}
int ap_metric_cpu_processor_type(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Processor Type", size);
}
int ap_metric_cpu_reference_compute_unit(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "Reference Compute Unit", size);
}
int ap_metric_cpu_vcpu_mapping(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "vCPU Mapping", size);
}
int ap_metric_cpu_vm_processing_power_consumption(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "cpu", "VM Processing Power Consumption", size);
}
int ap_metric_memory_current_memory_assigned(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "memory", "Current Memory assigned", size);
}
int ap_metric_memory_guaranteed_memory_assigned(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "memory", "Guaranteed Memory assigned", size);
}
int ap_metric_memory_max_memory_assigned(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "memory", "Max Memory assigned", size);
}
int ap_metric_memory_vm_memory_consumption(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "memory", "VM Memory Consumption", size);
}
int ap_metric_network_adapter_id(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Adapter Id", size);
}
int ap_metric_network_mapping(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Mapping", size);
}
int ap_metric_network_min_network_bandwidth(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Minimum Network Bandwidth", size);
}
int ap_metric_network_max_network_bandwidth(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Maximum Network Bandwidth", size);
}
int ap_metric_network_network_read_bytes(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Network Read Bytes", size);
}
int ap_metric_network_network_write_bytes(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Network Write Bytes", size);
}
int ap_metric_network_packets_retransmitted(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "network", "Packets Retransmitted", size);
}
int ap_metric_config_last_hardware_change(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "config", "Last Hardware Change", size);
}
int ap_metric_storage_phys_disc_to_storage_mapping(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Phys. Disc to Storage Mapping", size);
}
int ap_metric_storage_storage_id(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage ID", size);
}
int ap_metric_storage_read_bytes(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Read Bytes", size);
}
int ap_metric_storage_read_ops(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Read Ops", size);
}
int ap_metric_storage_read_op_latency_e2e(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Read Op Latency E2E msec", size);
}
int ap_metric_storage_read_op_latency_server(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Read Op Latency Server msec", size);
}
int ap_metric_storage_read_throughput_e2e(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Read Throughput E2E MB/sec", size);
}
int ap_metric_storage_write_bytes(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Write Bytes", size);
}
int ap_metric_storage_write_ops(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Write Ops", size);
}
int ap_metric_storage_write_op_latency_e2e(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Write Op Latency E2E msec", size);
}
int ap_metric_storage_write_op_latency_server(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Write Op Latency Server msec", size);
}
int ap_metric_storage_write_throughput_e2e(ap_handler *handler, perf_counter *pc, size_t size)
{
if(handler->err)
{
return 0;
}
return get_metric(handler, pc, "storage", "Storage Write Throughput E2E MB/sec", size);
}
|
86fad478819959e8aee7a8c0abc84620deeb0091
|
77fee94c58cd5b6305eef2f13d74b488db428c59
|
/litex/soc/software/bios/sim_debug.h
|
9402219b4abc3eaf58976cd6269daaf1f6f34f0a
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
enjoy-digital/litex
|
de5919d649c1b884c47a5e0364c2a9a584ebd614
|
405296b7fd99764af21fffd94afa5075c22affa8
|
refs/heads/master
| 2023-08-31T23:52:33.895792
| 2023-08-31T17:34:55
| 2023-08-31T17:36:21
| 45,734,719
| 2,351
| 524
|
NOASSERTION
| 2023-09-14T21:26:26
| 2015-11-07T12:02:12
|
C
|
UTF-8
|
C
| false
| false
| 480
|
h
|
sim_debug.h
|
#ifndef __SIM_DEBUG_H
#define __SIM_DEBUG_H
#ifdef __cplusplus
extern "C" {
#endif
// add next marker with given comment
void sim_mark(const char *comment);
#define sim_mark_func() sim_mark(__func__)
// print the summary of markers mapping (number -> comment)
void sim_markers_summary(void);
// enable simulation trace dump
void sim_trace(int on);
// check if trace is on
int sim_trace_on(void);
// finish simulation
void sim_finish(void);
#ifdef __cplusplus
}
#endif
#endif
|
3d0b1d1f920887aa6e71c7b19e833483d8ffedae
|
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
|
/src/mono/mono/eventpipe/test/dn-queue-tests.c
|
39a35c5b9b7636b38c6cb81623c838b11e7af1bb
|
[
"MIT"
] |
permissive
|
dotnet/runtime
|
f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f
|
47bb554d298e1e34c4e3895d7731e18ad1c47d02
|
refs/heads/main
| 2023-09-03T15:35:46.493337
| 2023-09-03T08:13:23
| 2023-09-03T08:13:23
| 210,716,005
| 13,765
| 5,179
|
MIT
| 2023-09-14T21:58:52
| 2019-09-24T23:36:39
|
C#
|
UTF-8
|
C
| false
| false
| 7,179
|
c
|
dn-queue-tests.c
|
#if defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <eglib/test/test.h>
#include <containers/dn-queue.h>
#ifdef _CRTDBG_MAP_ALLOC
static _CrtMemState dn_queue_memory_start_snapshot;
static _CrtMemState dn_queue_memory_end_snapshot;
static _CrtMemState dn_queue_memory_diff_snapshot;
#endif
#define N_ELEMS 101
#define POINTER_TO_INT32(v) ((int32_t)(ptrdiff_t)(v))
#define INT32_TO_POINTER(v) ((void *)(ptrdiff_t)(v))
static
void
DN_CALLBACK_CALLTYPE
test_queue_dispose_func (void *data)
{
(*(uint32_t *)data)++;
}
static
RESULT
test_queue_setup (void)
{
#ifdef _CRTDBG_MAP_ALLOC
_CrtMemCheckpoint (&dn_queue_memory_start_snapshot);
#endif
return OK;
}
static
RESULT
test_queue_alloc (void)
{
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_init (void)
{
dn_queue_t queue;
if (!dn_queue_init (&queue))
return FAILED ("failed to init queue");
dn_queue_dispose (&queue);
return OK;
}
static
RESULT
test_queue_free (void)
{
uint32_t dispose_count = 0;
dn_queue_t *queue = dn_queue_custom_alloc (DN_DEFAULT_ALLOCATOR);
if (!queue)
return FAILED ("failed to custom alloc queue");
dn_queue_push (queue, &dispose_count);
dn_queue_push (queue, &dispose_count);
dn_queue_custom_free (queue, test_queue_dispose_func);
if (dispose_count != 2)
return FAILED ("invalid dispose count on free");
return OK;
}
static
RESULT
test_queue_dispose (void)
{
uint32_t dispose_count = 0;
dn_queue_t queue;
if (!dn_queue_custom_init (&queue, DN_DEFAULT_ALLOCATOR))
return FAILED ("failed to custom init queue");
dn_queue_push (&queue, &dispose_count);
dn_queue_push (&queue, &dispose_count);
dn_queue_custom_dispose (&queue, test_queue_dispose_func);
if (dispose_count != 2)
return FAILED ("invalid dispose count on free");
return OK;
}
static
RESULT
test_queue_front (void)
{
const char * items[] = { "first", "second" };
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
dn_queue_push (queue, (char *)items [0]);
if (*dn_queue_front_t (queue, char *) != items [0])
return FAILED ("failed queue front #1");
dn_queue_push (queue, (char *)items [1]);
if (*dn_queue_front_t (queue, char *) != items [0])
return FAILED ("failed queue front #2");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_back (void)
{
const char * items[] = { "first", "second" };
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
dn_queue_push (queue, (char *)items [0]);
if (*dn_queue_back_t (queue, char *) != items [0])
return FAILED ("failed queue front #1");
dn_queue_push (queue, (char *)items [1]);
if (*dn_queue_back_t (queue, char *) != items [1])
return FAILED ("failed queue front #2");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_empty (void)
{
const char * items[] = { "first", "second" };
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
if (!dn_queue_empty (queue))
return FAILED ("failed empty #1");
dn_queue_push (queue, (char *)items [0]);
if (dn_queue_empty (queue))
return FAILED ("failed empty #2");
dn_queue_push (queue, (char *)items [1]);
if (dn_queue_empty (queue))
return FAILED ("failed empty #3");
dn_queue_pop (queue);
if (dn_queue_empty (queue))
return FAILED ("failed empty #4");
dn_queue_pop (queue);
if (!dn_queue_empty (queue))
return FAILED ("failed empty #5");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_size (void)
{
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
for (uint32_t i = 0; i < N_ELEMS; i++)
dn_queue_push_t (queue, uint32_t, i);
if (dn_queue_size (queue) != N_ELEMS)
return FAILED ("failed queue size");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_push_pop (void)
{
uint32_t dispose_count = 0;
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
for (uint32_t i = 0; i < N_ELEMS; i++) {
if (!dn_queue_push_t (queue, uint32_t, i))
return FAILED ("failed to push to queue");
}
if (*dn_queue_back_t (queue, uint32_t) != N_ELEMS - 1)
return FAILED ("incorrect back of queue");
uint32_t count;
for (count = 0; count < N_ELEMS && !dn_queue_empty (queue); count++) {
uint32_t current = *dn_queue_front_t (queue, uint32_t);
if (current != count)
return FAILED ("incorrect queue order");
dn_queue_pop (queue);
}
if (count != N_ELEMS)
return FAILED ("incorrect queue count");
dn_queue_clear (queue);
dn_queue_push (queue, &dispose_count);
dn_queue_push (queue, &dispose_count);
dn_queue_push (queue, &dispose_count);
dn_queue_custom_pop (queue, test_queue_dispose_func);
dn_queue_custom_pop (queue, test_queue_dispose_func);
if (dn_queue_size (queue) != 1)
return FAILED ("incorrect queue count after custom pop");
if (dispose_count != 2)
return FAILED ("incorrect dispose count after custom pop");
dn_queue_free (queue);
return OK;
}
static
RESULT
test_queue_clear (void)
{
uint32_t dispose_count = 0;
const char * items[] = { "first", "second" };
dn_queue_t *queue = dn_queue_alloc ();
if (!queue)
return FAILED ("failed to alloc queue");
if (!dn_queue_empty (queue))
return FAILED ("failed empty #1");
dn_queue_push (queue, (char *)items [0]);
if (dn_queue_empty (queue))
return FAILED ("failed empty #2");
dn_queue_push (queue, (char *)items [1]);
dn_queue_clear (queue);
if (!dn_queue_empty (queue))
return FAILED ("failed empty #3");
dn_queue_free (queue);
queue = dn_queue_custom_alloc (DN_DEFAULT_ALLOCATOR);
dn_queue_push (queue, &dispose_count);
dn_queue_push (queue, &dispose_count);
dn_queue_custom_clear (queue, test_queue_dispose_func);
if (dispose_count != 2)
return FAILED ("invalid dispose count on clear");
dispose_count = 0;
dn_queue_custom_free (queue, test_queue_dispose_func);
if (dispose_count != 0)
return FAILED ("invalid dispose count on clear/free");
return OK;
}
static
RESULT
test_queue_teardown (void)
{
#ifdef _CRTDBG_MAP_ALLOC
_CrtMemCheckpoint (&dn_queue_memory_end_snapshot);
if ( _CrtMemDifference(&dn_queue_memory_diff_snapshot, &dn_queue_memory_start_snapshot, &dn_queue_memory_end_snapshot) ) {
_CrtMemDumpStatistics( &dn_queue_memory_diff_snapshot );
return FAILED ("memory leak detected!");
}
#endif
return OK;
}
static Test dn_queue_tests [] = {
{"test_queue_setup", test_queue_setup},
{"test_queue_alloc", test_queue_alloc},
{"test_queue_init", test_queue_init},
{"test_queue_free", test_queue_free},
{"test_queue_dispose", test_queue_dispose},
{"test_queue_front", test_queue_front},
{"test_queue_back", test_queue_back},
{"test_queue_empty", test_queue_empty},
{"test_queue_size", test_queue_size},
{"test_queue_push_pop", test_queue_push_pop},
{"test_queue_clear", test_queue_clear},
{"test_queue_teardown", test_queue_teardown},
{NULL, NULL}
};
DEFINE_TEST_GROUP_INIT(dn_queue_tests_init, dn_queue_tests)
|
1b6ae41fa7006312c8e8827c0403abe6dc59d62b
|
340cc5d8ba77fbbafefb8a1755ae4dacbfb6953e
|
/src/nfpcapd/packet_bpf.c
|
e7c5182814c9518a6c4f395506983e3b62621ddd
|
[
"BSD-3-Clause"
] |
permissive
|
phaag/nfdump
|
1899c1b376c62040acdc994892949310cf85b32a
|
584453e6e3b4d6f23cf6c83cd2a7298cf0b5c44a
|
refs/heads/master
| 2023-08-31T06:53:13.565444
| 2023-08-20T12:22:46
| 2023-08-20T12:22:46
| 40,435,192
| 703
| 200
|
NOASSERTION
| 2023-08-20T18:40:33
| 2015-08-09T12:12:03
|
C
|
UTF-8
|
C
| false
| false
| 12,300
|
c
|
packet_bpf.c
|
/*
* Copyright (c) 2023, Peter Haag
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE 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.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef FIX_INCLUDE
#include <sys/types.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "packet_pcap.h"
#include "pcaproc.h"
#include "queue.h"
#include "util.h"
static void CloseSocket(packetParam_t *param);
static int setup_pcap_filter(packetParam_t *param, char *filter);
static void ReportStat(packetParam_t *param);
static inline void PcapDump(packetBuffer_t *packetBuffer, struct bpf_hdr *hdr, const u_char *sp);
static struct bpf_stat last_stat = {0};
static proc_stat_t proc_stat = {0};
/*
* Functions
*/
static int open_bpf(void) {
int fd = -1;
// Open bpf device
for (int i = 0; i < 255; i++) {
char dev[32];
(void)snprintf(dev, sizeof(dev), "/dev/bpf%u", i);
fd = open(dev, O_RDWR);
if (fd > -1) return fd;
switch (errno) {
case EBUSY:
break;
default:
return -1;
}
}
errno = ENOENT;
return -1;
} // End of open_bpf
static void CloseSocket(packetParam_t *param) {
close(param->bpf);
pcap_close(param->pcap_dev);
} // End of CloseSocket
// live device
int setup_bpf_live(packetParam_t *param, char *device, char *filter, int snaplen, int buffsize, int to_ms) {
param->pcap_dev = NULL;
param->bpf = 0;
int bpf = open_bpf();
if (bpf < 0) {
LogError("open_bpf() failed: %s", strerror(errno));
return -1;
}
unsigned int buf_len = param->bpfBufferSize;
if (ioctl(bpf, BIOCSBLEN, &buf_len) == -1) {
LogError("ioctl(BIOCSBLEN) failed: %s", strerror(errno));
close(bpf);
return -1;
}
dbg_printf("BIOCSBLEN requested: %zu, returned: %u\n", param->bpfBufferSize, buf_len);
if (buf_len && (buf_len < param->bpfBufferSize)) {
LogError("ioctl(BIOCSBLEN) buffer set to max: %u", buf_len);
param->bpfBufferSize = buf_len;
}
param->bpfBuffer = malloc(param->bpfBufferSize);
if (!param->bpfBuffer) {
LogError("malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno));
close(bpf);
return -1;
}
struct ifreq if_req;
strncpy(if_req.ifr_name, device, IFNAMSIZ - 1);
if (ioctl(bpf, BIOCSETIF, &if_req) > 0) {
LogError("ioctl(BIOCSETIF) failed: %s", strerror(errno));
close(bpf);
return -1;
}
unsigned int mode = 0;
if (ioctl(bpf, BIOCIMMEDIATE, &mode) == -1) {
LogError("ioctl(BIOCIMMEDIATE) failed: %s", strerror(errno));
close(bpf);
return -1;
}
if (ioctl(bpf, BIOCPROMISC, NULL) == -1) {
LogError("ioctl(BIOCPROMISC) failed: %s", strerror(errno));
close(bpf);
return -1;
}
uint32_t dlt = 0;
if (ioctl(bpf, BIOCGDLT, &dlt) < 0) {
LogError("ioctl(BIOCGDLT) failed: %s", strerror(errno));
close(bpf);
return -1;
}
switch (dlt) {
case DLT_RAW:
param->linktype = DLT_RAW;
break;
case DLT_EN10MB:
param->linktype = DLT_EN10MB;
break;
default:
LogError("Unsupported datalink type: %u", dlt);
errno = EINVAL;
close(bpf);
return -1;
}
// pcap handle for dumper
pcap_t *p = pcap_open_dead(DLT_EN10MB, 1 << 16);
param->pcap_dev = p;
param->bpf = bpf;
if (filter && !setup_pcap_filter(param, filter)) {
pcap_close(param->pcap_dev);
return -1;
}
return 0;
} /* setup_pcap_live */
static int setup_pcap_filter(packetParam_t *param, char *filter) {
struct bpf_program filter_code;
if (pcap_compile(param->pcap_dev, &filter_code, filter, 1, PCAP_NETMASK_UNKNOWN)) {
LogError("pcap_compile() failed: %s", pcap_geterr(param->pcap_dev));
return 0;
}
if (ioctl(param->bpf, BIOCSETF, (caddr_t)&filter_code) < 0) {
LogError("ioctl(BIOCSETF) failed: %s", strerror(errno));
return 0;
}
return 1;
} // End of setup_pcap_filter
static void ReportStat(packetParam_t *param) {
struct bpf_stat pstat;
memset((void *)&pstat, 0, sizeof(struct bpf_stat));
if (ioctl(param->bpf, BIOCGSTATS, &pstat) < 0) {
LogError("ioctl(BIOCGSTATS) failed: %s", strerror(errno));
} else {
last_stat = pstat;
}
LogInfo("Packets kernel received: %d, dropped by OS/Buffer: %d, processed: %u, skipped: %u, short caplen: %u, unknown: %u",
pstat.bs_recv - last_stat.bs_recv, pstat.bs_drop - last_stat.bs_drop, param->proc_stat.packets - proc_stat.packets,
param->proc_stat.skipped - proc_stat.skipped, param->proc_stat.short_snap - proc_stat.short_snap,
param->proc_stat.unknown - proc_stat.unknown);
proc_stat = param->proc_stat;
} // End of ReportStat
static inline void PcapDump(packetBuffer_t *packetBuffer, struct bpf_hdr *hdr, const u_char *sp) {
// caller checks for enough space in buffer
struct pcap_sf_pkthdr sf_hdr;
sf_hdr.ts.tv_sec = hdr->bh_tstamp.tv_sec;
sf_hdr.ts.tv_usec = hdr->bh_tstamp.tv_usec;
sf_hdr.caplen = hdr->bh_caplen;
sf_hdr.len = hdr->bh_datalen;
void *p = packetBuffer->buffer + packetBuffer->bufferSize;
memcpy(p, (void *)&sf_hdr, sizeof(sf_hdr));
p += sizeof(struct pcap_sf_pkthdr);
memcpy(p, (void *)sp, hdr->bh_caplen);
packetBuffer->bufferSize += (sizeof(struct pcap_sf_pkthdr) + hdr->bh_caplen);
dbg_printf("Buffer size: %zu\n", packetBuffer->bufferSize);
} // End of PcapDump
void __attribute__((noreturn)) * bpf_packet_thread(void *args) {
packetParam_t *packetParam = (packetParam_t *)args;
time_t t_win = packetParam->t_win;
time_t now = time(NULL);
time_t t_start = now - (now % t_win);
int done = *(packetParam->done);
int DoPacketDump = packetParam->bufferQueue != NULL;
packetBuffer_t *packetBuffer = NULL;
if (DoPacketDump) packetBuffer = queue_pop(packetParam->bufferQueue);
struct timeval timeout;
fd_set mask;
int width = packetParam->bpf + 1;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
while (!done) {
FD_ZERO(&mask);
FD_SET(packetParam->bpf, &mask);
dbg_printf("select() wait\n");
int ready = select(width, &mask, NULL, NULL, &timeout);
time_t t_packet = 0;
if (ready == -1) {
if (errno != EINTR) LogError("select() on bpf socket failed: %s", strerror(errno));
break;
} else if (ready == 0) {
dbg_printf("select() bpf - timeout\n");
struct timeval tv;
gettimeofday(&tv, NULL);
t_packet = tv.tv_sec;
if ((t_packet - t_start) >= t_win) { /* rotate file */
if (DoPacketDump) {
// Rotate dump file - close old - open new
packetBuffer->timeStamp = t_start;
queue_push(packetParam->flushQueue, packetBuffer);
packetBuffer = queue_pop(packetParam->bufferQueue);
}
// Rotate flow file
ReportStat(packetParam);
Push_SyncNode(packetParam->NodeList, t_start);
t_start = t_packet - (t_packet % t_win);
}
CacheCheck(packetParam->NodeList, t_start);
continue;
}
if (done) break;
ssize_t len = read(packetParam->bpf, packetParam->bpfBuffer, packetParam->bpfBufferSize);
if (len <= 0) { // error or eof
if (len < 0) { // error other than interrupted system call
LogError("read() bpf socket failed: %s", strerror(errno));
pthread_kill(packetParam->parent, SIGUSR1);
}
done = 1;
dbg_printf("read() bpf buffer: %s\n", strerror(errno));
break;
}
dbg_printf("read() bpf buffer, len: %zd\n", len);
void *p = packetParam->bpfBuffer;
while (p < (packetParam->bpfBuffer + len)) {
struct bpf_hdr *hdr = (struct bpf_hdr *)p;
dbg_printf("loop - next packet\n");
t_packet = hdr->bh_tstamp.tv_sec;
if ((t_packet - t_start) >= t_win) {
// Rote dump file - close old - open new
if (DoPacketDump) {
dbg_printf("packet_thread() flush file - buffer: %zu\n", packetBuffer->bufferSize);
// Rotate dump file - close old - open new
packetBuffer->timeStamp = t_start;
queue_push(packetParam->flushQueue, packetBuffer);
packetBuffer = queue_pop(packetParam->bufferQueue);
}
// Rotate flow file
ReportStat(packetParam);
Push_SyncNode(packetParam->NodeList, t_start);
t_start = t_packet - (t_packet % t_win);
}
size_t size = sizeof(struct pcap_sf_pkthdr) + hdr->bh_caplen;
u_char *data = (u_char *)(p + hdr->bh_hdrlen);
if (DoPacketDump) {
if ((packetBuffer->bufferSize + size) > BUFFSIZE) {
packetBuffer->timeStamp = 0;
dbg_printf("packet_thread() flush buffer - size %zu\n", packetBuffer->bufferSize);
queue_push(packetParam->flushQueue, packetBuffer);
packetBuffer = queue_pop(packetParam->bufferQueue);
}
PcapDump(packetBuffer, hdr, data);
}
struct pcap_pkthdr phdr;
phdr.ts.tv_sec = hdr->bh_tstamp.tv_sec;
phdr.ts.tv_usec = hdr->bh_tstamp.tv_usec;
phdr.caplen = hdr->bh_caplen;
phdr.len = hdr->bh_datalen;
ProcessPacket(packetParam, &phdr, data);
p += BPF_WORDALIGN(hdr->bh_hdrlen + hdr->bh_caplen);
}
done = done || *(packetParam->done);
}
// flush buffer
dbg_printf("Done capture loop - signal close\n");
if (DoPacketDump) {
packetBuffer->timeStamp = t_start;
queue_push(packetParam->flushQueue, packetBuffer);
queue_close(packetParam->flushQueue);
}
ReportStat(packetParam);
CloseSocket(packetParam);
packetParam->t_win = t_start;
// Tell parent we are gone
pthread_kill(packetParam->parent, SIGUSR1);
pthread_exit(NULL);
/* NOTREACHED */
} /* End of packet_thread */
|
22e109422719139204fd6fb151af9e452af82421
|
54a60696114ae0fc8233baf0111f3b0cf72be5b9
|
/inform6/Tests/Assistants/dumb-frotz/buffer.c
|
6aa48a191607854ad4dec2831de7b3e67ab59306
|
[
"Glulxe",
"Artistic-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
ganelson/inform
|
de89a3df0fa5b40660707a7c66853cf5b066b1c9
|
56be55c4879b133a37fcd55fcd2452868a881551
|
refs/heads/master
| 2023-09-01T01:08:43.133920
| 2023-08-31T23:06:22
| 2023-08-31T23:06:22
| 169,170,146
| 1,130
| 63
|
Artistic-2.0
| 2023-09-12T09:56:18
| 2019-02-05T00:18:15
|
C
|
UTF-8
|
C
| false
| false
| 2,035
|
c
|
buffer.c
|
/*
* buffer.c
*
* Text buffering and word wrapping
*
*/
#include "frotz.h"
extern void stream_char (zchar);
extern void stream_word (const zchar *);
extern void stream_new_line (void);
static zchar buffer[TEXT_BUFFER_SIZE];
static bufpos = 0;
static zchar prev_c = 0;
/*
* flush_buffer
*
* Copy the contents of the text buffer to the output streams.
*
*/
void flush_buffer (void)
{
static bool locked = FALSE;
/* Make sure we stop when flush_buffer is called from flush_buffer.
Note that this is difficult to avoid as we might print a newline
during flush_buffer, which might cause a newline interrupt, that
might execute any arbitrary opcode, which might flush the buffer. */
if (locked || bufpos == 0)
return;
/* Send the buffer to the output streams */
buffer[bufpos] = 0;
locked = TRUE; stream_word (buffer); locked = FALSE;
/* Reset the buffer */
bufpos = 0;
prev_c = 0;
}/* flush_buffer */
/*
* print_char
*
* High level output function.
*
*/
void print_char (zchar c)
{
static bool flag = FALSE;
if (message || ostream_memory || enable_buffering) {
if (!flag) {
/* Characters 0 and ZC_RETURN are special cases */
if (c == ZC_RETURN)
{ new_line (); return; }
if (c == 0)
return;
/* Flush the buffer before a whitespace or after a hyphen */
if (c == ' ' || c == ZC_INDENT || c == ZC_GAP || prev_c == '-' && c != '-')
flush_buffer ();
/* Set the flag if this is part one of a style or font change */
if (c == ZC_NEW_FONT || c == ZC_NEW_STYLE)
flag = TRUE;
/* Remember the current character code */
prev_c = c;
} else flag = FALSE;
/* Insert the character into the buffer */
buffer[bufpos++] = c;
if (bufpos == TEXT_BUFFER_SIZE)
runtime_error ("Text buffer overflow");
} else stream_char (c);
}/* print_char */
/*
* new_line
*
* High level newline function.
*
*/
void new_line (void)
{
flush_buffer (); stream_new_line ();
}/* new_line */
|
669b71cbfab5912eadce26c589f5599e5a3ac6fe
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/external/wpa_supplicant/src/eap_peer/eap_fast_pac.c
|
327fb8b8ea48f08a0ef88d34c025ae1d358fc347
|
[
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 21,260
|
c
|
eap_fast_pac.c
|
/*
* EAP peer method: EAP-FAST PAC file processing
* Copyright (c) 2004-2006, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "includes.h"
#include "common.h"
#include "eap_config.h"
#include "eap_i.h"
#include "eap_fast_pac.h"
/* TODO: encrypt PAC-Key in the PAC file */
/* Text data format */
static const char *pac_file_hdr = "wpa_supplicant EAP-FAST PAC file - version 1";
/*
* Binary data format
* 4-octet magic value: 6A E4 92 0C
* 2-octet version (big endian)
* <version specific data>
*
* version=0:
* Sequence of PAC entries:
* 2-octet PAC-Type (big endian)
* 32-octet PAC-Key
* 2-octet PAC-Opaque length (big endian)
* <variable len> PAC-Opaque data (length bytes)
* 2-octet PAC-Info length (big endian)
* <variable len> PAC-Info data (length bytes)
*/
#define EAP_FAST_PAC_BINARY_MAGIC 0x6ae4920c
#define EAP_FAST_PAC_BINARY_FORMAT_VERSION 0
/**
* eap_fast_free_pac - Free PAC data
* @pac: Pointer to the PAC entry
*
* Note that the PAC entry must not be in a list since this function does not
* remove the list links.
*/
void eap_fast_free_pac(struct eap_fast_pac *pac)
{
os_free(pac->pac_opaque);
os_free(pac->pac_info);
os_free(pac->a_id);
os_free(pac->i_id);
os_free(pac->a_id_info);
os_free(pac);
}
/**
* eap_fast_get_pac - Get a PAC entry based on A-ID
* @pac_root: Pointer to root of the PAC list
* @a_id: A-ID to search for
* @a_id_len: Length of A-ID
* @pac_type: PAC-Type to search for
* Returns: Pointer to the PAC entry, or %NULL if A-ID not found
*/
struct eap_fast_pac *eap_fast_get_pac(struct eap_fast_pac *pac_root, const u8 *a_id, size_t a_id_len, u16 pac_type)
{
struct eap_fast_pac *pac = pac_root;
while (pac) {
if (pac->pac_type == pac_type && pac->a_id_len == a_id_len && os_memcmp(pac->a_id, a_id, a_id_len) == 0) {
return pac;
}
pac = pac->next;
}
return NULL;
}
static void eap_fast_remove_pac(struct eap_fast_pac **pac_root, struct eap_fast_pac **pac_current, const u8 *a_id, size_t a_id_len, u16 pac_type)
{
struct eap_fast_pac *pac, *prev;
pac = *pac_root;
prev = NULL;
while (pac) {
if (pac->pac_type == pac_type && pac->a_id_len == a_id_len && os_memcmp(pac->a_id, a_id, a_id_len) == 0) {
if (prev == NULL) {
*pac_root = pac->next;
} else {
prev->next = pac->next;
}
if (*pac_current == pac) {
*pac_current = NULL;
}
eap_fast_free_pac(pac);
break;
}
prev = pac;
pac = pac->next;
}
}
static int eap_fast_copy_buf(u8 **dst, size_t *dst_len, const u8 *src, size_t src_len)
{
if (src) {
*dst = os_malloc(src_len);
if (*dst == NULL) {
return -1;
}
os_memcpy(*dst, src, src_len);
*dst_len = src_len;
}
return 0;
}
/**
* eap_fast_add_pac - Add a copy of a PAC entry to a list
* @pac_root: Pointer to PAC list root pointer
* @pac_current: Pointer to the current PAC pointer
* @entry: New entry to clone and add to the list
* Returns: 0 on success, -1 on failure
*
* This function makes a clone of the given PAC entry and adds this copied
* entry to the list (pac_root). If an old entry for the same A-ID is found,
* it will be removed from the PAC list and in this case, pac_current entry
* is set to %NULL if it was the removed entry.
*/
int eap_fast_add_pac(struct eap_fast_pac **pac_root, struct eap_fast_pac **pac_current, struct eap_fast_pac *entry)
{
struct eap_fast_pac *pac;
if (entry == NULL || entry->a_id == NULL) {
return -1;
}
/* Remove a possible old entry for the matching A-ID. */
eap_fast_remove_pac(pac_root, pac_current, entry->a_id, entry->a_id_len, entry->pac_type);
/* Allocate a new entry and add it to the list of PACs. */
pac = os_zalloc(sizeof(*pac));
if (pac == NULL) {
return -1;
}
pac->pac_type = entry->pac_type;
os_memcpy(pac->pac_key, entry->pac_key, EAP_FAST_PAC_KEY_LEN);
if (eap_fast_copy_buf(&pac->pac_opaque, &pac->pac_opaque_len, entry->pac_opaque, entry->pac_opaque_len) < 0 || eap_fast_copy_buf(&pac->pac_info, &pac->pac_info_len, entry->pac_info, entry->pac_info_len) < 0 || eap_fast_copy_buf(&pac->a_id, &pac->a_id_len, entry->a_id, entry->a_id_len) < 0 || eap_fast_copy_buf(&pac->i_id, &pac->i_id_len, entry->i_id, entry->i_id_len) < 0 || eap_fast_copy_buf(&pac->a_id_info, &pac->a_id_info_len, entry->a_id_info, entry->a_id_info_len) < 0) {
eap_fast_free_pac(pac);
return -1;
}
pac->next = *pac_root;
*pac_root = pac;
return 0;
}
struct eap_fast_read_ctx {
FILE *f;
const char *pos;
const char *end;
int line;
char *buf;
size_t buf_len;
};
static int eap_fast_read_line(struct eap_fast_read_ctx *rc, char **value)
{
char *pos;
rc->line++;
if (rc->f) {
if (fgets(rc->buf, rc->buf_len, rc->f) == NULL) {
return -1;
}
} else {
const char *l_end;
size_t len;
if (rc->pos >= rc->end) {
return -1;
}
l_end = rc->pos;
while (l_end < rc->end && *l_end != '\n') {
l_end++;
}
len = l_end - rc->pos;
if (len >= rc->buf_len) {
len = rc->buf_len - 1;
}
os_memcpy(rc->buf, rc->pos, len);
rc->buf[len] = '\0';
rc->pos = l_end + 1;
}
rc->buf[rc->buf_len - 1] = '\0';
pos = rc->buf;
while (*pos != '\0') {
if (*pos == '\n' || *pos == '\r') {
*pos = '\0';
break;
}
pos++;
}
pos = os_strchr(rc->buf, '=');
if (pos) {
*pos++ = '\0';
}
*value = pos;
return 0;
}
static u8 *eap_fast_parse_hex(const char *value, size_t *len)
{
int hlen;
u8 *buf;
if (value == NULL) {
return NULL;
}
hlen = os_strlen(value);
if (hlen & 1) {
return NULL;
}
*len = hlen / 2;
buf = os_malloc(*len);
if (buf == NULL) {
return NULL;
}
if (hexstr2bin(value, buf, *len)) {
os_free(buf);
return NULL;
}
return buf;
}
static int eap_fast_init_pac_data(struct eap_sm *sm, const char *pac_file, struct eap_fast_read_ctx *rc)
{
os_memset(rc, 0, sizeof(*rc));
rc->buf_len = 2048;
rc->buf = os_malloc(rc->buf_len);
if (rc->buf == NULL) {
return -1;
}
if (os_strncmp(pac_file, "blob://", 7) == 0) {
const struct wpa_config_blob *blob;
blob = eap_get_config_blob(sm, pac_file + 7);
if (blob == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC blob '%s' - " "assume no PAC entries have been " "provisioned", pac_file + 7);
os_free(rc->buf);
return -1;
}
rc->pos = (char *)blob->data;
rc->end = (char *)blob->data + blob->len;
} else {
rc->f = fopen(pac_file, "rb");
if (rc->f == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC file '%s' - " "assume no PAC entries have been " "provisioned", pac_file);
os_free(rc->buf);
return -1;
}
}
return 0;
}
static void eap_fast_deinit_pac_data(struct eap_fast_read_ctx *rc)
{
os_free(rc->buf);
if (rc->f) {
fclose(rc->f);
}
}
static const char *eap_fast_parse_start(struct eap_fast_pac **pac)
{
if (*pac) {
return "START line without END";
}
*pac = os_zalloc(sizeof(struct eap_fast_pac));
if (*pac == NULL) {
return "No memory for PAC entry";
}
(*pac)->pac_type = PAC_TYPE_TUNNEL_PAC;
return NULL;
}
static const char *eap_fast_parse_end(struct eap_fast_pac **pac_root, struct eap_fast_pac **pac)
{
if (*pac == NULL) {
return "END line without START";
}
if (*pac_root) {
struct eap_fast_pac *end = *pac_root;
while (end->next) {
end = end->next;
}
end->next = *pac;
} else {
*pac_root = *pac;
}
*pac = NULL;
return NULL;
}
static const char *eap_fast_parse_pac_type(struct eap_fast_pac *pac, char *pos)
{
if (!pos) {
return "Cannot parse pac type";
}
pac->pac_type = atoi(pos);
if (pac->pac_type != PAC_TYPE_TUNNEL_PAC && pac->pac_type != PAC_TYPE_USER_AUTHORIZATION && pac->pac_type != PAC_TYPE_MACHINE_AUTHENTICATION) {
return "Unrecognized PAC-Type";
}
return NULL;
}
static const char *eap_fast_parse_pac_key(struct eap_fast_pac *pac, char *pos)
{
u8 *key;
size_t key_len;
key = eap_fast_parse_hex(pos, &key_len);
if (key == NULL || key_len != EAP_FAST_PAC_KEY_LEN) {
os_free(key);
return "Invalid PAC-Key";
}
os_memcpy(pac->pac_key, key, EAP_FAST_PAC_KEY_LEN);
os_free(key);
return NULL;
}
static const char *eap_fast_parse_pac_opaque(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->pac_opaque);
pac->pac_opaque = eap_fast_parse_hex(pos, &pac->pac_opaque_len);
if (pac->pac_opaque == NULL) {
return "Invalid PAC-Opaque";
}
return NULL;
}
static const char *eap_fast_parse_a_id(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->a_id);
pac->a_id = eap_fast_parse_hex(pos, &pac->a_id_len);
if (pac->a_id == NULL) {
return "Invalid A-ID";
}
return NULL;
}
static const char *eap_fast_parse_i_id(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->i_id);
pac->i_id = eap_fast_parse_hex(pos, &pac->i_id_len);
if (pac->i_id == NULL) {
return "Invalid I-ID";
}
return NULL;
}
static const char *eap_fast_parse_a_id_info(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->a_id_info);
pac->a_id_info = eap_fast_parse_hex(pos, &pac->a_id_info_len);
if (pac->a_id_info == NULL) {
return "Invalid A-ID-Info";
}
return NULL;
}
/**
* eap_fast_load_pac - Load PAC entries (text format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Pointer to root of the PAC list (to be filled)
* @pac_file: Name of the PAC file/blob to load
* Returns: 0 on success, -1 on failure
*/
int eap_fast_load_pac(struct eap_sm *sm, struct eap_fast_pac **pac_root, const char *pac_file)
{
struct eap_fast_read_ctx rc;
struct eap_fast_pac *pac = NULL;
int count = 0;
char *pos;
const char *err = NULL;
if (pac_file == NULL) {
return -1;
}
if (eap_fast_init_pac_data(sm, pac_file, &rc) < 0) {
return 0;
}
if (eap_fast_read_line(&rc, &pos) < 0) {
/* empty file - assume it is fine to overwrite */
eap_fast_deinit_pac_data(&rc);
return 0;
}
if (os_strcmp(pac_file_hdr, rc.buf) != 0) {
err = "Unrecognized header line";
}
while (!err && eap_fast_read_line(&rc, &pos) == 0) {
if (os_strcmp(rc.buf, "START") == 0) {
err = eap_fast_parse_start(&pac);
} else if (os_strcmp(rc.buf, "END") == 0) {
err = eap_fast_parse_end(pac_root, &pac);
count++;
} else if (!pac) {
err = "Unexpected line outside START/END block";
} else if (os_strcmp(rc.buf, "PAC-Type") == 0) {
err = eap_fast_parse_pac_type(pac, pos);
} else if (os_strcmp(rc.buf, "PAC-Key") == 0) {
err = eap_fast_parse_pac_key(pac, pos);
} else if (os_strcmp(rc.buf, "PAC-Opaque") == 0) {
err = eap_fast_parse_pac_opaque(pac, pos);
} else if (os_strcmp(rc.buf, "A-ID") == 0) {
err = eap_fast_parse_a_id(pac, pos);
} else if (os_strcmp(rc.buf, "I-ID") == 0) {
err = eap_fast_parse_i_id(pac, pos);
} else if (os_strcmp(rc.buf, "A-ID-Info") == 0) {
err = eap_fast_parse_a_id_info(pac, pos);
}
}
if (pac) {
err = "PAC block not terminated with END";
eap_fast_free_pac(pac);
}
eap_fast_deinit_pac_data(&rc);
if (err) {
wpa_printf(MSG_INFO, "EAP-FAST: %s in '%s:%d'", err, pac_file, rc.line);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Read %d PAC entries from '%s'", count, pac_file);
return 0;
}
static void eap_fast_write(char **buf, char **pos, size_t *buf_len, const char *field, const u8 *data, size_t len, int txt)
{
size_t i, need;
int ret;
char *end;
if (data == NULL || buf == NULL || *buf == NULL || pos == NULL || *pos == NULL || *pos < *buf) {
return;
}
need = os_strlen(field) + len * 2 + 30;
if (txt) {
need += os_strlen(field) + len + 20;
}
if (*pos - *buf + need > *buf_len) {
char *nbuf = os_realloc(*buf, *buf_len + need);
if (nbuf == NULL) {
os_free(*buf);
*buf = NULL;
return;
}
*pos = nbuf + (*pos - *buf);
*buf = nbuf;
*buf_len += need;
}
end = *buf + *buf_len;
ret = os_snprintf(*pos, end - *pos, "%s=", field);
if (os_snprintf_error(end - *pos, ret)) {
return;
}
*pos += ret;
*pos += wpa_snprintf_hex(*pos, end - *pos, data, len);
ret = os_snprintf(*pos, end - *pos, "\n");
if (os_snprintf_error(end - *pos, ret)) {
return;
}
*pos += ret;
if (txt) {
ret = os_snprintf(*pos, end - *pos, "%s-txt=", field);
if (os_snprintf_error(end - *pos, ret)) {
return;
}
*pos += ret;
for (i = 0; i < len; i++) {
ret = os_snprintf(*pos, end - *pos, "%c", data[i]);
if (os_snprintf_error(end - *pos, ret)) {
return;
}
*pos += ret;
}
ret = os_snprintf(*pos, end - *pos, "\n");
if (os_snprintf_error(end - *pos, ret)) {
return;
}
*pos += ret;
}
}
static int eap_fast_write_pac(struct eap_sm *sm, const char *pac_file, char *buf, size_t len)
{
if (os_strncmp(pac_file, "blob://", 7) == 0) {
struct wpa_config_blob *blob;
blob = os_zalloc(sizeof(*blob));
if (blob == NULL) {
return -1;
}
blob->data = (u8 *)buf;
blob->len = len;
buf = NULL;
blob->name = os_strdup(pac_file + 7);
if (blob->name == NULL) {
os_free(blob);
return -1;
}
eap_set_config_blob(sm, blob);
} else {
FILE *f;
f = fopen(pac_file, "wb");
if (f == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: Failed to open PAC " "file '%s' for writing", pac_file);
return -1;
}
if (fwrite(buf, 1, len, f) != len) {
wpa_printf(MSG_INFO, "EAP-FAST: Failed to write all " "PACs into '%s'", pac_file);
fclose(f);
return -1;
}
os_free(buf);
fclose(f);
}
return 0;
}
static int eap_fast_add_pac_data(struct eap_fast_pac *pac, char **buf, char **pos, size_t *buf_len)
{
int ret;
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "START\nPAC-Type=%d\n", pac->pac_type);
if (os_snprintf_error(*buf + *buf_len - *pos, ret)) {
return -1;
}
*pos += ret;
eap_fast_write(buf, pos, buf_len, "PAC-Key", pac->pac_key, EAP_FAST_PAC_KEY_LEN, 0);
eap_fast_write(buf, pos, buf_len, "PAC-Opaque", pac->pac_opaque, pac->pac_opaque_len, 0);
eap_fast_write(buf, pos, buf_len, "PAC-Info", pac->pac_info, pac->pac_info_len, 0);
eap_fast_write(buf, pos, buf_len, "A-ID", pac->a_id, pac->a_id_len, 0);
eap_fast_write(buf, pos, buf_len, "I-ID", pac->i_id, pac->i_id_len, 1);
eap_fast_write(buf, pos, buf_len, "A-ID-Info", pac->a_id_info, pac->a_id_info_len, 1);
if (*buf == NULL) {
wpa_printf(MSG_DEBUG, "EAP-FAST: No memory for PAC " "data");
return -1;
}
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "END\n");
if (os_snprintf_error(*buf + *buf_len - *pos, ret)) {
return -1;
}
*pos += ret;
return 0;
}
/**
* eap_fast_save_pac - Save PAC entries (text format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Root of the PAC list
* @pac_file: Name of the PAC file/blob
* Returns: 0 on success, -1 on failure
*/
int eap_fast_save_pac(struct eap_sm *sm, struct eap_fast_pac *pac_root, const char *pac_file)
{
struct eap_fast_pac *pac;
int ret, count = 0;
char *buf, *pos;
size_t buf_len;
if (pac_file == NULL) {
return -1;
}
buf_len = 1024;
pos = buf = os_malloc(buf_len);
if (buf == NULL) {
return -1;
}
ret = os_snprintf(pos, buf + buf_len - pos, "%s\n", pac_file_hdr);
if (os_snprintf_error(buf + buf_len - pos, ret)) {
os_free(buf);
return -1;
}
pos += ret;
pac = pac_root;
while (pac) {
if (eap_fast_add_pac_data(pac, &buf, &pos, &buf_len)) {
os_free(buf);
return -1;
}
count++;
pac = pac->next;
}
if (eap_fast_write_pac(sm, pac_file, buf, pos - buf)) {
os_free(buf);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Wrote %d PAC entries into '%s'", count, pac_file);
return 0;
}
/**
* eap_fast_pac_list_truncate - Truncate a PAC list to the given length
* @pac_root: Root of the PAC list
* @max_len: Maximum length of the list (>= 1)
* Returns: Number of PAC entries removed
*/
size_t eap_fast_pac_list_truncate(struct eap_fast_pac *pac_root, size_t max_len)
{
struct eap_fast_pac *pac, *prev;
size_t count;
pac = pac_root;
prev = NULL;
count = 0;
while (pac) {
count++;
if (count > max_len) {
break;
}
prev = pac;
pac = pac->next;
}
if (count <= max_len || prev == NULL) {
return 0;
}
count = 0;
prev->next = NULL;
while (pac) {
prev = pac;
pac = pac->next;
eap_fast_free_pac(prev);
count++;
}
return count;
}
static void eap_fast_pac_get_a_id(struct eap_fast_pac *pac)
{
u8 *pos, *end;
u16 type, len;
pos = pac->pac_info;
end = pos + pac->pac_info_len;
while (pos + 4 < end) {
type = WPA_GET_BE16(pos);
pos += 2;
len = WPA_GET_BE16(pos);
pos += 2;
if (len > (unsigned int)(end - pos)) {
break;
}
if (type == PAC_TYPE_A_ID) {
os_free(pac->a_id);
pac->a_id = os_malloc(len);
if (pac->a_id == NULL) {
break;
}
os_memcpy(pac->a_id, pos, len);
pac->a_id_len = len;
}
if (type == PAC_TYPE_A_ID_INFO) {
os_free(pac->a_id_info);
pac->a_id_info = os_malloc(len);
if (pac->a_id_info == NULL) {
break;
}
os_memcpy(pac->a_id_info, pos, len);
pac->a_id_info_len = len;
}
pos += len;
}
}
/**
* eap_fast_load_pac_bin - Load PAC entries (binary format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Pointer to root of the PAC list (to be filled)
* @pac_file: Name of the PAC file/blob to load
* Returns: 0 on success, -1 on failure
*/
int eap_fast_load_pac_bin(struct eap_sm *sm, struct eap_fast_pac **pac_root, const char *pac_file)
{
const struct wpa_config_blob *blob = NULL;
u8 *buf, *end, *pos;
size_t len, count = 0;
struct eap_fast_pac *pac, *prev;
*pac_root = NULL;
if (pac_file == NULL) {
return -1;
}
if (os_strncmp(pac_file, "blob://", 7) == 0) {
blob = eap_get_config_blob(sm, pac_file + 7);
if (blob == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC blob '%s' - " "assume no PAC entries have been " "provisioned", pac_file + 7);
return 0;
}
buf = blob->data;
len = blob->len;
} else {
buf = (u8 *)os_readfile(pac_file, &len);
if (buf == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC file '%s' - " "assume no PAC entries have been " "provisioned", pac_file);
return 0;
}
}
if (len == 0) {
if (blob == NULL) {
os_free(buf);
}
return 0;
}
if (len < 6 || WPA_GET_BE32(buf) != EAP_FAST_PAC_BINARY_MAGIC || WPA_GET_BE16(buf + 4) != EAP_FAST_PAC_BINARY_FORMAT_VERSION) {
wpa_printf(MSG_INFO, "EAP-FAST: Invalid PAC file '%s' (bin)", pac_file);
if (blob == NULL) {
os_free(buf);
}
return -1;
}
pac = prev = NULL;
pos = buf + 6;
end = buf + len;
while (pos < end) {
u16 val;
if (end - pos < 2 + EAP_FAST_PAC_KEY_LEN + 2 + 2) {
goto parse_fail;
}
pac = os_zalloc(sizeof(*pac));
if (pac == NULL) {
goto parse_fail;
}
pac->pac_type = WPA_GET_BE16(pos);
pos += 2;
os_memcpy(pac->pac_key, pos, EAP_FAST_PAC_KEY_LEN);
pos += EAP_FAST_PAC_KEY_LEN;
val = WPA_GET_BE16(pos);
pos += 2;
if (val > end - pos) {
goto parse_fail;
}
pac->pac_opaque_len = val;
pac->pac_opaque = os_malloc(pac->pac_opaque_len);
if (pac->pac_opaque == NULL) {
goto parse_fail;
}
os_memcpy(pac->pac_opaque, pos, pac->pac_opaque_len);
pos += pac->pac_opaque_len;
if (2 > end - pos) {
goto parse_fail;
}
val = WPA_GET_BE16(pos);
pos += 2;
if (val > end - pos) {
goto parse_fail;
}
pac->pac_info_len = val;
pac->pac_info = os_malloc(pac->pac_info_len);
if (pac->pac_info == NULL) {
goto parse_fail;
}
os_memcpy(pac->pac_info, pos, pac->pac_info_len);
pos += pac->pac_info_len;
eap_fast_pac_get_a_id(pac);
count++;
if (prev) {
prev->next = pac;
} else {
*pac_root = pac;
}
prev = pac;
}
if (blob == NULL) {
os_free(buf);
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Read %lu PAC entries from '%s' (bin)", (unsigned long)count, pac_file);
return 0;
parse_fail:
wpa_printf(MSG_INFO, "EAP-FAST: Failed to parse PAC file '%s' (bin)", pac_file);
if (blob == NULL) {
os_free(buf);
}
if (pac) {
eap_fast_free_pac(pac);
}
return -1;
}
/**
* eap_fast_save_pac_bin - Save PAC entries (binary format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Root of the PAC list
* @pac_file: Name of the PAC file/blob
* Returns: 0 on success, -1 on failure
*/
int eap_fast_save_pac_bin(struct eap_sm *sm, struct eap_fast_pac *pac_root, const char *pac_file)
{
size_t len, count = 0;
struct eap_fast_pac *pac;
u8 *buf, *pos;
len = 6;
pac = pac_root;
while (pac) {
if (pac->pac_opaque_len > 65535 || pac->pac_info_len > 65535) {
return -1;
}
len += 2 + EAP_FAST_PAC_KEY_LEN + 2 + pac->pac_opaque_len + 2 + pac->pac_info_len;
pac = pac->next;
}
buf = os_malloc(len);
if (buf == NULL) {
return -1;
}
pos = buf;
WPA_PUT_BE32(pos, EAP_FAST_PAC_BINARY_MAGIC);
pos += 4;
WPA_PUT_BE16(pos, EAP_FAST_PAC_BINARY_FORMAT_VERSION);
pos += 2;
pac = pac_root;
while (pac) {
WPA_PUT_BE16(pos, pac->pac_type);
pos += 2;
os_memcpy(pos, pac->pac_key, EAP_FAST_PAC_KEY_LEN);
pos += EAP_FAST_PAC_KEY_LEN;
WPA_PUT_BE16(pos, pac->pac_opaque_len);
pos += 2;
os_memcpy(pos, pac->pac_opaque, pac->pac_opaque_len);
pos += pac->pac_opaque_len;
WPA_PUT_BE16(pos, pac->pac_info_len);
pos += 2;
os_memcpy(pos, pac->pac_info, pac->pac_info_len);
pos += pac->pac_info_len;
pac = pac->next;
count++;
}
if (eap_fast_write_pac(sm, pac_file, (char *)buf, len)) {
os_free(buf);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Wrote %lu PAC entries into '%s' " "(bin)", (unsigned long)count, pac_file);
return 0;
}
|
f18169d160f1980e958607639d57a04cb02931c6
|
94096248c1de2dcf46e69ca913cedfa290e44224
|
/tests/api/test-random.c
|
893f2b65744a7eee8a4d75a1863e5d40a1df0b4f
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
svaarala/duktape
|
612110d1a6db46226c171cfd222974b1b3651ad5
|
5e169deafbbd12823665f5d30fb4c4c04e3dfa26
|
refs/heads/master
| 2023-08-06T16:43:33.014729
| 2022-11-17T21:02:08
| 2022-11-17T21:02:08
| 15,852,088
| 4,796
| 610
|
MIT
| 2023-09-11T17:13:01
| 2014-01-12T22:16:14
|
JavaScript
|
UTF-8
|
C
| false
| false
| 626
|
c
|
test-random.c
|
/*
* duk_random()
*/
/*===
average is sane: 1
done
===*/
void test(duk_context *ctx) {
long i;
double d;
double sum = 0.0;
double count = 0.0;
double avg;
for (i = 0; i < 1000000L; i++) {
d = (double) duk_random(ctx);
if (!(d >= 0.0 && d < 1.0)) {
printf("failed: %lf\n", d);
}
sum += d;
count += 1.0;
}
avg = sum / count;
/* The range here is much larger than actually expected, and here
* just to catch cases where duk_random() would consistently return
* e.g. 0.0 or some other fixed value.
*/
printf("average is sane: %d\n", (avg >= 0.45 && avg <= 0.55) ? 1 : 0);
printf("done\n");
}
|
b6474382ce4b83e12692be8ab9f6c2ba620302e3
|
d61b532db0d3e08818338cfaac530a1ced1ffe3b
|
/lang/cem/libcc/stdio/flushbuf.c
|
d5d5188d3ca8aac89e57cd5cc67b411b67026baf
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
davidgiven/ack
|
61049c7a8e95ff61a77b1edd3c22bb290720e276
|
db5a32c68c4a60ca26a3927a799ea662b5b2b0e5
|
refs/heads/default
| 2023-08-29T07:33:12.771205
| 2023-07-08T20:17:27
| 2023-07-08T20:17:27
| 37,686,316
| 376
| 74
|
NOASSERTION
| 2023-07-08T20:17:28
| 2015-06-18T21:33:42
|
C
|
UTF-8
|
C
| false
| false
| 1,129
|
c
|
flushbuf.c
|
/* $Id$ */
#include <stdio.h>
int
_flushbuf(c, iop)
register FILE *iop;
{
if (fileno(iop) < 0) return EOF;
if (! io_testflag(iop, IO_UNBUFF)) {
if (iop->_buf == 0) {
if (iop == stdout && isatty(fileno(stdout))) {
iop->_flags |= IO_UNBUFF;
}
else {
extern char *malloc();
if (!(iop->_buf = (unsigned char *) malloc(_BUFSIZ))) {
iop->_flags |= IO_UNBUFF;
}
else {
iop->_flags |= IO_MYBUF;
iop->_bufsiz = _BUFSIZ;
iop->_count = _BUFSIZ-1;
}
}
iop->_ptr = iop->_buf;
}
}
if (io_testflag(iop, IO_UNBUFF)) {
char c1 = c;
iop->_count = 0;
if (write(fileno(iop), &c1, 1) != 1) {
iop->_flags |= IO_ERR;
return EOF;
}
return c;
}
else {
int count = iop->_ptr - iop->_buf;
iop->_count = iop->_bufsiz - 1;
iop->_ptr = iop->_buf + 1;
if (count > 0) {
if (write(fileno(iop), iop->_buf, count) != count) {
*(iop->_buf) = c;
iop->_flags |= IO_ERR;
return EOF;
}
}
*(iop->_buf) = c;
}
return c;
}
_cleanup()
{
register int i;
for ( i = 0 ; i < _NFILES ; i++ )
if ( _io_table[i] != NULL )
fclose(_io_table[i]);
}
|
89a6e14937d0d2f2afa80159520aadbba277bd84
|
34cfb15a219a735d58fcaadfb71ef1606a9114dc
|
/ext/deps/libcat/include/cat_watchdog.h
|
6bf2759e5a944b433124a899a5effd0c85e02bf7
|
[
"Apache-2.0",
"ISC",
"BSL-1.0",
"MIT",
"BSD-2-Clause"
] |
permissive
|
swow/swow
|
e32007f3cf1c8daf4accd7d64f9b2b728f5ab103
|
231f580dd1ee84d0364f314387073c5bda9854d2
|
refs/heads/develop
| 2023-08-19T13:51:39.840737
| 2023-08-05T01:51:04
| 2023-08-05T03:13:03
| 295,651,066
| 1,085
| 117
|
Apache-2.0
| 2023-06-15T09:18:12
| 2020-09-15T07:37:43
|
C
|
UTF-8
|
C
| false
| false
| 3,414
|
h
|
cat_watchdog.h
|
/*
+--------------------------------------------------------------------------+
| libcat |
+--------------------------------------------------------------------------+
| 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. See accompanying LICENSE file. |
+--------------------------------------------------------------------------+
| Author: Twosee <twosee@php.net> |
+--------------------------------------------------------------------------+
*/
#ifndef CAT_WATCH_DOG_H
#define CAT_WATCH_DOG_H
#ifdef __cplusplus
extern "C" {
#endif
#include "cat.h"
#include "cat_coroutine.h"
#include "cat_atomic.h"
#define CAT_WATCH_DOG_DEFAULT_QUANTUM (5 * 1000 * 1000)
#define CAT_WATCH_DOG_DEFAULT_THRESHOLD (10 * 1000 * 1000)
#define CAT_WATCH_DOG_THRESHOLD_DISABLED -1
#ifndef CAT_THREAD_SAFE
#define CAT_WATCH_DOG_ROLE_NAME "process"
#else
#define CAT_WATCH_DOG_ROLE_NAME "thread"
#endif
#define CAT_ALERT_COUNT_FMT "%" PRIu64
#define CAT_ALERT_COUNT_FMT_SPEC PRIu64
typedef uint64_t cat_alert_count_t;
typedef struct cat_watchdog_s cat_watchdog_t;
typedef void (*cat_watchdog_alerter_t)(cat_watchdog_t *watchdog);
CAT_GLOBALS_STRUCT_BEGIN(cat_watchdog) {
cat_watchdog_t *watchdog;
} CAT_GLOBALS_STRUCT_END(cat_watchdog);
extern CAT_API CAT_GLOBALS_DECLARE(cat_watchdog);
#define CAT_WATCH_DOG_G(x) CAT_GLOBALS_GET(cat_watchdog, x)
struct cat_watchdog_s
{
/* public (options, readonly) */
/* alert if blocking time is greater than quantum (nano secondes) */
cat_timeout_t quantum;
/* do something if blocking time is greater than threshold (nano secondes) */
cat_timeout_t threshold;
cat_watchdog_alerter_t alerter;
/* private */
cat_alert_count_t alert_count;
cat_bool_t allocated;
cat_atomic_bool_t stop;
uv_pid_t pid; /* TODO: cat_pid_t */
CAT_GLOBALS_TYPE(cat_coroutine) *globals;
cat_coroutine_switches_t last_switches;
uv_thread_t thread;
uv_sem_t *sem;
uv_cond_t cond;
uv_mutex_t mutex;
};
CAT_API cat_bool_t cat_watchdog_module_init(void);
CAT_API cat_bool_t cat_watchdog_module_shutdown(void);
CAT_API cat_bool_t cat_watchdog_runtime_init(void);
CAT_API cat_bool_t cat_watchdog_runtime_shutdown(void);
CAT_API cat_bool_t cat_watchdog_run(cat_watchdog_t *watchdog, cat_timeout_t quantum, cat_timeout_t threshold, cat_watchdog_alerter_t alerter);
CAT_API cat_bool_t cat_watchdog_stop(void);
CAT_API void cat_watchdog_alert_standard(cat_watchdog_t *watchdog);
CAT_API cat_bool_t cat_watchdog_is_running(void);
CAT_API cat_timeout_t cat_watchdog_get_quantum(void);
CAT_API cat_timeout_t cat_watchdog_get_threshold(void);
#ifdef __cplusplus
}
#endif
#endif /* CAT_WATCH_DOG_H */
|
5c6b7b2d224bd7649e95fc9505e3fcab72840513
|
065e86c9923692fe68f45c3de1888a29eb609f42
|
/test/tests_sha2.c
|
ac5746f5fd16f3b5ab71963bc9c7e54976b3c4de
|
[
"BSD-3-Clause",
"Apache-2.0",
"ISC",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL",
"MIT"
] |
permissive
|
intel/QAT_Engine
|
000a099a37d38ad174faea4b84ac54f8afef8800
|
a5a0bfe2c7cdb1aa8f6168e8ad7f25423359650d
|
refs/heads/master
| 2023-09-01T12:27:11.668274
| 2023-08-22T14:12:53
| 2023-08-23T09:02:17
| 48,074,518
| 302
| 123
|
BSD-3-Clause
| 2023-08-23T09:02:18
| 2015-12-15T23:15:52
|
C
|
UTF-8
|
C
| false
| false
| 8,845
|
c
|
tests_sha2.c
|
/***************************************************************************
*
* BSD LICENSE
*
* Copyright(c) 2023 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <openssl/async.h>
#include <openssl/objects.h>
#include <openssl/engine.h>
#include "tests.h"
#include "../qat_utils.h"
#define SHA2_224_DIGEST_LENGTH 28
#define SHA2_256_DIGEST_LENGTH 32
#define SHA2_384_DIGEST_LENGTH 48
#define SHA2_512_DIGEST_LENGTH 64
unsigned char sha2_224_expected[] = {
0x27, 0x1E, 0x41, 0xDB, 0x21, 0x89, 0xDC, 0x9D,
0xB9, 0x4E, 0x7A, 0x56, 0x41, 0xDB, 0xF6, 0x78,
0x9D, 0xB6, 0x61, 0xDA, 0xDC, 0x24, 0x86, 0xEA,
0xEF, 0xB5, 0xFF, 0xD6,
};
unsigned char sha2_256_expected[] = {
0xC6, 0x22, 0x00, 0x54, 0x93, 0xC4, 0xCB, 0x75,
0xF3, 0xE0, 0x8E, 0xDA, 0x4C, 0xC0, 0xBF, 0xE1,
0x72, 0xE2, 0xC5, 0xEE, 0xCA, 0x66, 0x1E, 0xC4,
0x90, 0x8C, 0x54, 0x90, 0xFC, 0x3D, 0x69, 0x94,
};
unsigned char sha2_384_expected[] = {
0x49, 0x13, 0x44, 0x2B, 0x8D, 0x4C, 0xA7, 0x39,
0x98, 0x22, 0x98, 0x03, 0xFB, 0x3E, 0xEE, 0x49,
0x55, 0x5C, 0x16, 0x62, 0x38, 0x44, 0x54, 0x9D,
0xA5, 0x4E, 0x2C, 0xA3, 0x00, 0x63, 0xE3, 0x70,
0x00, 0xBB, 0x66, 0x38, 0xED, 0x89, 0x59, 0xFA,
0xC9, 0x90, 0xD6, 0x35, 0xC9, 0xB8, 0x42, 0x28,
};
unsigned char sha2_512_expected[] = {
0x87, 0x73, 0xF7, 0xF1, 0x90, 0x99, 0x33, 0xF5,
0x96, 0x6C, 0xAE, 0xC1, 0x8F, 0x5B, 0xB1, 0x20,
0x09, 0x22, 0x81, 0xC0, 0xCC, 0x47, 0x33, 0x44,
0xA0, 0x82, 0x21, 0xAF, 0x3A, 0x0D, 0x5E, 0xE3,
0xD6, 0x3F, 0xFD, 0xBD, 0xEA, 0x86, 0xB9, 0xE4,
0x25, 0x58, 0x3F, 0xFA, 0x7B, 0x11, 0x8A, 0xEE,
0xED, 0x90, 0x65, 0x14, 0x35, 0x46, 0xCA, 0xD0,
0x08, 0xA9, 0x3D, 0x3E, 0x7F, 0x03, 0x18, 0xB2,
};
/******************************************************************************
* function:
* run_sha2(void *args)
*
* @param args [IN] - the test parameters
*
* Description: Runs SHA-2 tests for corresponding digest length
******************************************************************************/
static int run_sha2(void *args)
{
TEST_PARAMS *temp_args = (TEST_PARAMS *) args;
int count = *(temp_args->count);
int size = temp_args->size;
/* If temp_args->explicit_engine is not set then set the
engine to NULL to allow fallback to software if
that engine under test does not support this operation.
This relies on the engine we are testing being
set as the default engine. */
ENGINE *e = temp_args->explicit_engine ? temp_args->e : NULL;
int print_output = temp_args->print_output;
int verify = temp_args->verify;
int i = 0;
int inLen = size;
int ret = 1;
unsigned int digest_len = 0;
unsigned char md[SHA2_512_DIGEST_LENGTH];
unsigned char *expected = NULL;
/* Use default input size in verify mode. */
if (verify)
inLen = 4096;
unsigned char *inData = OPENSSL_malloc(inLen);
if (inData == NULL) {
fprintf(stderr, "# FAIL: [%s] --- inData malloc failed! \n", __func__);
exit(EXIT_FAILURE);
}
/* Setup the input and output data. */
memset(inData, 0xaa, inLen);
memset(md, 0x00, SHA2_512_DIGEST_LENGTH);
for (i = 0; i < count; i++) {
switch (temp_args->type) {
case TEST_SHA2_224:
DEBUG("\n----- SHA2_224 digest ----- \n\n");
digest_len = SHA2_224_DIGEST_LENGTH;
expected = (void *)&sha2_224_expected;
ret = EVP_Digest(inData, /* Input data pointer. */
inLen, /* Input data length. */
md, /* Output hash pointer. */
NULL, EVP_sha224(), /* Hash algorithm indicator. */
e); /* Engine indicator. */
break;
case TEST_SHA2_256:
DEBUG("\n----- SHA2_256 digest ----- \n\n");
digest_len = SHA2_256_DIGEST_LENGTH;
expected = (void *)&sha2_256_expected;
ret = EVP_Digest(inData, /* Input data pointer. */
inLen, /* Input data length. */
md, /* Output hash pointer. */
NULL, EVP_sha256(), /* Hash algorithm indicator. */
e); /* Engine indicator. */
break;
case TEST_SHA2_384:
DEBUG("\n----- SHA2_384 digest ----- \n\n");
digest_len = SHA2_384_DIGEST_LENGTH;
expected = (void *)&sha2_384_expected;
ret = EVP_Digest(inData, /* Input data pointer. */
inLen, /* Input data length. */
md, /* Output hash pointer. */
NULL, EVP_sha384(), /* Hash algorithm indicator. */
e); /* Engine indicator. */
break;
case TEST_SHA2_512:
DEBUG("\n----- SHA2_512 digest ----- \n\n");
digest_len = SHA2_512_DIGEST_LENGTH;
expected = (void *)&sha2_512_expected;
ret = EVP_Digest(inData, /* Input data pointer. */
inLen, /* Input data length. */
md, /* Output hash pointer. */
NULL, EVP_sha512(), /* Hash algorithm indicator. */
e); /* Engine indicator. */
break;
}
if (ret != 1 || verify) {
/* Compare the digest results with the expected results. */
if (memcmp(md, expected, digest_len)) {
fprintf(stderr, "# FAIL verify for %s.\n",
test_name(temp_args->type));
tests_hexdump("SHA2 actual :", md, digest_len);
tests_hexdump("SHA2 expected:", expected, digest_len);
ret = 0;
break;
} else {
fprintf(stderr, "# PASS verify for %s.\n",
test_name(temp_args->type));
}
}
} /* count for-loop */
if (print_output)
tests_hexdump("SHA2 digest text:", md, digest_len);
if (inData)
OPENSSL_free(inData);
return ret;
}
/******************************************************************************
* function:
* tests_run_sha2(TEST_PARAMS *args)
*
* @param args [IN] - the test parameters
*
* Description:
* This function is designed to test the QAT engine with variable message sizes
* using the SHA2 algorithm. The higher level EVP interface function EVP_Digest()
* is used inside of test application.
* This is a boundary test, the application should return the expected digest hash value.
* In verify mode a input size of 1024 bytes is used to generate a comparison digest.
******************************************************************************/
void tests_run_sha2(TEST_PARAMS *args)
{
args->additional_args = NULL;
if (!args->enable_async)
run_sha2(args);
else
start_async_job(args, run_sha2);
}
|
d485035042e8dcfd323ffaa24681137c20f13c53
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/ffmpeg/libavformat/h261dec.c
|
0fca1a340ad9916ef15fe5f2ea2926204bfefebf
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"IJG",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only",
"BSD-2-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 2,173
|
c
|
h261dec.c
|
/*
* RAW H.261 video demuxer
* Copyright (c) 2009 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/intreadwrite.h"
#include "avformat.h"
#include "rawdec.h"
static int h261_probe(const AVProbeData *p)
{
int i;
int valid_psc=0;
int invalid_psc=0;
int next_gn=0;
int src_fmt=0;
for(i=0; i<p->buf_size; i++){
if ((AV_RB16(&p->buf[i]) - 1) < 0xFFU) {
int shift = av_log2_16bit(p->buf[i+1]);
uint32_t code = AV_RB64(&p->buf[FFMAX(i-1, 0)]) >> (24+shift);
if ((code & 0xffff0000) == 0x10000) {
int gn= (code>>12)&0xf;
if(!gn)
src_fmt= code&8;
if(gn != next_gn) invalid_psc++;
else valid_psc++;
if(src_fmt){ // CIF
static const int lut[16]={1,2,3,4,5,6,7,8,9,10,11,12,0,16,16,16};
next_gn = lut[gn];
}else{ //QCIF
static const int lut[16]={1,3,16,5,16,0,16,16,16,16,16,16,16,16,16,16};
next_gn = lut[gn];
}
}
}
}
if(valid_psc > 2*invalid_psc + 6){
return AVPROBE_SCORE_EXTENSION;
}else if(valid_psc > 2*invalid_psc + 2)
return AVPROBE_SCORE_EXTENSION / 2;
return 0;
}
FF_DEF_RAWVIDEO_DEMUXER(h261, "raw H.261", h261_probe, "h261", AV_CODEC_ID_H261)
|
1bc442609122057cb3cd173e7af86d363e5bd899
|
1efb2283837c9b70bc6449cec877799e4efa3268
|
/test/mpi/rma/rget_testall.c
|
a7a2d6e4332ad3ae3834f508b0475cdbb666c304
|
[
"mpich2"
] |
permissive
|
pmodels/mpich
|
d2392e8e30536cad3e500c16aa1e71211101d83f
|
2d265f9f5f93ebdd07ad547423bc6212868262a4
|
refs/heads/main
| 2023-09-04T05:50:15.041823
| 2023-09-01T23:07:33
| 2023-09-01T23:07:33
| 70,918,679
| 506
| 313
|
NOASSERTION
| 2023-09-14T14:38:36
| 2016-10-14T14:39:42
|
C
|
UTF-8
|
C
| false
| false
| 2,095
|
c
|
rget_testall.c
|
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include <stdio.h>
#include <mpi.h>
#include "mpitest.h"
/* This test checks request-based get with MPI_Testall. Both the return value of
* MPI_Testall and status.MPI_ERROR should be correctly set.
*
* Thanks for Joseph Schuchart reporting this bug in MPICH and contributing
* the prototype of this test program. */
int main(int argc, char **argv)
{
int rank, size;
MPI_Win win = MPI_WIN_NULL;
int *baseptr = NULL;
int errs = 0, mpi_errno = MPI_SUCCESS;
int val1 = 0, val2 = 0, flag = 0;
MPI_Request reqs[2];
MPI_Status stats[2];
MTest_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
MPI_Win_allocate(2 * sizeof(int), sizeof(int), MPI_INFO_NULL, MPI_COMM_WORLD, &baseptr, &win);
/* Initialize window buffer */
MPI_Win_lock(MPI_LOCK_EXCLUSIVE, rank, 0, win);
baseptr[0] = 1;
baseptr[1] = 2;
MPI_Win_unlock(rank, win);
/* Synchronize the processes before starting the second access epoch */
MPI_Barrier(MPI_COMM_WORLD);
/* Issue request-based get with testall. */
MPI_Win_lock_all(0, win);
MPI_Rget(&val1, 1, MPI_INT, 0, 0, 1, MPI_INT, win, &reqs[0]);
MPI_Rget(&val2, 1, MPI_INT, 0, 1, 1, MPI_INT, win, &reqs[1]);
do {
mpi_errno = MPI_Testall(2, reqs, &flag, stats);
} while (flag == 0);
/* Check get value. */
if (val1 != 1 || val2 != 2) {
printf("%d - Got val1 = %d, val2 = %d, expected 1, 2\n", rank, val1, val2);
fflush(stdout);
errs++;
}
/* Check return error code. */
if (mpi_errno != MPI_SUCCESS) {
printf("%d - Got return errno %d, expected MPI_SUCCESS(%d)\n",
rank, mpi_errno, MPI_SUCCESS);
fflush(stdout);
errs++;
}
MPI_Win_unlock_all(win);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Win_free(&win);
MTest_Finalize(errs);
return MTestReturnValue(errs);
}
|
adcb18b05de17f853a2a2e1d2b9f1b114e104c48
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/MdePkg/Include/Library/SmmMemLib.h
|
2d86848ed0892c4fd06de7d69733262994f3000e
|
[
"BSD-2-Clause"
] |
permissive
|
CloverHackyColor/CloverBootloader
|
7042ca7dd6b513d22be591a295e49071ae1482ee
|
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
|
refs/heads/master
| 2023-08-30T22:14:34.590134
| 2023-08-27T19:14:02
| 2023-08-27T19:14:02
| 205,810,121
| 4,734
| 770
|
BSD-2-Clause
| 2023-09-03T12:41:33
| 2019-09-02T08:22:14
|
C
|
UTF-8
|
C
| false
| false
| 5,078
|
h
|
SmmMemLib.h
|
/** @file
Provides services for SMM Memory Operation.
The SMM Mem Library provides function for checking if buffer is outside SMRAM and valid.
It also provides functions for copy data from SMRAM to non-SMRAM, from non-SMRAM to SMRAM,
from non-SMRAM to non-SMRAM, or set data in non-SMRAM.
Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _SMM_MEM_LIB_H_
#define _SMM_MEM_LIB_H_
/**
This function check if the buffer is valid per processor architecture and not overlap with SMRAM.
@param Buffer The buffer start address to be checked.
@param Length The buffer length to be checked.
@retval TRUE This buffer is valid per processor architecture and not overlap with SMRAM.
@retval FALSE This buffer is not valid per processor architecture or overlap with SMRAM.
**/
BOOLEAN
EFIAPI
SmmIsBufferOutsideSmmValid (
IN EFI_PHYSICAL_ADDRESS Buffer,
IN UINT64 Length
);
/**
Copies a source buffer (non-SMRAM) to a destination buffer (SMRAM).
This function copies a source buffer (non-SMRAM) to a destination buffer (SMRAM).
It checks if source buffer is valid per processor architecture and not overlap with SMRAM.
If the check passes, it copies memory and returns EFI_SUCCESS.
If the check fails, it return EFI_SECURITY_VIOLATION.
The implementation must be reentrant.
@param DestinationBuffer The pointer to the destination buffer of the memory copy.
@param SourceBuffer The pointer to the source buffer of the memory copy.
@param Length The number of bytes to copy from SourceBuffer to DestinationBuffer.
@retval EFI_SECURITY_VIOLATION The SourceBuffer is invalid per processor architecture or overlap with SMRAM.
@retval EFI_SUCCESS Memory is copied.
**/
EFI_STATUS
EFIAPI
SmmCopyMemToSmram (
OUT VOID *DestinationBuffer,
IN CONST VOID *SourceBuffer,
IN UINTN Length
);
/**
Copies a source buffer (SMRAM) to a destination buffer (NON-SMRAM).
This function copies a source buffer (non-SMRAM) to a destination buffer (SMRAM).
It checks if destination buffer is valid per processor architecture and not overlap with SMRAM.
If the check passes, it copies memory and returns EFI_SUCCESS.
If the check fails, it returns EFI_SECURITY_VIOLATION.
The implementation must be reentrant.
@param DestinationBuffer The pointer to the destination buffer of the memory copy.
@param SourceBuffer The pointer to the source buffer of the memory copy.
@param Length The number of bytes to copy from SourceBuffer to DestinationBuffer.
@retval EFI_SECURITY_VIOLATION The DesinationBuffer is invalid per processor architecture or overlap with SMRAM.
@retval EFI_SUCCESS Memory is copied.
**/
EFI_STATUS
EFIAPI
SmmCopyMemFromSmram (
OUT VOID *DestinationBuffer,
IN CONST VOID *SourceBuffer,
IN UINTN Length
);
/**
Copies a source buffer (NON-SMRAM) to a destination buffer (NON-SMRAM).
This function copies a source buffer (non-SMRAM) to a destination buffer (SMRAM).
It checks if source buffer and destination buffer are valid per processor architecture and not overlap with SMRAM.
If the check passes, it copies memory and returns EFI_SUCCESS.
If the check fails, it returns EFI_SECURITY_VIOLATION.
The implementation must be reentrant, and it must handle the case where source buffer overlaps destination buffer.
@param DestinationBuffer The pointer to the destination buffer of the memory copy.
@param SourceBuffer The pointer to the source buffer of the memory copy.
@param Length The number of bytes to copy from SourceBuffer to DestinationBuffer.
@retval EFI_SECURITY_VIOLATION The DesinationBuffer is invalid per processor architecture or overlap with SMRAM.
@retval EFI_SECURITY_VIOLATION The SourceBuffer is invalid per processor architecture or overlap with SMRAM.
@retval EFI_SUCCESS Memory is copied.
**/
EFI_STATUS
EFIAPI
SmmCopyMem(
OUT VOID *DestinationBuffer,
IN CONST VOID *SourceBuffer,
IN UINTN Length
);
/**
Fills a target buffer (NON-SMRAM) with a byte value.
This function fills a target buffer (non-SMRAM) with a byte value.
It checks if target buffer is valid per processor architecture and not overlap with SMRAM.
If the check passes, it fills memory and returns EFI_SUCCESS.
If the check fails, it returns EFI_SECURITY_VIOLATION.
@param Buffer The memory to set.
@param Length The number of bytes to set.
@param Value The value with which to fill Length bytes of Buffer.
@retval EFI_SECURITY_VIOLATION The Buffer is invalid per processor architecture or overlap with SMRAM.
@retval EFI_SUCCESS Memory is set.
**/
EFI_STATUS
EFIAPI
SmmSetMem(
OUT VOID *Buffer,
IN UINTN Length,
IN UINT8 Value
);
#endif
|
105908c306eabca928f4c753bec3f546fd52df63
|
f1ee65fbe1ffc43c2aac45e41515f1987eb534a4
|
/src/third_party/nasm/version.h
|
87e584770d15062bea94ccfed52cb1e5da1b4289
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
klzgrad/naiveproxy
|
6e0d206b6f065b9311d1e12b363109f2d35cc058
|
8ef1cecadfd4e2b5d57e7ea2fa42d05717e51c2e
|
refs/heads/master
| 2023-08-20T22:42:12.511091
| 2023-06-04T03:54:34
| 2023-08-16T23:30:19
| 119,178,893
| 5,710
| 976
|
BSD-3-Clause
| 2023-08-05T10:59:59
| 2018-01-27T16:02:33
|
C++
|
UTF-8
|
C
| false
| false
| 276
|
h
|
version.h
|
#ifndef NASM_VERSION_H
#define NASM_VERSION_H
#define NASM_MAJOR_VER 2
#define NASM_MINOR_VER 15
#define NASM_SUBMINOR_VER 2
#define NASM_PATCHLEVEL_VER 96
#define NASM_VERSION_ID 0x020f0260
#define NASM_VER "2.15.03rc6"
#endif /* NASM_VERSION_H */
|
b8eaa1e24bf1922a80f499052642e54f4b389235
|
b5e9996707d879b3b01dbb45e6478b667b22fac7
|
/rmatch.c
|
1cd3bf9b94b945afbd47b4e6914d180d682be316
|
[
"ISC",
"GPL-1.0-or-later"
] |
permissive
|
kristapsdz/openrsync
|
6cafc395f68389ac92e9f3786790124013299b10
|
f50d0f8204ea18306a0c29c6ae850292ea826995
|
refs/heads/master
| 2023-08-23T10:30:31.062794
| 2022-05-08T21:47:56
| 2022-05-08T21:47:56
| 166,116,085
| 401
| 30
|
ISC
| 2023-04-12T05:24:54
| 2019-01-16T21:38:50
|
C
|
UTF-8
|
C
| false
| false
| 10,127
|
c
|
rmatch.c
|
/*
* Copyright (c) 2021 Claudio Jeker <claudio@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 1989, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Guido van Rossum.
*
* 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 "config.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include "charclass.h"
#include "extern.h"
#define RANGE_MATCH 1
#define RANGE_NOMATCH 0
#define RANGE_ERROR (-1)
static int
classmatch(const char *pattern, char test, const char **ep)
{
const char *mismatch = pattern;
const struct cclass *cc;
const char *colon;
size_t len;
int rval = RANGE_NOMATCH;
if (*pattern++ != ':') {
*ep = mismatch;
return RANGE_ERROR;
}
if ((colon = strchr(pattern, ':')) == NULL || colon[1] != ']') {
*ep = mismatch;
return RANGE_ERROR;
}
*ep = colon + 2;
len = (size_t)(colon - pattern);
for (cc = cclasses; cc->name != NULL; cc++) {
if (!strncmp(pattern, cc->name, len) && cc->name[len] == '\0') {
if (cc->isctype((unsigned char)test))
rval = RANGE_MATCH;
return rval;
}
}
/* invalid character class, treat as normal text */
*ep = mismatch;
return RANGE_ERROR;
}
static int
rangematch(const char **pp, char test)
{
const char *pattern = *pp;
int negate, ok;
char c, c2;
/*
* A bracket expression starting with an unquoted circumflex
* character produces unspecified results (IEEE 1003.2-1992,
* 3.13.2). This implementation treats it like '!', for
* consistency with the regular expression syntax.
* J.T. Conklin (conklin@ngai.kaleida.com)
*/
if ((negate = (*pattern == '!' || *pattern == '^')))
++pattern;
/*
* A right bracket shall lose its special meaning and represent
* itself in a bracket expression if it occurs first in the list.
* -- POSIX.2 2.8.3.2
*/
ok = 0;
c = *pattern++;
do {
if (c == '[') {
switch (classmatch(pattern, test, &pattern)) {
case RANGE_MATCH:
ok = 1;
continue;
case RANGE_NOMATCH:
continue;
default:
/* invalid character class, treat litterally. */
break;
}
}
if (c == '\\')
c = *pattern++;
if (c == '\0')
return RANGE_ERROR;
/* patterns can not match on '/' */
if (c == '/')
return RANGE_NOMATCH;
if (*pattern == '-'
&& (c2 = *(pattern + 1)) != '\0' && c2 != ']') {
pattern += 2;
if (c2 == '\\')
c2 = *pattern++;
if (c2 == '\0')
return RANGE_ERROR;
if (c <= test && test <= c2)
ok = 1;
} else if (c == test)
ok = 1;
} while ((c = *pattern++) != ']');
*pp = pattern;
return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH);
}
/*
* Single character match, advances pattern as much as needed.
* Return 0 on match and !0 (aka 1) on missmatch.
* When matched pp is advanced to the end of the pattern matched.
*/
static int
matchchar(const char **pp, const char in)
{
const char *pattern = *pp;
char c;
int rv = 0;
switch (c = *pattern++) {
case '?':
if (in == '\0')
rv = 1;
if (in == '/')
rv = 1;
break;
case '[':
if (in == '\0')
rv = 1;
if (in == '/')
rv = 1;
if (rv == 1)
break;
switch (rangematch(&pattern, in)) {
case RANGE_ERROR:
/* not a good range, treat as normal text */
goto normal;
case RANGE_MATCH:
break;
case RANGE_NOMATCH:
rv = 1;
}
break;
case '\\':
if ((c = *pattern++) == '\0') {
c = '\\';
--pattern;
}
/* FALLTHROUGH */
default:
normal:
if (c != in)
rv = 1;
break;
}
*pp = pattern;
return rv;
}
/*
* Do a substring match. If wild is set then the pattern started with a '*'.
* The match will go until '*', '/' or '\0' is encountered in pattern or
* the input string is consumed up to end.
* The pattern and string handles pp and ss are updated only on success.
*/
static int
matchsub(const char **pp, const char **ss, const char *end, int wild)
{
const char *pattern = *pp;
const char *p = pattern;
const char *string = *ss;
size_t matchlen;
/* first calculate how many characters the submatch will consume */
for (matchlen = 0; *p != '\0'; matchlen++) {
if (p[0] == '*')
break;
/* '/' acts as barrier */
if (p[0] == '/' || (p[0] == '\\' && p[1] == '/')) {
if (wild) {
/* match needs to match up to end of segment */
if (string > end - matchlen)
return 1;
string = end - matchlen;
wild = 0;
}
break;
}
/*
* skip forward one character in pattern by doing a
* dummy lookup.
*/
matchchar(&p, ' ');
}
/* not enough char to match */
if (string > end - matchlen)
return 1;
if (*p == '\0') {
if (wild) {
/* match needs to match up to end of segment */
string = end - matchlen;
wild = 0;
}
}
while (*pattern != '\0' && *pattern != '*') {
/* eat possible escape char before '/' */
if (pattern[0] == '\\' && pattern[1] == '/')
pattern++;
if (pattern[0] == '/')
break;
/* check if there are still characters available to compare */
if (string >= end)
return 1;
/* Compare one char at a time. */
if (!matchchar(&pattern, *string++))
continue;
if (wild) {
/* skip forward one char and restart match */
string = ++*ss;
pattern = *pp;
/* can it still match? */
if (string > end - matchlen)
return 1;
} else {
/* failed match */
return 1;
}
}
*pp = pattern;
*ss = string;
return 0;
}
/*
* File matching with the addition of the special '**'.
* Returns 0 on match and !0 for strings that do not match pattern.
*/
int
rmatch(const char *pattern, const char *string, int leading_dir)
{
const char *segend, *segnext, *mismatch = NULL;
int wild, starstar;
while (*pattern && *string) {
/* handle leading '/' first */
if (pattern[0] == '\\' && pattern[1] == '/')
pattern++;
if (*string == '/' && *pattern == '/') {
string++;
pattern++;
}
/* match to the next '/' in string */
segend = strchr(string, '/');
if (segend == NULL)
segend = strchr(string, '\0');
while (*pattern) {
/*
* Check for '*' and '**'. For '*' reduce '*' and '?'
* sequences into n-'?' and trailing '*'.
* For '**' this optimisation can not be done
* since '**???/' will match 'a/aa/aaa/' but not
* 'a/aa/aa/' still additional '*' will be reduced.
*/
wild = 0;
starstar = 0;
for ( ; *pattern == '*' || *pattern == '?'; pattern++) {
if (pattern[0] == '*') {
if (pattern[1] == '*') {
starstar = 1;
pattern++;
}
wild = 1;
} else if (!starstar) { /* pattern[0] == '?' */
if (string < segend && *string != '/')
string++;
else
/* no match possible */
return 1;
} else
break;
}
/* pattern ends in '**' so it is a match */
if (starstar && *pattern == '\0')
return 0;
if (starstar) {
segnext = segend;
mismatch = pattern;
}
while (string < segend) {
if (matchsub(&pattern, &string, segend, wild)) {
failed_match:
/*
* failed to match, if starstar retry
* with the next segment.
*/
if (mismatch) {
pattern = mismatch;
wild = 1;
string = segnext;
if (*string == '/')
string++;
segend = strchr(string, '/');
if (!segend)
segend = strchr(string,
'\0');
segnext = segend;
if (string < segend)
continue;
}
/* no match possible */
return 1;
}
break;
}
/* at end of string segment, eat up any extra '*' */
if (string >= segend && *pattern != '*')
break;
}
if (*string != '\0' && *string != '/')
goto failed_match;
if (*pattern != '\0' && *pattern != '/')
goto failed_match;
}
/* if both pattern and string are consumed it was a match */
if (*pattern == '\0' && *string == '\0')
return 0;
/* if leading_dir is set then string can also be '/' for success */
if (leading_dir && *pattern == '\0' && *string == '/')
return 0;
/* else failure */
return 1;
}
|
7c60315387f75b1e79230062827a453c337df11c
|
9823f12bbe144dae3c9decaba2bc38d3a2e94e90
|
/user/board/stm32f10x_hd/mcu_config.h
|
3446ad2ed4aa0351e2ce6e21f25c4fe4110ee531
|
[
"MIT"
] |
permissive
|
eboxmaker/eBox_Framework
|
e8512fe26ecd729df97fdf38c875567677954858
|
b6c19c526568ac68df3032295c46cbd26212e111
|
refs/heads/master
| 2023-08-15T10:41:53.584433
| 2023-07-23T04:10:52
| 2023-07-23T04:10:52
| 95,169,842
| 133
| 68
|
MIT
| 2020-10-31T01:02:41
| 2017-06-23T01:07:19
|
C
|
GB18030
|
C
| false
| false
| 2,320
|
h
|
mcu_config.h
|
#ifndef __MCU_CONFIG_H
#define __MCU_CONFIG_H
#include "stdint.h"
#include "ebox_type.h"
//用户配置区域
//请查阅ebox_cpu_type.h寻找特定信号CPU的详细配置
#define STM32_TYPE STM32F103ZE
#define STM32_PINS 144
#define STM32_FLASH 512
#define STM32_RAM1 64
#define STM32_COMPANY "ST\0"
#define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */
//由于KEIL自身有编译的宏定义会导致此选项无效,所以要更改keil的device选项,选择正确的MCU
#if !defined (STM32F10X_LD) && !defined (STM32F10X_LD_VL) && !defined (STM32F10X_MD) && !defined (STM32F10X_MD_VL) && !defined (STM32F10X_HD) && !defined (STM32F10X_HD_VL) && !defined (STM32F10X_XL) && !defined (STM32F10X_CL)
#if (STM32_FLASH <= 32)
#define STM32F10X_LD
#elif (STM32_FLASH <= 128)
#define STM32F10X_MD
#elif (MCU_FLASH <= 1024)
#define STM32F10X_HD
#endif
#endif
//外设配置
//------------------抽象层宏定义------------------------
#define MCU_TYPE STM32_TYPE
#define MCU_PINS STM32_PINS
#define MCU_COMPANY STM32_COMPANY
//RAM 区域定义
#define MCU_SRAM1_SIZE STM32_RAM1*1024
#define MCU_SRAM1_BEGIN 0x20000000
#define MCU_SRAM1_END (MCU_SRAM1_BEGIN + MCU_SRAM1_SIZE)
#if defined(__CC_ARM) || defined(__clang__)
extern int Image$$RW_IRAM1$$ZI$$Limit;
#define MCU_HEAP_BEGIN ((uint32_t)&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
#pragma section="HEAP"
#else
extern int __bss_end;
#endif
#define MCU_HEAP_END MCU_SRAM1_END
#define MCU_HEAP_SIZE (MCU_HEAP_END - MCU_HEAP_BEGIN)
#define MCU_SRAM1_USED (MCU_HEAP_BEGIN - MCU_SRAM1_BEGIN)
#define MCU_SRAM1_REMAIND (MCU_SRAM1_END - MCU_HEAP_BEGIN)
//FLASH 区域定义
#define MCU_FLASH_SIZE STM32_FLASH*1024
//#define MCU_FLASH_SIZE 128*1024
#if defined(__CC_ARM) || defined(__clang__)
extern int SHT$$INIT_ARRAY$$Limit;
#define MCU_FLASH_PRG_END ((uint32_t)&SHT$$INIT_ARRAY$$Limit)
#endif
#define MCU_FLASH_BEGIN 0x8000000
#define MCU_FLASH_END (0x8000000+MCU_FLASH_SIZE)
#define MCU_FLASH_USED (MCU_FLASH_PRG_END - MCU_FLASH_BEGIN)
#define MCU_FLASH_REMAIND (MCU_FLASH_END - MCU_FLASH_PRG_END)
//--------------------------------------------------------
#include "stm32f10x.h"
#endif
|
48de08c53351cdbdc0acf5e58cc9d309a2fa03e2
|
c6759b857e55991fea3ef0b465dbcee53fa38714
|
/gap8/rtos/pulp/archi_pulp/include/archi/chips/pulp/apb_soc_ctrl/apb_soc_ctrl_regmap.h
|
f207379ae79249f34e04549b331b0b12db6bbd87
|
[
"Apache-2.0"
] |
permissive
|
GreenWaves-Technologies/gap_sdk
|
1b343bba97b7a5ce62a24162bd72eef5cc67e269
|
3fea306d52ee33f923f2423c5a75d9eb1c07e904
|
refs/heads/master
| 2023-09-01T14:38:34.270427
| 2023-08-10T09:04:44
| 2023-08-10T09:04:44
| 133,324,605
| 145
| 96
|
Apache-2.0
| 2023-08-27T19:03:52
| 2018-05-14T07:50:29
|
C
|
UTF-8
|
C
| false
| false
| 1,385
|
h
|
apb_soc_ctrl_regmap.h
|
/* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT.
*/
/*
* Copyright (C) 2020 GreenWaves Technologies
*
* 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.
*/
#ifndef __ARCHI_APB_SOC_CTRL_REGMAP__
#define __ARCHI_APB_SOC_CTRL_REGMAP__
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
#include <stdint.h>
#endif
//
// REGISTERS GLOBAL STRUCT
//
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
/** APB_SOC_CTRL_Type Register Layout Typedef */
typedef struct {
volatile uint32_t info; // Core information register.
volatile uint32_t fc_boot; // Boot address
volatile uint32_t fc_fetch; // FC Fetch enable
volatile uint32_t reserved_0[37]; // Reserved/Not used.
volatile uint32_t corestatus; // EOC and chip status register
} __attribute__((packed)) apb_soc_ctrl_t;
#endif /* LANGUAGE_ASSEMBLY || __ASSEMBLER__ */
#endif
|
7365c95d2cc8df4e883c3bd6a0623f9c995f1938
|
1c1671b3cae08475a392d7397e290a44057afc85
|
/ch554_conf.c
|
cf3b1a5a98a603aecd432140d99c64bdcbdcdb7f
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
rikka0w0/CH55x_USB_CompositeDevice
|
aea8bfb000bc22528e222855954d2de34260e4d7
|
489bcf73a9872945ca642d420113aea2c8824348
|
refs/heads/master
| 2022-11-21T20:03:36.121407
| 2018-03-19T04:55:55
| 2018-03-19T04:55:55
| 115,002,442
| 101
| 28
|
MIT
| 2020-07-30T06:55:33
| 2017-12-21T12:15:24
|
C++
|
UTF-8
|
C
| false
| false
| 4,589
|
c
|
ch554_conf.c
|
#include "Delay.H"
#include "ch554_platform.h"
#include "usb_desc.h"
#include "usb_endp.h"
#include "usb_mal.h"
#include "i2c.h"
void ConfigSysClock() {
//SAFE_MOD = 0x55;
//SAFE_MOD = 0xAA;
//CLOCK_CFG |= bOSC_EN_XT; // Enable External Crystal
//CLOCK_CFG &= ~bOSC_EN_INT; // Disable External Crystal
// Enters `safe mode` for next 13 to 23 CPU clock cycles
SAFE_MOD = 0x55;
SAFE_MOD = 0xAA;
#if defined CLOCK_FREQ_32
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x07; // 32MHz
#elif defined CLOCK_FREQ_24
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x06; // 24MHz
#elif defined CLOCK_FREQ_16
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x05; // 16MHz
#elif defined CLOCK_FREQ_12
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x04; // 12MHz
#elif defined CLOCK_FREQ_6
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x03; // 6MHz
#elif defined CLOCK_FREQ_3
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x02; // 3MHz
#elif defined CLOCK_FREQ_P750
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x01; // 750KHz
#elif defined CLOCK_FREQ_P1875
CLOCK_CFG = CLOCK_CFG & ~ MASK_SYS_CK_SEL | 0x00; // 187.5KHz
#else
#error "Clock frequency is not configured!"
#endif
SAFE_MOD = 0x00;
}
void USBDevice_Init() {
IE_USB = 0; // Disable USB interrupt (for setup)
USB_CTRL = 0x00; // Device mode, Full speed(12Mbps), Disable pull up(Invisible to host), Reset stuff
//UDEV_CTRL = bUD_PD_DIS; //Disable DP/DN pull down resistor
//Configure Endpoint 0
UEP0_DMA_L = (uint8_t) Ep0Buffer; // Address of Endpoint 0 buffer
// bUEP4_RX_EN and bUEP4_TX_EN controls both Endpoint 0 and 4, refer to table 16.3.2
UEP4_1_MOD &= ~(bUEP4_RX_EN | bUEP4_TX_EN); // EP0 64-byte buffer
UEP0_CTRL = UEP_R_RES_ACK | UEP_T_RES_NAK; // SETUP/OUT -> ACK, IN -> NAK
//Configure Endpoint 1
UEP1_DMA_L = (uint8_t) Ep1Buffer; // Address of Endpoint 1 buffer
//UEP4_1_MOD = UEP4_1_MOD & ~bUEP1_BUF_MOD | bUEP1_TX_EN;
UEP4_1_MOD &=~bUEP1_BUF_MOD; //See table 16.3.3
UEP4_1_MOD |= bUEP1_TX_EN; // EP1 Tx only, 64 bytes of buffer
// Enable DATA0/DATA1 toggling, Reply NAK for IN transactions
UEP1_CTRL = bUEP_AUTO_TOG | UEP_T_RES_NAK;
//Configure Endpoint 2
UEP2_DMA_L = (uint8_t) Ep2Buffer; // Address of Endpoint 2 buffer
//UEP2_3_MOD = UEP2_3_MOD & ~bUEP2_BUF_MOD | bUEP2_TX_EN;
UEP2_3_MOD &=~bUEP2_BUF_MOD; // Disable Endpoint2 buffer mode
UEP2_3_MOD |= bUEP2_TX_EN; // Enable Endpoint2 Tx
UEP2_3_MOD |= bUEP2_RX_EN; // Enable Endpoint2 Rx
// Enable DATA0/DATA1 toggling, Reply NAK for IN transactions, ACK for OUT transactions
UEP2_CTRL = bUEP_AUTO_TOG | UEP_T_RES_NAK | UEP_R_RES_ACK;
//Configure Endpoint 3
UEP3_DMA_L = (uint16_t) Ep3Buffer; // Address of Endpoint 2 buffer
//UEP2_3_MOD = UEP2_3_MOD & ~bUEP2_BUF_MOD | bUEP2_TX_EN;
UEP2_3_MOD &=~bUEP3_BUF_MOD; // Disable Endpoint3 buffer mode
UEP2_3_MOD |= bUEP3_TX_EN; // Enable Endpoint3 Tx
UEP2_3_MOD |= bUEP3_RX_EN; // Enable Endpoint3 Rx
UEP3_CTRL = bUEP_AUTO_TOG | UEP_T_RES_NAK | UEP_R_RES_ACK;
// Setup interrupts
USB_INT_FG = 0xFF; // Clear interrupt flags
// Generate a interrupt when USB bus suspend | transfer complete | bus reset
USB_INT_EN = bUIE_SUSPEND | bUIE_TRANSFER | bUIE_BUS_RST;
IE_USB = 1; //Enable USB interrupt
// Get ready for enumeration
USB_DEV_AD = 0x00; //Set USB address to 0, get ready for enumeration
// Connect pull up resistor | While handling interrup, reply NAK t if flag is set | Enable DMA
USB_CTRL = bUC_DEV_PU_EN | bUC_INT_BUSY | bUC_DMA_EN;
UDEV_CTRL |= bUD_PORT_EN; // Enable USB Port
// Reset all tx length to 0
UEP1_T_LEN = 0;
UEP2_T_LEN = 0;
UEP3_T_LEN = 0;
}
void UART0_Init(void) {
uint32_t x;
uint8_t x2;
SM0 = 0;
SM1 = 1;
SM2 = 0; // UART0 Mode 0
// Use Timer1 as the baud rate generator
RCLK = 0;
TCLK = 0;
PCON |= SMOD;
x = 10 * FREQ_SYS / UART0_BUAD / 16;
x2 = x % 10;
x /= 10;
if ( x2 >= 5 ) x ++; // Round
TMOD = TMOD & ~ bT1_GATE & ~ bT1_CT & ~ MASK_T1_MOD | bT1_M1; // Timer1: 8-bit auto reload
T2MOD = T2MOD | bTMR_CLK | bT1_CLK; // Select input clock for Timer1
TH1 = 0-x;
TR1 = 1; // Start Timer1
TI = 1;
REN = 1; // Enable UART1
}
void CH554_Init(void) {
ConfigSysClock();
mDelaymS(5); // Wait until the internal crystal becomes stable
UART0_Init();
I2C_Init();
LUN_Init();
USBDevice_Init();
EA = 1;
}
void putchar(char c) {
while (!TI) /* assumes UART is initialized */
;
TI = 0;
SBUF = c;
}
char getchar() {
while(!RI); /* assumes UART is initialized */
RI = 0;
return SBUF;
}
|
6ed6c76bc4367717adc8d7aadf2c2c91ef53cc5a
|
d34491914a659b09e9e1e86ca304643d03735592
|
/event/nio.c
|
4ae5cc7aa7c9242eb58737d465fa6a0f029b38d4
|
[
"BSD-3-Clause"
] |
permissive
|
ithewei/libhv
|
acfa23901ebff7445631df7abfb4ac832af4cef6
|
23ed8fbe22a4b270cef70d2924bab4f3f8fff2c2
|
refs/heads/master
| 2023-09-03T19:14:57.606708
| 2023-08-29T13:36:08
| 2023-08-29T13:36:08
| 146,397,768
| 6,015
| 1,171
|
BSD-3-Clause
| 2023-09-12T03:31:03
| 2018-08-28T05:47:15
|
C
|
UTF-8
|
C
| false
| false
| 17,328
|
c
|
nio.c
|
#include "iowatcher.h"
#ifndef EVENT_IOCP
#include "hevent.h"
#include "hsocket.h"
#include "hssl.h"
#include "hlog.h"
#include "herr.h"
#include "hthread.h"
static void __connect_timeout_cb(htimer_t* timer) {
hio_t* io = (hio_t*)timer->privdata;
if (io) {
char localaddrstr[SOCKADDR_STRLEN] = {0};
char peeraddrstr[SOCKADDR_STRLEN] = {0};
hlogw("connect timeout [%s] <=> [%s]",
SOCKADDR_STR(io->localaddr, localaddrstr),
SOCKADDR_STR(io->peeraddr, peeraddrstr));
io->error = ETIMEDOUT;
hio_close(io);
}
}
static void __close_timeout_cb(htimer_t* timer) {
hio_t* io = (hio_t*)timer->privdata;
if (io) {
char localaddrstr[SOCKADDR_STRLEN] = {0};
char peeraddrstr[SOCKADDR_STRLEN] = {0};
hlogw("close timeout [%s] <=> [%s]",
SOCKADDR_STR(io->localaddr, localaddrstr),
SOCKADDR_STR(io->peeraddr, peeraddrstr));
io->error = ETIMEDOUT;
hio_close(io);
}
}
static void __accept_cb(hio_t* io) {
hio_accept_cb(io);
}
static void __connect_cb(hio_t* io) {
hio_del_connect_timer(io);
hio_connect_cb(io);
}
static void __read_cb(hio_t* io, void* buf, int readbytes) {
// printd("> %.*s\n", readbytes, buf);
io->last_read_hrtime = io->loop->cur_hrtime;
hio_handle_read(io, buf, readbytes);
}
static void __write_cb(hio_t* io, const void* buf, int writebytes) {
// printd("< %.*s\n", writebytes, buf);
io->last_write_hrtime = io->loop->cur_hrtime;
hio_write_cb(io, buf, writebytes);
}
static void __close_cb(hio_t* io) {
// printd("close fd=%d\n", io->fd);
hio_del_connect_timer(io);
hio_del_close_timer(io);
hio_del_read_timer(io);
hio_del_write_timer(io);
hio_del_keepalive_timer(io);
hio_del_heartbeat_timer(io);
hio_close_cb(io);
}
static void ssl_server_handshake(hio_t* io) {
printd("ssl server handshake...\n");
int ret = hssl_accept(io->ssl);
if (ret == 0) {
// handshake finish
hio_del(io, HV_READ);
printd("ssl handshake finished.\n");
__accept_cb(io);
}
else if (ret == HSSL_WANT_READ) {
if ((io->events & HV_READ) == 0) {
hio_add(io, ssl_server_handshake, HV_READ);
}
}
else {
hloge("ssl handshake failed: %d", ret);
io->error = ERR_SSL_HANDSHAKE;
hio_close(io);
}
}
static void ssl_client_handshake(hio_t* io) {
printd("ssl client handshake...\n");
int ret = hssl_connect(io->ssl);
if (ret == 0) {
// handshake finish
hio_del(io, HV_READ);
printd("ssl handshake finished.\n");
__connect_cb(io);
}
else if (ret == HSSL_WANT_READ) {
if ((io->events & HV_READ) == 0) {
hio_add(io, ssl_client_handshake, HV_READ);
}
}
else {
hloge("ssl handshake failed: %d", ret);
io->error = ERR_SSL_HANDSHAKE;
hio_close(io);
}
}
static void nio_accept(hio_t* io) {
// printd("nio_accept listenfd=%d\n", io->fd);
int connfd = 0, err = 0, accept_cnt = 0;
socklen_t addrlen;
hio_t* connio = NULL;
while (accept_cnt++ < 3) {
addrlen = sizeof(sockaddr_u);
connfd = accept(io->fd, io->peeraddr, &addrlen);
if (connfd < 0) {
err = socket_errno();
if (err == EAGAIN || err == EINTR) {
return;
} else {
perror("accept");
io->error = err;
goto accept_error;
}
}
addrlen = sizeof(sockaddr_u);
getsockname(connfd, io->localaddr, &addrlen);
connio = hio_get(io->loop, connfd);
// NOTE: inherit from listenio
connio->accept_cb = io->accept_cb;
connio->userdata = io->userdata;
if (io->unpack_setting) {
hio_set_unpack(connio, io->unpack_setting);
}
if (io->io_type == HIO_TYPE_SSL) {
if (connio->ssl == NULL) {
// io->ssl_ctx > g_ssl_ctx > hssl_ctx_new
hssl_ctx_t ssl_ctx = NULL;
if (io->ssl_ctx) {
ssl_ctx = io->ssl_ctx;
} else if (g_ssl_ctx) {
ssl_ctx = g_ssl_ctx;
} else {
io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
io->alloced_ssl_ctx = 1;
}
if (ssl_ctx == NULL) {
io->error = ERR_NEW_SSL_CTX;
goto accept_error;
}
hssl_t ssl = hssl_new(ssl_ctx, connfd);
if (ssl == NULL) {
io->error = ERR_NEW_SSL;
goto accept_error;
}
connio->ssl = ssl;
}
hio_enable_ssl(connio);
ssl_server_handshake(connio);
}
else {
// NOTE: SSL call accept_cb after handshake finished
__accept_cb(connio);
}
}
return;
accept_error:
hloge("listenfd=%d accept error: %s:%d", io->fd, socket_strerror(io->error), io->error);
// NOTE: Don't close listen fd automatically anyway.
// hio_close(io);
}
static void nio_connect(hio_t* io) {
// printd("nio_connect connfd=%d\n", io->fd);
socklen_t addrlen = sizeof(sockaddr_u);
int ret = getpeername(io->fd, io->peeraddr, &addrlen);
if (ret < 0) {
io->error = socket_errno();
goto connect_error;
}
else {
addrlen = sizeof(sockaddr_u);
getsockname(io->fd, io->localaddr, &addrlen);
if (io->io_type == HIO_TYPE_SSL) {
if (io->ssl == NULL) {
// io->ssl_ctx > g_ssl_ctx > hssl_ctx_new
hssl_ctx_t ssl_ctx = NULL;
if (io->ssl_ctx) {
ssl_ctx = io->ssl_ctx;
} else if (g_ssl_ctx) {
ssl_ctx = g_ssl_ctx;
} else {
io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
io->alloced_ssl_ctx = 1;
}
if (ssl_ctx == NULL) {
io->error = ERR_NEW_SSL_CTX;
goto connect_error;
}
hssl_t ssl = hssl_new(ssl_ctx, io->fd);
if (ssl == NULL) {
io->error = ERR_NEW_SSL;
goto connect_error;
}
io->ssl = ssl;
}
if (io->hostname) {
hssl_set_sni_hostname(io->ssl, io->hostname);
}
ssl_client_handshake(io);
}
else {
// NOTE: SSL call connect_cb after handshake finished
__connect_cb(io);
}
return;
}
connect_error:
hlogw("connfd=%d connect error: %s:%d", io->fd, socket_strerror(io->error), io->error);
hio_close(io);
}
static void nio_connect_event_cb(hevent_t* ev) {
hio_t* io = (hio_t*)ev->userdata;
uint32_t id = (uintptr_t)ev->privdata;
if (io->id != id) return;
nio_connect(io);
}
static int nio_connect_async(hio_t* io) {
hevent_t ev;
memset(&ev, 0, sizeof(ev));
ev.cb = nio_connect_event_cb;
ev.userdata = io;
ev.privdata = (void*)(uintptr_t)io->id;
hloop_post_event(io->loop, &ev);
return 0;
}
static int __nio_read(hio_t* io, void* buf, int len) {
int nread = 0;
switch (io->io_type) {
case HIO_TYPE_SSL:
nread = hssl_read(io->ssl, buf, len);
break;
case HIO_TYPE_TCP:
nread = recv(io->fd, buf, len, 0);
break;
case HIO_TYPE_UDP:
case HIO_TYPE_KCP:
case HIO_TYPE_IP:
{
socklen_t addrlen = sizeof(sockaddr_u);
nread = recvfrom(io->fd, buf, len, 0, io->peeraddr, &addrlen);
}
break;
default:
nread = read(io->fd, buf, len);
break;
}
// hlogd("read retval=%d", nread);
return nread;
}
static int __nio_write(hio_t* io, const void* buf, int len) {
int nwrite = 0;
switch (io->io_type) {
case HIO_TYPE_SSL:
nwrite = hssl_write(io->ssl, buf, len);
break;
case HIO_TYPE_TCP:
{
int flag = 0;
#ifdef MSG_NOSIGNAL
flag |= MSG_NOSIGNAL;
#endif
nwrite = send(io->fd, buf, len, flag);
}
break;
case HIO_TYPE_UDP:
case HIO_TYPE_KCP:
case HIO_TYPE_IP:
nwrite = sendto(io->fd, buf, len, 0, io->peeraddr, SOCKADDR_LEN(io->peeraddr));
break;
default:
nwrite = write(io->fd, buf, len);
break;
}
// hlogd("write retval=%d", nwrite);
return nwrite;
}
static void nio_read(hio_t* io) {
// printd("nio_read fd=%d\n", io->fd);
void* buf;
int len = 0, nread = 0, err = 0;
read:
buf = io->readbuf.base + io->readbuf.tail;
if (io->read_flags & HIO_READ_UNTIL_LENGTH) {
len = io->read_until_length - (io->readbuf.tail - io->readbuf.head);
} else {
len = io->readbuf.len - io->readbuf.tail;
}
assert(len > 0);
nread = __nio_read(io, buf, len);
// printd("read retval=%d\n", nread);
if (nread < 0) {
err = socket_errno();
if (err == EAGAIN || err == EINTR) {
// goto read_done;
return;
} else if (err == EMSGSIZE) {
// ignore
return;
} else {
// perror("read");
io->error = err;
goto read_error;
}
}
if (nread == 0) {
goto disconnect;
}
io->readbuf.tail += nread;
__read_cb(io, buf, nread);
if (nread == len && !io->closed) {
// NOTE: ssl may have own cache
if (io->io_type == HIO_TYPE_SSL) {
// read continue
goto read;
}
}
return;
read_error:
disconnect:
if (io->io_type & HIO_TYPE_SOCK_STREAM) {
hio_close(io);
}
}
static void nio_write(hio_t* io) {
// printd("nio_write fd=%d\n", io->fd);
int nwrite = 0, err = 0;
hrecursive_mutex_lock(&io->write_mutex);
write:
if (write_queue_empty(&io->write_queue)) {
hrecursive_mutex_unlock(&io->write_mutex);
if (io->close) {
io->close = 0;
hio_close(io);
}
return;
}
offset_buf_t* pbuf = write_queue_front(&io->write_queue);
char* base = pbuf->base;
char* buf = base + pbuf->offset;
int len = pbuf->len - pbuf->offset;
nwrite = __nio_write(io, buf, len);
// printd("write retval=%d\n", nwrite);
if (nwrite < 0) {
err = socket_errno();
if (err == EAGAIN || err == EINTR) {
hrecursive_mutex_unlock(&io->write_mutex);
return;
} else {
// perror("write");
io->error = err;
goto write_error;
}
}
if (nwrite == 0) {
goto disconnect;
}
pbuf->offset += nwrite;
io->write_bufsize -= nwrite;
__write_cb(io, buf, nwrite);
if (nwrite == len) {
// NOTE: after write_cb, pbuf maybe invalid.
// HV_FREE(pbuf->base);
HV_FREE(base);
write_queue_pop_front(&io->write_queue);
if (!io->closed) {
// write continue
goto write;
}
}
hrecursive_mutex_unlock(&io->write_mutex);
return;
write_error:
disconnect:
hrecursive_mutex_unlock(&io->write_mutex);
if (io->io_type & HIO_TYPE_SOCK_STREAM) {
hio_close(io);
}
}
static void hio_handle_events(hio_t* io) {
if ((io->events & HV_READ) && (io->revents & HV_READ)) {
if (io->accept) {
nio_accept(io);
}
else {
nio_read(io);
}
}
if ((io->events & HV_WRITE) && (io->revents & HV_WRITE)) {
// NOTE: del HV_WRITE, if write_queue empty
hrecursive_mutex_lock(&io->write_mutex);
if (write_queue_empty(&io->write_queue)) {
hio_del(io, HV_WRITE);
}
hrecursive_mutex_unlock(&io->write_mutex);
if (io->connect) {
// NOTE: connect just do once
// ONESHOT
io->connect = 0;
nio_connect(io);
}
else {
nio_write(io);
}
}
io->revents = 0;
}
int hio_accept(hio_t* io) {
io->accept = 1;
return hio_add(io, hio_handle_events, HV_READ);
}
int hio_connect(hio_t* io) {
int ret = connect(io->fd, io->peeraddr, SOCKADDR_LEN(io->peeraddr));
#ifdef OS_WIN
if (ret < 0 && socket_errno() != WSAEWOULDBLOCK) {
#else
if (ret < 0 && socket_errno() != EINPROGRESS) {
#endif
perror("connect");
io->error = socket_errno();
hio_close_async(io);
return ret;
}
if (ret == 0) {
// connect ok
nio_connect_async(io);
return 0;
}
int timeout = io->connect_timeout ? io->connect_timeout : HIO_DEFAULT_CONNECT_TIMEOUT;
io->connect_timer = htimer_add(io->loop, __connect_timeout_cb, timeout, 1);
io->connect_timer->privdata = io;
io->connect = 1;
return hio_add(io, hio_handle_events, HV_WRITE);
}
int hio_read (hio_t* io) {
if (io->closed) {
hloge("hio_read called but fd[%d] already closed!", io->fd);
return -1;
}
hio_add(io, hio_handle_events, HV_READ);
if (io->readbuf.tail > io->readbuf.head &&
io->unpack_setting == NULL &&
io->read_flags == 0) {
hio_read_remain(io);
}
return 0;
}
int hio_write (hio_t* io, const void* buf, size_t len) {
if (io->closed) {
hloge("hio_write called but fd[%d] already closed!", io->fd);
return -1;
}
int nwrite = 0, err = 0;
hrecursive_mutex_lock(&io->write_mutex);
#if WITH_KCP
if (io->io_type == HIO_TYPE_KCP) {
nwrite = hio_write_kcp(io, buf, len);
// if (nwrite < 0) goto write_error;
goto write_done;
}
#endif
if (write_queue_empty(&io->write_queue)) {
try_write:
nwrite = __nio_write(io, buf, len);
// printd("write retval=%d\n", nwrite);
if (nwrite < 0) {
err = socket_errno();
if (err == EAGAIN || err == EINTR) {
nwrite = 0;
hlogw("try_write failed, enqueue!");
goto enqueue;
} else {
// perror("write");
io->error = err;
goto write_error;
}
}
if (nwrite == 0) {
goto disconnect;
}
if (nwrite == len) {
goto write_done;
}
enqueue:
hio_add(io, hio_handle_events, HV_WRITE);
}
if (nwrite < len) {
if (io->write_bufsize + len - nwrite > io->max_write_bufsize) {
hloge("write bufsize > %u, close it!", io->max_write_bufsize);
io->error = ERR_OVER_LIMIT;
goto write_error;
}
offset_buf_t remain;
remain.len = len - nwrite;
remain.offset = 0;
// NOTE: free in nio_write
HV_ALLOC(remain.base, remain.len);
memcpy(remain.base, ((char*)buf) + nwrite, remain.len);
if (io->write_queue.maxsize == 0) {
write_queue_init(&io->write_queue, 4);
}
write_queue_push_back(&io->write_queue, &remain);
io->write_bufsize += remain.len;
if (io->write_bufsize > WRITE_BUFSIZE_HIGH_WATER) {
hlogw("write len=%u enqueue %u, bufsize=%u over high water %u",
(unsigned int)len,
(unsigned int)(remain.len - remain.offset),
(unsigned int)io->write_bufsize,
(unsigned int)WRITE_BUFSIZE_HIGH_WATER);
}
}
write_done:
hrecursive_mutex_unlock(&io->write_mutex);
if (nwrite > 0) {
__write_cb(io, buf, nwrite);
}
return nwrite;
write_error:
disconnect:
hrecursive_mutex_unlock(&io->write_mutex);
/* NOTE:
* We usually free resources in hclose_cb,
* if hio_close_sync, we have to be very careful to avoid using freed resources.
* But if hio_close_async, we do not have to worry about this.
*/
if (io->io_type & HIO_TYPE_SOCK_STREAM) {
hio_close_async(io);
}
return nwrite < 0 ? nwrite : -1;
}
int hio_close (hio_t* io) {
if (io->closed) return 0;
if (hv_gettid() != io->loop->tid) {
return hio_close_async(io);
}
hrecursive_mutex_lock(&io->write_mutex);
if (io->closed) {
hrecursive_mutex_unlock(&io->write_mutex);
return 0;
}
if (!write_queue_empty(&io->write_queue) && io->error == 0 && io->close == 0) {
io->close = 1;
hrecursive_mutex_unlock(&io->write_mutex);
hlogw("write_queue not empty, close later.");
int timeout_ms = io->close_timeout ? io->close_timeout : HIO_DEFAULT_CLOSE_TIMEOUT;
io->close_timer = htimer_add(io->loop, __close_timeout_cb, timeout_ms, 1);
io->close_timer->privdata = io;
return 0;
}
io->closed = 1;
hrecursive_mutex_unlock(&io->write_mutex);
hio_done(io);
__close_cb(io);
if (io->ssl) {
hssl_free(io->ssl);
io->ssl = NULL;
}
if (io->ssl_ctx && io->alloced_ssl_ctx) {
hssl_ctx_free(io->ssl_ctx);
io->ssl_ctx = NULL;
}
SAFE_FREE(io->hostname);
if (io->io_type & HIO_TYPE_SOCKET) {
closesocket(io->fd);
}
return 0;
}
#endif
|
c54132d0ad90253ec44b24af63b4ef1846f9516e
|
1577e1cf4e89584a125cffb855ca50a9654c6d55
|
/Security/keychain/SecureObjectSync/SOSRingBasic.h
|
85dfdf49b0a9bf07dde7e83e8be0401fe7f72e84
|
[] |
no_license
|
apple-open-source/macos
|
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
|
2d2b15f13487673de33297e49f00ef94af743a9a
|
refs/heads/master
| 2023-08-01T11:03:26.870408
| 2023-03-27T00:00:00
| 2023-03-27T00:00:00
| 180,595,052
| 124
| 24
| null | 2022-12-27T14:54:09
| 2019-04-10T14:06:23
| null |
UTF-8
|
C
| false
| false
| 1,289
|
h
|
SOSRingBasic.h
|
//
// SOSRingBasic.h
// sec
//
// Created by Richard Murphy on 3/3/15.
//
//
#ifndef _sec_SOSRingBasic_
#define _sec_SOSRingBasic_
#include "SOSRingTypes.h"
SOSRingRef SOSRingCreate_Basic(CFStringRef name, CFStringRef myPeerID, CFErrorRef *error);
bool SOSRingResetToEmpty_Basic(SOSRingRef ring, CFStringRef myPeerID, CFErrorRef *error);
SOSRingStatus SOSRingDeviceIsInRing_Basic(SOSRingRef ring, CFStringRef peerID);
bool SOSRingResetToOffering_Basic(SOSRingRef ring, SecKeyRef user_privkey, SOSFullPeerInfoRef requestor, CFErrorRef *error);
bool SOSRingApply_Basic(SOSRingRef ring, SecKeyRef user_pubkey, SOSFullPeerInfoRef requestor, CFErrorRef *error);
bool SOSRingWithdraw_Basic(SOSRingRef ring, SecKeyRef user_privkey, SOSFullPeerInfoRef requestor, CFErrorRef *error);
bool SOSRingGenerationSign_Basic(SOSRingRef ring, SecKeyRef user_privkey, SOSFullPeerInfoRef requestor, CFErrorRef *error);
bool SOSRingConcordanceSign_Basic(SOSRingRef ring, SOSFullPeerInfoRef requestor, CFErrorRef *error);
bool SOSRingSetPayload_Basic(SOSRingRef ring, SecKeyRef user_privkey, CFDataRef payload, SOSFullPeerInfoRef requestor, CFErrorRef *error);
CFDataRef SOSRingGetPayload_Basic(SOSRingRef ring, CFErrorRef *error);
extern ringFuncStruct basic;
#endif /* defined(_sec_SOSRingBasic_) */
|
ea2c4ac8ab5450bfd88f9c3ae473dd69cf16036f
|
51de1ebe7fa09fb262e015fb454829987ed5fc83
|
/provisioning_service_client/samples/prov_sc_enrollment_group_sample/prov_sc_enrollment_group_sample.c
|
265d8cd4ea186765a7beb5d5802369225b471607
|
[
"MIT"
] |
permissive
|
Azure/azure-iot-sdk-c
|
54bf46938f5b8089ba06081cb4d7967fa3a8f777
|
1f3d95b4dae09927ae4bbe479e52d48acef1f93c
|
refs/heads/main
| 2023-08-31T03:36:13.694208
| 2023-08-30T23:56:13
| 2023-08-30T23:56:13
| 70,934,373
| 629
| 902
|
NOASSERTION
| 2023-09-06T17:41:38
| 2016-10-14T17:54:57
|
C
|
UTF-8
|
C
| false
| false
| 3,693
|
c
|
prov_sc_enrollment_group_sample.c
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdlib.h>
#include <stdio.h>
#include "azure_c_shared_utility/platform.h"
#include "../../../certs/certs.h"
#include "prov_service_client/provisioning_service_client.h"
static bool g_use_trace = true;
#ifdef USE_OPENSSL
static bool g_use_certificate = true;
#else
static bool g_use_certificate = false;
#endif //USE_OPENSSL
int main(void)
{
int result = 0;
const char* connectionString = "[Connection String]";
const char* groupId = "[Group Id]";
const char* signingCertificate = "[Signing Certificate]";
const char* tags = "{\"key\":\"value\"}";
PROVISIONING_SERVICE_CLIENT_HANDLE prov_sc;
ATTESTATION_MECHANISM_HANDLE am_handle;
ENROLLMENT_GROUP_HANDLE eg_handle;
INITIAL_TWIN_HANDLE twin_handle;
printf("Starting Enrollment Group sample...\n");
/* ---Create a Provisioning Service Client Handle */
printf("Connecting to the Provisioning Service...\n");
/*This function must be called before anything else so that sockets work*/
platform_init();
/* This creates a handle that will be used to represent a connection to the
Device Provisioning Service indicated by the connection string given. */
prov_sc = prov_sc_create_from_connection_string(connectionString);
/* ---Optionally set connection options--- */
if (g_use_trace)
{
prov_sc_set_trace(prov_sc, TRACING_STATUS_ON);
}
if (g_use_certificate)
{
prov_sc_set_certificate(prov_sc, certificates);
}
/* ---Create an Enrollment Group structure--- */
printf("Creating an Enrollment Group structure...\n");
am_handle = attestationMechanism_createWithX509SigningCert(signingCertificate, NULL);
eg_handle = enrollmentGroup_create(groupId, am_handle);
/* ---Create the Enrollment Group on the Provisioning Service--- */
printf("Creating an Enrollment Group on the Provisioning Service...\n");
/*Note that after a successful create, the pointer of the given model
is updated to contain new information generated by the Provisioning Service*/
prov_sc_create_or_update_enrollment_group(prov_sc, &eg_handle);
/* ---Retrieve an Enrollment Group on the Provisioning Service--- */
printf("Retrieving an Enrollment Group from the Provisioning Service...\n");
/*Note that in this context, doing a "get" call is a useless since the "create or update" call
above already updated "eg_handle", and no changes have been made since. This is just to
show you how a "get" would be performed */
enrollmentGroup_destroy(eg_handle);
prov_sc_get_enrollment_group(prov_sc, groupId, &eg_handle);
/* ---Update an Enrollment Group on the Provisioning Service ---*/
printf("Updated an Individual Enrollment structure\n");
//in this example we'll add an initial twin state
twin_handle = initialTwin_create(tags, NULL);
enrollmentGroup_setInitialTwin(eg_handle, twin_handle);
/* This is the same call as we used for creation. However, because we already created the
enrollment on the Provisioning Service, this call will now update the already existing one */
prov_sc_create_or_update_enrollment_group(prov_sc, &eg_handle);
/* ---Delete an Enrollment Group on the Provisioning Service--- */
printf("Deleting an Enrollment Group on the Provisioning Service...\n");
prov_sc_delete_enrollment_group(prov_sc, eg_handle);
/* ---Clean up handles--- */
enrollmentGroup_destroy(eg_handle);
prov_sc_destroy(prov_sc);
platform_deinit();
return result;
}
|
2f580b60aae655aa1f88c10c316a27842a1e03f6
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/gui/QvisAnnotationObjectInterfaceFactory.C
|
e39b11707c26b45817d8d0684655b2427ba0ec40
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
visit-dav/visit
|
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
|
601ae46e0bef2e18425b482a755d03490ade0493
|
refs/heads/develop
| 2023-09-06T08:19:38.397058
| 2023-09-05T21:29:32
| 2023-09-05T21:29:32
| 165,565,988
| 335
| 120
|
BSD-3-Clause
| 2023-09-14T00:53:37
| 2019-01-13T23:27:26
|
C
|
UTF-8
|
C
| false
| false
| 4,539
|
c
|
QvisAnnotationObjectInterfaceFactory.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <QvisAnnotationObjectInterfaceFactory.h>
#include <QvisImageAnnotationInterface.h>
#include <QvisLegendAttributesInterface.h>
#include <QvisLine2DInterface.h>
#include <QvisLine3DInterface.h>
#include <QvisText2DInterface.h>
#include <QvisText3DInterface.h>
#include <QvisTimeSliderInterface.h>
#include <DebugStream.h>
// ****************************************************************************
// Method: QvisAnnotationObjectInterfaceFactory::QvisAnnotationObjectInterfaceFactory
//
// Purpose:
// Constructor for the QvisAnnotationObjectInterfaceFactory class.
//
// Programmer: Brad Whitlock
// Creation: Fri Oct 31 09:31:50 PDT 2003
//
// Modifications:
//
// ****************************************************************************
QvisAnnotationObjectInterfaceFactory::QvisAnnotationObjectInterfaceFactory()
{
}
// ****************************************************************************
// Method: QvisAnnotationObjectInterfaceFactory::~QvisAnnotationObjectInterfaceFactory
//
// Purpose:
// Destructor for the QvisAnnotationObjectInterfaceFactory class.
//
// Programmer: Brad Whitlock
// Creation: Fri Oct 31 09:31:50 PDT 2003
//
// Modifications:
//
// ****************************************************************************
QvisAnnotationObjectInterfaceFactory::~QvisAnnotationObjectInterfaceFactory()
{
}
// ****************************************************************************
// Method: QvisAnnotationObjectInterfaceFactory::GetMaxInterfaces
//
// Purpose:
// Returns the maximum number of interfaces that the factory creates.
//
// Programmer: Brad Whitlock
// Creation: Fri Oct 31 09:31:50 PDT 2003
//
// Modifications:
// Brad Whitlock, Tue Jun 28 13:32:58 PST 2005
// Made it return 8.
//
// Brad Whitlock, Tue Mar 20 14:38:57 PST 2007
// Made it return MaxAnnotationType.
//
// ****************************************************************************
int
QvisAnnotationObjectInterfaceFactory::GetMaxInterfaces() const
{
return (int)AnnotationObject::MaxAnnotationType;
}
// ****************************************************************************
// Method: QvisAnnotationObjectInterfaceFactory::CreateInterface
//
// Purpose:
// Creates an interface and returns it.
//
// Arguments:
// i : The index of the interface to create.
// parent : The parent widget for the interface.
//
// Returns: A pointer to the new interface or 0 if no interface was created.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation: Fri Oct 31 09:32:56 PDT 2003
//
// Modifications:
// Brad Whitlock, Tue Jun 28 12:09:55 PDT 2005
// Added John Anderson's image and line2d annotation interfaces.
//
// Brad Whitlock, Tue Mar 20 14:13:00 PST 2007
// Added legend attributes interface.
//
// Brad Whitlock, Wed Nov 7 17:09:34 PST 2007
// Added text 3d.
//
// ****************************************************************************
QvisAnnotationObjectInterface *
QvisAnnotationObjectInterfaceFactory::CreateInterface(
AnnotationObject::AnnotationType i, QWidget *parent) const
{
QvisAnnotationObjectInterface *retval = 0;
switch(i)
{
case AnnotationObject::Text2D:
retval = new QvisText2DInterface(parent);
break;
case AnnotationObject::Text3D:
retval = new QvisText3DInterface(parent);
break;
case AnnotationObject::TimeSlider:
retval = new QvisTimeSliderInterface(parent);
break;
case AnnotationObject::Line2D:
retval = new QvisLine2DInterface(parent);
break;
case AnnotationObject::Line3D:
retval = new QvisLine3DInterface(parent);
break;
case AnnotationObject::Arrow2D:
// Nothing yet
break;
case AnnotationObject::Arrow3D:
// Nothing yet
break;
case AnnotationObject::Box:
// Nothing yet
break;
case AnnotationObject::Image:
retval = new QvisImageAnnotationInterface(parent);
break;
case AnnotationObject::LegendAttributes:
retval = new QvisLegendAttributesInterface(parent);
break;
default:
debug1 << "QvisAnnotationObjectInterfaceFactory::CreateInterface:"
<< " invalid index=" << (int)i << endl;
break;
}
return retval;
}
|
91f801acbf79cf0c06b859472eba6bb1f7944d84
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/native_client/src/public/nacl_desc.h
|
47b7b85286b2b03469b7591e84cae4ae69409846
|
[
"BSD-3-Clause",
"Zlib",
"Classpath-exception-2.0",
"BSD-Source-Code",
"LZMA-exception",
"LicenseRef-scancode-unicode",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-intel-osl-1993",
"HPND-sell-variant",
"ICU",
"LicenseRef-scancode-protobuf",
"bzip2-1.0.6",
"Spencer-94",
"NCSA",
"LicenseRef-scancode-nilsson-historical",
"CC0-1.0",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"NTP",
"GPL-2.0-only",
"LicenseRef-scancode-other-permissive",
"GPL-3.0-only",
"GFDL-1.1-only",
"W3C",
"LicenseRef-scancode-python-cwi",
"GCC-exception-3.1",
"BSL-1.0",
"Python-2.0",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"CPL-1.0",
"GFDL-1.1-or-later",
"W3C-19980720",
"LGPL-2.0-only",
"LicenseRef-scancode-amd-historical",
"LicenseRef-scancode-ietf",
"SAX-PD",
"LicenseRef-scancode-x11-hanson",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"dtoa",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"PSF-2.0",
"LicenseRef-scancode-newlib-historical",
"LicenseRef-scancode-generic-exception",
"SMLNJ",
"HP-1986",
"LicenseRef-scancode-free-unknown",
"SunPro",
"MPL-1.1"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 2,204
|
h
|
nacl_desc.h
|
/*
* Copyright (c) 2014 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef NATIVE_CLIENT_SRC_PUBLIC_NACL_DESC_H_
#define NATIVE_CLIENT_SRC_PUBLIC_NACL_DESC_H_ 1
#include "native_client/src/include/build_config.h"
#include "native_client/src/include/nacl_base.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/public/imc_types.h"
#if NACL_OSX
#include <mach/mach.h>
#endif
EXTERN_C_BEGIN
struct NaClDesc;
/*
* Increments the reference count of |desc|. Returns |desc|.
*/
struct NaClDesc *NaClDescRef(struct NaClDesc *desc);
/*
* Decrements the reference count of |desc|. If the reference count
* reaches zero, this will call |desc|'s destructor and free |desc|.
*/
void NaClDescUnref(struct NaClDesc *desc);
/*
* Create a NaClDesc for a NaClHandle which has reliable identity information.
* That identity can be used for future validation caching.
*
* If the file_path string is empty, this returns a NaClDesc that is not marked
* as validation-cacheable.
*
* On success, returns a new read-only NaClDesc that uses the passed handle,
* setting file path information internally.
* On failure, returns NULL.
*/
struct NaClDesc *NaClDescCreateWithFilePathMetadata(NaClHandle handle,
const char *file_path);
/*
* NaClDescIoMakeFromHandle() takes ownership of the |handle| argument
* -- when the returned NaClDesc object is destroyed (when the
* refcount goes to 0), the handle will be closed. The |flags|
* argument should be one of NACL_ABI_O_RDONLY, NACL_ABI_O_RDWR,
* NACL_ABI_O_WRONLY possibly bitwise ORed with NACL_ABI_O_APPEND.
*/
struct NaClDesc *NaClDescIoMakeFromHandle(NaClHandle handle,
int flags) NACL_WUR;
struct NaClDesc *NaClDescImcShmMake(NaClHandle handle, int64_t size) NACL_WUR;
#if NACL_OSX
struct NaClDesc *NaClDescImcShmMachMake(mach_port_t handle,
int64_t size) NACL_WUR;
#endif
struct NaClDesc *NaClDescSyncSocketMake(NaClHandle handle) NACL_WUR;
EXTERN_C_END
#endif
|
ca0ecbab43967b398cc7c586729e1c8905f9a066
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/tests/usr.bin/xlint/lint1/msg_330.c
|
ab4191e22aa834294670308d28e06246722592b4
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 666
|
c
|
msg_330.c
|
/* $NetBSD: msg_330.c,v 1.8 2023/08/02 18:51:25 rillig Exp $ */
# 3 "msg_330.c"
// Test for message: operand of '%s' must be bool, not '%s' [330]
//
// See d_c99_bool_strict.c for many more examples.
/* lint1-extra-flags: -T -X 351 */
typedef _Bool bool;
void
called(bool);
/*ARGSUSED*/
void
example(bool b, char c, int i)
{
called(!b);
/* expect+2: error: operand of '!' must be bool, not 'char' [330] */
/* expect+1: error: parameter 1 expects '_Bool', gets passed 'int' [334] */
called(!c);
/* expect+2: error: operand of '!' must be bool, not 'int' [330] */
/* expect+1: error: parameter 1 expects '_Bool', gets passed 'int' [334] */
called(!i);
}
|
90061d43d04e06502b68b4f5a50330a708cd23a6
|
73fbb7c1c93f53c9499e83f13c5ed8e4d4ce9d4a
|
/tests/kvasir-tests/perl/perlapi.h
|
5a5df61f51127d4a7141d52622fce524c3954ed4
|
[
"MIT"
] |
permissive
|
codespecs/daikon
|
8cccbaa7cce77d88160ae368054d9ef74043d465
|
62109d49852676657ce3205283cebbb46456425c
|
refs/heads/master
| 2023-09-01T19:45:13.280344
| 2023-08-22T03:21:40
| 2023-08-22T03:21:40
| 37,424,689
| 183
| 56
|
NOASSERTION
| 2023-08-22T03:21:41
| 2015-06-14T18:40:55
|
C
|
UTF-8
|
C
| false
| false
| 36,093
|
h
|
perlapi.h
|
/*
* perlapi.h
*
* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
* !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
* This file is built by embed.pl from data in embed.fnc, embed.pl,
* pp.sym, intrpvar.h, perlvars.h and thrdvar.h.
* Any changes made here will be lost!
*
* Edit those files and run 'make regen_headers' to effect changes.
*/
/* declare accessor functions for Perl variables */
#ifndef __perlapi_h__
#define __perlapi_h__
#if defined (MULTIPLICITY)
START_EXTERN_C
#undef PERLVAR
#undef PERLVARA
#undef PERLVARI
#undef PERLVARIC
#define PERLVAR(v,t) EXTERN_C t* Perl_##v##_ptr(pTHX);
#define PERLVARA(v,n,t) typedef t PL_##v##_t[n]; \
EXTERN_C PL_##v##_t* Perl_##v##_ptr(pTHX);
#define PERLVARI(v,t,i) PERLVAR(v,t)
#define PERLVARIC(v,t,i) PERLVAR(v, const t)
#include "thrdvar.h"
#include "intrpvar.h"
#include "perlvars.h"
#undef PERLVAR
#undef PERLVARA
#undef PERLVARI
#undef PERLVARIC
END_EXTERN_C
#if defined(PERL_CORE)
/* accessor functions for Perl variables (provide binary compatibility) */
/* these need to be mentioned here, or most linkers won't put them in
the perl executable */
#ifndef PERL_NO_FORCE_LINK
START_EXTERN_C
#ifndef DOINIT
EXT void *PL_force_link_funcs[];
#else
EXT void *PL_force_link_funcs[] = {
#undef PERLVAR
#undef PERLVARA
#undef PERLVARI
#undef PERLVARIC
#define PERLVAR(v,t) (void*)Perl_##v##_ptr,
#define PERLVARA(v,n,t) PERLVAR(v,t)
#define PERLVARI(v,t,i) PERLVAR(v,t)
#define PERLVARIC(v,t,i) PERLVAR(v,t)
#include "thrdvar.h"
#include "intrpvar.h"
#include "perlvars.h"
#undef PERLVAR
#undef PERLVARA
#undef PERLVARI
#undef PERLVARIC
};
#endif /* DOINIT */
END_EXTERN_C
#endif /* PERL_NO_FORCE_LINK */
#else /* !PERL_CORE */
#undef PL_Argv
#define PL_Argv (*Perl_IArgv_ptr(aTHX))
#undef PL_BINCOMPAT0
#define PL_BINCOMPAT0 (*Perl_IBINCOMPAT0_ptr(aTHX))
#undef PL_Cmd
#define PL_Cmd (*Perl_ICmd_ptr(aTHX))
#undef PL_DBcv
#define PL_DBcv (*Perl_IDBcv_ptr(aTHX))
#undef PL_DBgv
#define PL_DBgv (*Perl_IDBgv_ptr(aTHX))
#undef PL_DBline
#define PL_DBline (*Perl_IDBline_ptr(aTHX))
#undef PL_DBsignal
#define PL_DBsignal (*Perl_IDBsignal_ptr(aTHX))
#undef PL_DBsingle
#define PL_DBsingle (*Perl_IDBsingle_ptr(aTHX))
#undef PL_DBsub
#define PL_DBsub (*Perl_IDBsub_ptr(aTHX))
#undef PL_DBtrace
#define PL_DBtrace (*Perl_IDBtrace_ptr(aTHX))
#undef PL_Dir
#define PL_Dir (*Perl_IDir_ptr(aTHX))
#undef PL_Env
#define PL_Env (*Perl_IEnv_ptr(aTHX))
#undef PL_LIO
#define PL_LIO (*Perl_ILIO_ptr(aTHX))
#undef PL_Mem
#define PL_Mem (*Perl_IMem_ptr(aTHX))
#undef PL_MemParse
#define PL_MemParse (*Perl_IMemParse_ptr(aTHX))
#undef PL_MemShared
#define PL_MemShared (*Perl_IMemShared_ptr(aTHX))
#undef PL_OpPtr
#define PL_OpPtr (*Perl_IOpPtr_ptr(aTHX))
#undef PL_OpSlab
#define PL_OpSlab (*Perl_IOpSlab_ptr(aTHX))
#undef PL_OpSpace
#define PL_OpSpace (*Perl_IOpSpace_ptr(aTHX))
#undef PL_Proc
#define PL_Proc (*Perl_IProc_ptr(aTHX))
#undef PL_Sock
#define PL_Sock (*Perl_ISock_ptr(aTHX))
#undef PL_StdIO
#define PL_StdIO (*Perl_IStdIO_ptr(aTHX))
#undef PL_amagic_generation
#define PL_amagic_generation (*Perl_Iamagic_generation_ptr(aTHX))
#undef PL_an
#define PL_an (*Perl_Ian_ptr(aTHX))
#undef PL_argvgv
#define PL_argvgv (*Perl_Iargvgv_ptr(aTHX))
#undef PL_argvout_stack
#define PL_argvout_stack (*Perl_Iargvout_stack_ptr(aTHX))
#undef PL_argvoutgv
#define PL_argvoutgv (*Perl_Iargvoutgv_ptr(aTHX))
#undef PL_basetime
#define PL_basetime (*Perl_Ibasetime_ptr(aTHX))
#undef PL_beginav
#define PL_beginav (*Perl_Ibeginav_ptr(aTHX))
#undef PL_beginav_save
#define PL_beginav_save (*Perl_Ibeginav_save_ptr(aTHX))
#undef PL_bitcount
#define PL_bitcount (*Perl_Ibitcount_ptr(aTHX))
#undef PL_bufend
#define PL_bufend (*Perl_Ibufend_ptr(aTHX))
#undef PL_bufptr
#define PL_bufptr (*Perl_Ibufptr_ptr(aTHX))
#undef PL_checkav
#define PL_checkav (*Perl_Icheckav_ptr(aTHX))
#undef PL_checkav_save
#define PL_checkav_save (*Perl_Icheckav_save_ptr(aTHX))
#undef PL_clocktick
#define PL_clocktick (*Perl_Iclocktick_ptr(aTHX))
#undef PL_collation_ix
#define PL_collation_ix (*Perl_Icollation_ix_ptr(aTHX))
#undef PL_collation_name
#define PL_collation_name (*Perl_Icollation_name_ptr(aTHX))
#undef PL_collation_standard
#define PL_collation_standard (*Perl_Icollation_standard_ptr(aTHX))
#undef PL_collxfrm_base
#define PL_collxfrm_base (*Perl_Icollxfrm_base_ptr(aTHX))
#undef PL_collxfrm_mult
#define PL_collxfrm_mult (*Perl_Icollxfrm_mult_ptr(aTHX))
#undef PL_compcv
#define PL_compcv (*Perl_Icompcv_ptr(aTHX))
#undef PL_compiling
#define PL_compiling (*Perl_Icompiling_ptr(aTHX))
#undef PL_comppad_name
#define PL_comppad_name (*Perl_Icomppad_name_ptr(aTHX))
#undef PL_comppad_name_fill
#define PL_comppad_name_fill (*Perl_Icomppad_name_fill_ptr(aTHX))
#undef PL_comppad_name_floor
#define PL_comppad_name_floor (*Perl_Icomppad_name_floor_ptr(aTHX))
#undef PL_cop_seqmax
#define PL_cop_seqmax (*Perl_Icop_seqmax_ptr(aTHX))
#undef PL_copline
#define PL_copline (*Perl_Icopline_ptr(aTHX))
#undef PL_cred_mutex
#define PL_cred_mutex (*Perl_Icred_mutex_ptr(aTHX))
#undef PL_cryptseen
#define PL_cryptseen (*Perl_Icryptseen_ptr(aTHX))
#undef PL_cshlen
#define PL_cshlen (*Perl_Icshlen_ptr(aTHX))
#undef PL_cshname
#define PL_cshname (*Perl_Icshname_ptr(aTHX))
#undef PL_curcopdb
#define PL_curcopdb (*Perl_Icurcopdb_ptr(aTHX))
#undef PL_curstname
#define PL_curstname (*Perl_Icurstname_ptr(aTHX))
#undef PL_curthr
#define PL_curthr (*Perl_Icurthr_ptr(aTHX))
#undef PL_custom_op_descs
#define PL_custom_op_descs (*Perl_Icustom_op_descs_ptr(aTHX))
#undef PL_custom_op_names
#define PL_custom_op_names (*Perl_Icustom_op_names_ptr(aTHX))
#undef PL_dbargs
#define PL_dbargs (*Perl_Idbargs_ptr(aTHX))
#undef PL_debstash
#define PL_debstash (*Perl_Idebstash_ptr(aTHX))
#undef PL_debug
#define PL_debug (*Perl_Idebug_ptr(aTHX))
#undef PL_debug_pad
#define PL_debug_pad (*Perl_Idebug_pad_ptr(aTHX))
#undef PL_def_layerlist
#define PL_def_layerlist (*Perl_Idef_layerlist_ptr(aTHX))
#undef PL_defgv
#define PL_defgv (*Perl_Idefgv_ptr(aTHX))
#undef PL_diehook
#define PL_diehook (*Perl_Idiehook_ptr(aTHX))
#undef PL_doextract
#define PL_doextract (*Perl_Idoextract_ptr(aTHX))
#undef PL_doswitches
#define PL_doswitches (*Perl_Idoswitches_ptr(aTHX))
#undef PL_dowarn
#define PL_dowarn (*Perl_Idowarn_ptr(aTHX))
#undef PL_e_script
#define PL_e_script (*Perl_Ie_script_ptr(aTHX))
#undef PL_egid
#define PL_egid (*Perl_Iegid_ptr(aTHX))
#undef PL_encoding
#define PL_encoding (*Perl_Iencoding_ptr(aTHX))
#undef PL_endav
#define PL_endav (*Perl_Iendav_ptr(aTHX))
#undef PL_envgv
#define PL_envgv (*Perl_Ienvgv_ptr(aTHX))
#undef PL_errgv
#define PL_errgv (*Perl_Ierrgv_ptr(aTHX))
#undef PL_error_count
#define PL_error_count (*Perl_Ierror_count_ptr(aTHX))
#undef PL_euid
#define PL_euid (*Perl_Ieuid_ptr(aTHX))
#undef PL_eval_cond
#define PL_eval_cond (*Perl_Ieval_cond_ptr(aTHX))
#undef PL_eval_mutex
#define PL_eval_mutex (*Perl_Ieval_mutex_ptr(aTHX))
#undef PL_eval_owner
#define PL_eval_owner (*Perl_Ieval_owner_ptr(aTHX))
#undef PL_eval_root
#define PL_eval_root (*Perl_Ieval_root_ptr(aTHX))
#undef PL_eval_start
#define PL_eval_start (*Perl_Ieval_start_ptr(aTHX))
#undef PL_evalseq
#define PL_evalseq (*Perl_Ievalseq_ptr(aTHX))
#undef PL_exit_flags
#define PL_exit_flags (*Perl_Iexit_flags_ptr(aTHX))
#undef PL_exitlist
#define PL_exitlist (*Perl_Iexitlist_ptr(aTHX))
#undef PL_exitlistlen
#define PL_exitlistlen (*Perl_Iexitlistlen_ptr(aTHX))
#undef PL_expect
#define PL_expect (*Perl_Iexpect_ptr(aTHX))
#undef PL_fdpid
#define PL_fdpid (*Perl_Ifdpid_ptr(aTHX))
#undef PL_fdpid_mutex
#define PL_fdpid_mutex (*Perl_Ifdpid_mutex_ptr(aTHX))
#undef PL_fdscript
#define PL_fdscript (*Perl_Ifdscript_ptr(aTHX))
#undef PL_filemode
#define PL_filemode (*Perl_Ifilemode_ptr(aTHX))
#undef PL_forkprocess
#define PL_forkprocess (*Perl_Iforkprocess_ptr(aTHX))
#undef PL_formfeed
#define PL_formfeed (*Perl_Iformfeed_ptr(aTHX))
#undef PL_generation
#define PL_generation (*Perl_Igeneration_ptr(aTHX))
#undef PL_gensym
#define PL_gensym (*Perl_Igensym_ptr(aTHX))
#undef PL_gid
#define PL_gid (*Perl_Igid_ptr(aTHX))
#undef PL_glob_index
#define PL_glob_index (*Perl_Iglob_index_ptr(aTHX))
#undef PL_globalstash
#define PL_globalstash (*Perl_Iglobalstash_ptr(aTHX))
#undef PL_hash_seed
#define PL_hash_seed (*Perl_Ihash_seed_ptr(aTHX))
#undef PL_hash_seed_set
#define PL_hash_seed_set (*Perl_Ihash_seed_set_ptr(aTHX))
#undef PL_he_arenaroot
#define PL_he_arenaroot (*Perl_Ihe_arenaroot_ptr(aTHX))
#undef PL_he_root
#define PL_he_root (*Perl_Ihe_root_ptr(aTHX))
#undef PL_hintgv
#define PL_hintgv (*Perl_Ihintgv_ptr(aTHX))
#undef PL_hints
#define PL_hints (*Perl_Ihints_ptr(aTHX))
#undef PL_in_clean_all
#define PL_in_clean_all (*Perl_Iin_clean_all_ptr(aTHX))
#undef PL_in_clean_objs
#define PL_in_clean_objs (*Perl_Iin_clean_objs_ptr(aTHX))
#undef PL_in_load_module
#define PL_in_load_module (*Perl_Iin_load_module_ptr(aTHX))
#undef PL_in_my
#define PL_in_my (*Perl_Iin_my_ptr(aTHX))
#undef PL_in_my_stash
#define PL_in_my_stash (*Perl_Iin_my_stash_ptr(aTHX))
#undef PL_incgv
#define PL_incgv (*Perl_Iincgv_ptr(aTHX))
#undef PL_initav
#define PL_initav (*Perl_Iinitav_ptr(aTHX))
#undef PL_inplace
#define PL_inplace (*Perl_Iinplace_ptr(aTHX))
#undef PL_known_layers
#define PL_known_layers (*Perl_Iknown_layers_ptr(aTHX))
#undef PL_last_lop
#define PL_last_lop (*Perl_Ilast_lop_ptr(aTHX))
#undef PL_last_lop_op
#define PL_last_lop_op (*Perl_Ilast_lop_op_ptr(aTHX))
#undef PL_last_swash_hv
#define PL_last_swash_hv (*Perl_Ilast_swash_hv_ptr(aTHX))
#undef PL_last_swash_key
#define PL_last_swash_key (*Perl_Ilast_swash_key_ptr(aTHX))
#undef PL_last_swash_klen
#define PL_last_swash_klen (*Perl_Ilast_swash_klen_ptr(aTHX))
#undef PL_last_swash_slen
#define PL_last_swash_slen (*Perl_Ilast_swash_slen_ptr(aTHX))
#undef PL_last_swash_tmps
#define PL_last_swash_tmps (*Perl_Ilast_swash_tmps_ptr(aTHX))
#undef PL_last_uni
#define PL_last_uni (*Perl_Ilast_uni_ptr(aTHX))
#undef PL_lastfd
#define PL_lastfd (*Perl_Ilastfd_ptr(aTHX))
#undef PL_laststatval
#define PL_laststatval (*Perl_Ilaststatval_ptr(aTHX))
#undef PL_laststype
#define PL_laststype (*Perl_Ilaststype_ptr(aTHX))
#undef PL_lex_brackets
#define PL_lex_brackets (*Perl_Ilex_brackets_ptr(aTHX))
#undef PL_lex_brackstack
#define PL_lex_brackstack (*Perl_Ilex_brackstack_ptr(aTHX))
#undef PL_lex_casemods
#define PL_lex_casemods (*Perl_Ilex_casemods_ptr(aTHX))
#undef PL_lex_casestack
#define PL_lex_casestack (*Perl_Ilex_casestack_ptr(aTHX))
#undef PL_lex_defer
#define PL_lex_defer (*Perl_Ilex_defer_ptr(aTHX))
#undef PL_lex_dojoin
#define PL_lex_dojoin (*Perl_Ilex_dojoin_ptr(aTHX))
#undef PL_lex_expect
#define PL_lex_expect (*Perl_Ilex_expect_ptr(aTHX))
#undef PL_lex_formbrack
#define PL_lex_formbrack (*Perl_Ilex_formbrack_ptr(aTHX))
#undef PL_lex_inpat
#define PL_lex_inpat (*Perl_Ilex_inpat_ptr(aTHX))
#undef PL_lex_inwhat
#define PL_lex_inwhat (*Perl_Ilex_inwhat_ptr(aTHX))
#undef PL_lex_op
#define PL_lex_op (*Perl_Ilex_op_ptr(aTHX))
#undef PL_lex_repl
#define PL_lex_repl (*Perl_Ilex_repl_ptr(aTHX))
#undef PL_lex_starts
#define PL_lex_starts (*Perl_Ilex_starts_ptr(aTHX))
#undef PL_lex_state
#define PL_lex_state (*Perl_Ilex_state_ptr(aTHX))
#undef PL_lex_stuff
#define PL_lex_stuff (*Perl_Ilex_stuff_ptr(aTHX))
#undef PL_lineary
#define PL_lineary (*Perl_Ilineary_ptr(aTHX))
#undef PL_linestart
#define PL_linestart (*Perl_Ilinestart_ptr(aTHX))
#undef PL_linestr
#define PL_linestr (*Perl_Ilinestr_ptr(aTHX))
#undef PL_localpatches
#define PL_localpatches (*Perl_Ilocalpatches_ptr(aTHX))
#undef PL_lockhook
#define PL_lockhook (*Perl_Ilockhook_ptr(aTHX))
#undef PL_main_cv
#define PL_main_cv (*Perl_Imain_cv_ptr(aTHX))
#undef PL_main_root
#define PL_main_root (*Perl_Imain_root_ptr(aTHX))
#undef PL_main_start
#define PL_main_start (*Perl_Imain_start_ptr(aTHX))
#undef PL_max_intro_pending
#define PL_max_intro_pending (*Perl_Imax_intro_pending_ptr(aTHX))
#undef PL_maxo
#define PL_maxo (*Perl_Imaxo_ptr(aTHX))
#undef PL_maxsysfd
#define PL_maxsysfd (*Perl_Imaxsysfd_ptr(aTHX))
#undef PL_mess_sv
#define PL_mess_sv (*Perl_Imess_sv_ptr(aTHX))
#undef PL_min_intro_pending
#define PL_min_intro_pending (*Perl_Imin_intro_pending_ptr(aTHX))
#undef PL_minus_F
#define PL_minus_F (*Perl_Iminus_F_ptr(aTHX))
#undef PL_minus_a
#define PL_minus_a (*Perl_Iminus_a_ptr(aTHX))
#undef PL_minus_c
#define PL_minus_c (*Perl_Iminus_c_ptr(aTHX))
#undef PL_minus_l
#define PL_minus_l (*Perl_Iminus_l_ptr(aTHX))
#undef PL_minus_n
#define PL_minus_n (*Perl_Iminus_n_ptr(aTHX))
#undef PL_minus_p
#define PL_minus_p (*Perl_Iminus_p_ptr(aTHX))
#undef PL_modglobal
#define PL_modglobal (*Perl_Imodglobal_ptr(aTHX))
#undef PL_multi_close
#define PL_multi_close (*Perl_Imulti_close_ptr(aTHX))
#undef PL_multi_end
#define PL_multi_end (*Perl_Imulti_end_ptr(aTHX))
#undef PL_multi_open
#define PL_multi_open (*Perl_Imulti_open_ptr(aTHX))
#undef PL_multi_start
#define PL_multi_start (*Perl_Imulti_start_ptr(aTHX))
#undef PL_multiline
#define PL_multiline (*Perl_Imultiline_ptr(aTHX))
#undef PL_nexttoke
#define PL_nexttoke (*Perl_Inexttoke_ptr(aTHX))
#undef PL_nexttype
#define PL_nexttype (*Perl_Inexttype_ptr(aTHX))
#undef PL_nextval
#define PL_nextval (*Perl_Inextval_ptr(aTHX))
#undef PL_nice_chunk
#define PL_nice_chunk (*Perl_Inice_chunk_ptr(aTHX))
#undef PL_nice_chunk_size
#define PL_nice_chunk_size (*Perl_Inice_chunk_size_ptr(aTHX))
#undef PL_nomemok
#define PL_nomemok (*Perl_Inomemok_ptr(aTHX))
#undef PL_nthreads
#define PL_nthreads (*Perl_Inthreads_ptr(aTHX))
#undef PL_nthreads_cond
#define PL_nthreads_cond (*Perl_Inthreads_cond_ptr(aTHX))
#undef PL_nullstash
#define PL_nullstash (*Perl_Inullstash_ptr(aTHX))
#undef PL_numeric_compat1
#define PL_numeric_compat1 (*Perl_Inumeric_compat1_ptr(aTHX))
#undef PL_numeric_local
#define PL_numeric_local (*Perl_Inumeric_local_ptr(aTHX))
#undef PL_numeric_name
#define PL_numeric_name (*Perl_Inumeric_name_ptr(aTHX))
#undef PL_numeric_radix_sv
#define PL_numeric_radix_sv (*Perl_Inumeric_radix_sv_ptr(aTHX))
#undef PL_numeric_standard
#define PL_numeric_standard (*Perl_Inumeric_standard_ptr(aTHX))
#undef PL_ofmt
#define PL_ofmt (*Perl_Iofmt_ptr(aTHX))
#undef PL_oldbufptr
#define PL_oldbufptr (*Perl_Ioldbufptr_ptr(aTHX))
#undef PL_oldname
#define PL_oldname (*Perl_Ioldname_ptr(aTHX))
#undef PL_oldoldbufptr
#define PL_oldoldbufptr (*Perl_Ioldoldbufptr_ptr(aTHX))
#undef PL_op_mask
#define PL_op_mask (*Perl_Iop_mask_ptr(aTHX))
#undef PL_op_seqmax
#define PL_op_seqmax (*Perl_Iop_seqmax_ptr(aTHX))
#undef PL_origalen
#define PL_origalen (*Perl_Iorigalen_ptr(aTHX))
#undef PL_origargc
#define PL_origargc (*Perl_Iorigargc_ptr(aTHX))
#undef PL_origargv
#define PL_origargv (*Perl_Iorigargv_ptr(aTHX))
#undef PL_origenviron
#define PL_origenviron (*Perl_Iorigenviron_ptr(aTHX))
#undef PL_origfilename
#define PL_origfilename (*Perl_Iorigfilename_ptr(aTHX))
#undef PL_ors_sv
#define PL_ors_sv (*Perl_Iors_sv_ptr(aTHX))
#undef PL_osname
#define PL_osname (*Perl_Iosname_ptr(aTHX))
#undef PL_pad_reset_pending
#define PL_pad_reset_pending (*Perl_Ipad_reset_pending_ptr(aTHX))
#undef PL_padix
#define PL_padix (*Perl_Ipadix_ptr(aTHX))
#undef PL_padix_floor
#define PL_padix_floor (*Perl_Ipadix_floor_ptr(aTHX))
#undef PL_patchlevel
#define PL_patchlevel (*Perl_Ipatchlevel_ptr(aTHX))
#undef PL_pending_ident
#define PL_pending_ident (*Perl_Ipending_ident_ptr(aTHX))
#undef PL_perl_destruct_level
#define PL_perl_destruct_level (*Perl_Iperl_destruct_level_ptr(aTHX))
#undef PL_perldb
#define PL_perldb (*Perl_Iperldb_ptr(aTHX))
#undef PL_perlio
#define PL_perlio (*Perl_Iperlio_ptr(aTHX))
#undef PL_pidstatus
#define PL_pidstatus (*Perl_Ipidstatus_ptr(aTHX))
#undef PL_ppid
#define PL_ppid (*Perl_Ippid_ptr(aTHX))
#undef PL_preambleav
#define PL_preambleav (*Perl_Ipreambleav_ptr(aTHX))
#undef PL_preambled
#define PL_preambled (*Perl_Ipreambled_ptr(aTHX))
#undef PL_preprocess
#define PL_preprocess (*Perl_Ipreprocess_ptr(aTHX))
#undef PL_profiledata
#define PL_profiledata (*Perl_Iprofiledata_ptr(aTHX))
#undef PL_psig_name
#define PL_psig_name (*Perl_Ipsig_name_ptr(aTHX))
#undef PL_psig_pend
#define PL_psig_pend (*Perl_Ipsig_pend_ptr(aTHX))
#undef PL_psig_ptr
#define PL_psig_ptr (*Perl_Ipsig_ptr_ptr(aTHX))
#undef PL_ptr_table
#define PL_ptr_table (*Perl_Iptr_table_ptr(aTHX))
#undef PL_reentrant_buffer
#define PL_reentrant_buffer (*Perl_Ireentrant_buffer_ptr(aTHX))
#undef PL_reentrant_retint
#define PL_reentrant_retint (*Perl_Ireentrant_retint_ptr(aTHX))
#undef PL_regex_pad
#define PL_regex_pad (*Perl_Iregex_pad_ptr(aTHX))
#undef PL_regex_padav
#define PL_regex_padav (*Perl_Iregex_padav_ptr(aTHX))
#undef PL_rehash_seed
#define PL_rehash_seed (*Perl_Irehash_seed_ptr(aTHX))
#undef PL_rehash_seed_set
#define PL_rehash_seed_set (*Perl_Irehash_seed_set_ptr(aTHX))
#undef PL_replgv
#define PL_replgv (*Perl_Ireplgv_ptr(aTHX))
#undef PL_rsfp
#define PL_rsfp (*Perl_Irsfp_ptr(aTHX))
#undef PL_rsfp_filters
#define PL_rsfp_filters (*Perl_Irsfp_filters_ptr(aTHX))
#undef PL_runops
#define PL_runops (*Perl_Irunops_ptr(aTHX))
#undef PL_runops_dbg
#define PL_runops_dbg (*Perl_Irunops_dbg_ptr(aTHX))
#undef PL_runops_std
#define PL_runops_std (*Perl_Irunops_std_ptr(aTHX))
#undef PL_savebegin
#define PL_savebegin (*Perl_Isavebegin_ptr(aTHX))
#undef PL_sawampersand
#define PL_sawampersand (*Perl_Isawampersand_ptr(aTHX))
#undef PL_sh_path_compat
#define PL_sh_path_compat (*Perl_Ish_path_compat_ptr(aTHX))
#undef PL_sharehook
#define PL_sharehook (*Perl_Isharehook_ptr(aTHX))
#undef PL_sig_pending
#define PL_sig_pending (*Perl_Isig_pending_ptr(aTHX))
#undef PL_sighandlerp
#define PL_sighandlerp (*Perl_Isighandlerp_ptr(aTHX))
#undef PL_signals
#define PL_signals (*Perl_Isignals_ptr(aTHX))
#undef PL_sort_RealCmp
#define PL_sort_RealCmp (*Perl_Isort_RealCmp_ptr(aTHX))
#undef PL_splitstr
#define PL_splitstr (*Perl_Isplitstr_ptr(aTHX))
#undef PL_srand_called
#define PL_srand_called (*Perl_Isrand_called_ptr(aTHX))
#undef PL_stashcache
#define PL_stashcache (*Perl_Istashcache_ptr(aTHX))
#undef PL_statusvalue
#define PL_statusvalue (*Perl_Istatusvalue_ptr(aTHX))
#undef PL_statusvalue_vms
#define PL_statusvalue_vms (*Perl_Istatusvalue_vms_ptr(aTHX))
#undef PL_stderrgv
#define PL_stderrgv (*Perl_Istderrgv_ptr(aTHX))
#undef PL_stdingv
#define PL_stdingv (*Perl_Istdingv_ptr(aTHX))
#undef PL_strtab
#define PL_strtab (*Perl_Istrtab_ptr(aTHX))
#undef PL_strtab_mutex
#define PL_strtab_mutex (*Perl_Istrtab_mutex_ptr(aTHX))
#undef PL_sub_generation
#define PL_sub_generation (*Perl_Isub_generation_ptr(aTHX))
#undef PL_sublex_info
#define PL_sublex_info (*Perl_Isublex_info_ptr(aTHX))
#undef PL_subline
#define PL_subline (*Perl_Isubline_ptr(aTHX))
#undef PL_subname
#define PL_subname (*Perl_Isubname_ptr(aTHX))
#undef PL_suidscript
#define PL_suidscript (*Perl_Isuidscript_ptr(aTHX))
#undef PL_sv_arenaroot
#define PL_sv_arenaroot (*Perl_Isv_arenaroot_ptr(aTHX))
#undef PL_sv_count
#define PL_sv_count (*Perl_Isv_count_ptr(aTHX))
#undef PL_sv_lock_mutex
#define PL_sv_lock_mutex (*Perl_Isv_lock_mutex_ptr(aTHX))
#undef PL_sv_mutex
#define PL_sv_mutex (*Perl_Isv_mutex_ptr(aTHX))
#undef PL_sv_no
#define PL_sv_no (*Perl_Isv_no_ptr(aTHX))
#undef PL_sv_objcount
#define PL_sv_objcount (*Perl_Isv_objcount_ptr(aTHX))
#undef PL_sv_root
#define PL_sv_root (*Perl_Isv_root_ptr(aTHX))
#undef PL_sv_undef
#define PL_sv_undef (*Perl_Isv_undef_ptr(aTHX))
#undef PL_sv_yes
#define PL_sv_yes (*Perl_Isv_yes_ptr(aTHX))
#undef PL_svref_mutex
#define PL_svref_mutex (*Perl_Isvref_mutex_ptr(aTHX))
#undef PL_sys_intern
#define PL_sys_intern (*Perl_Isys_intern_ptr(aTHX))
#undef PL_taint_warn
#define PL_taint_warn (*Perl_Itaint_warn_ptr(aTHX))
#undef PL_tainting
#define PL_tainting (*Perl_Itainting_ptr(aTHX))
#undef PL_threadhook
#define PL_threadhook (*Perl_Ithreadhook_ptr(aTHX))
#undef PL_threadnum
#define PL_threadnum (*Perl_Ithreadnum_ptr(aTHX))
#undef PL_threads_mutex
#define PL_threads_mutex (*Perl_Ithreads_mutex_ptr(aTHX))
#undef PL_threadsv_names
#define PL_threadsv_names (*Perl_Ithreadsv_names_ptr(aTHX))
#undef PL_thrsv
#define PL_thrsv (*Perl_Ithrsv_ptr(aTHX))
#undef PL_tokenbuf
#define PL_tokenbuf (*Perl_Itokenbuf_ptr(aTHX))
#undef PL_uid
#define PL_uid (*Perl_Iuid_ptr(aTHX))
#undef PL_unicode
#define PL_unicode (*Perl_Iunicode_ptr(aTHX))
#undef PL_unlockhook
#define PL_unlockhook (*Perl_Iunlockhook_ptr(aTHX))
#undef PL_unsafe
#define PL_unsafe (*Perl_Iunsafe_ptr(aTHX))
#undef PL_utf8_alnum
#define PL_utf8_alnum (*Perl_Iutf8_alnum_ptr(aTHX))
#undef PL_utf8_alnumc
#define PL_utf8_alnumc (*Perl_Iutf8_alnumc_ptr(aTHX))
#undef PL_utf8_alpha
#define PL_utf8_alpha (*Perl_Iutf8_alpha_ptr(aTHX))
#undef PL_utf8_ascii
#define PL_utf8_ascii (*Perl_Iutf8_ascii_ptr(aTHX))
#undef PL_utf8_cntrl
#define PL_utf8_cntrl (*Perl_Iutf8_cntrl_ptr(aTHX))
#undef PL_utf8_digit
#define PL_utf8_digit (*Perl_Iutf8_digit_ptr(aTHX))
#undef PL_utf8_graph
#define PL_utf8_graph (*Perl_Iutf8_graph_ptr(aTHX))
#undef PL_utf8_idcont
#define PL_utf8_idcont (*Perl_Iutf8_idcont_ptr(aTHX))
#undef PL_utf8_idstart
#define PL_utf8_idstart (*Perl_Iutf8_idstart_ptr(aTHX))
#undef PL_utf8_lower
#define PL_utf8_lower (*Perl_Iutf8_lower_ptr(aTHX))
#undef PL_utf8_mark
#define PL_utf8_mark (*Perl_Iutf8_mark_ptr(aTHX))
#undef PL_utf8_print
#define PL_utf8_print (*Perl_Iutf8_print_ptr(aTHX))
#undef PL_utf8_punct
#define PL_utf8_punct (*Perl_Iutf8_punct_ptr(aTHX))
#undef PL_utf8_space
#define PL_utf8_space (*Perl_Iutf8_space_ptr(aTHX))
#undef PL_utf8_tofold
#define PL_utf8_tofold (*Perl_Iutf8_tofold_ptr(aTHX))
#undef PL_utf8_tolower
#define PL_utf8_tolower (*Perl_Iutf8_tolower_ptr(aTHX))
#undef PL_utf8_totitle
#define PL_utf8_totitle (*Perl_Iutf8_totitle_ptr(aTHX))
#undef PL_utf8_toupper
#define PL_utf8_toupper (*Perl_Iutf8_toupper_ptr(aTHX))
#undef PL_utf8_upper
#define PL_utf8_upper (*Perl_Iutf8_upper_ptr(aTHX))
#undef PL_utf8_xdigit
#define PL_utf8_xdigit (*Perl_Iutf8_xdigit_ptr(aTHX))
#undef PL_utf8locale
#define PL_utf8locale (*Perl_Iutf8locale_ptr(aTHX))
#undef PL_uudmap
#define PL_uudmap (*Perl_Iuudmap_ptr(aTHX))
#undef PL_warnhook
#define PL_warnhook (*Perl_Iwarnhook_ptr(aTHX))
#undef PL_widesyscalls
#define PL_widesyscalls (*Perl_Iwidesyscalls_ptr(aTHX))
#undef PL_xiv_arenaroot
#define PL_xiv_arenaroot (*Perl_Ixiv_arenaroot_ptr(aTHX))
#undef PL_xiv_root
#define PL_xiv_root (*Perl_Ixiv_root_ptr(aTHX))
#undef PL_xnv_arenaroot
#define PL_xnv_arenaroot (*Perl_Ixnv_arenaroot_ptr(aTHX))
#undef PL_xnv_root
#define PL_xnv_root (*Perl_Ixnv_root_ptr(aTHX))
#undef PL_xpv_arenaroot
#define PL_xpv_arenaroot (*Perl_Ixpv_arenaroot_ptr(aTHX))
#undef PL_xpv_root
#define PL_xpv_root (*Perl_Ixpv_root_ptr(aTHX))
#undef PL_xpvav_arenaroot
#define PL_xpvav_arenaroot (*Perl_Ixpvav_arenaroot_ptr(aTHX))
#undef PL_xpvav_root
#define PL_xpvav_root (*Perl_Ixpvav_root_ptr(aTHX))
#undef PL_xpvbm_arenaroot
#define PL_xpvbm_arenaroot (*Perl_Ixpvbm_arenaroot_ptr(aTHX))
#undef PL_xpvbm_root
#define PL_xpvbm_root (*Perl_Ixpvbm_root_ptr(aTHX))
#undef PL_xpvcv_arenaroot
#define PL_xpvcv_arenaroot (*Perl_Ixpvcv_arenaroot_ptr(aTHX))
#undef PL_xpvcv_root
#define PL_xpvcv_root (*Perl_Ixpvcv_root_ptr(aTHX))
#undef PL_xpvhv_arenaroot
#define PL_xpvhv_arenaroot (*Perl_Ixpvhv_arenaroot_ptr(aTHX))
#undef PL_xpvhv_root
#define PL_xpvhv_root (*Perl_Ixpvhv_root_ptr(aTHX))
#undef PL_xpviv_arenaroot
#define PL_xpviv_arenaroot (*Perl_Ixpviv_arenaroot_ptr(aTHX))
#undef PL_xpviv_root
#define PL_xpviv_root (*Perl_Ixpviv_root_ptr(aTHX))
#undef PL_xpvlv_arenaroot
#define PL_xpvlv_arenaroot (*Perl_Ixpvlv_arenaroot_ptr(aTHX))
#undef PL_xpvlv_root
#define PL_xpvlv_root (*Perl_Ixpvlv_root_ptr(aTHX))
#undef PL_xpvmg_arenaroot
#define PL_xpvmg_arenaroot (*Perl_Ixpvmg_arenaroot_ptr(aTHX))
#undef PL_xpvmg_root
#define PL_xpvmg_root (*Perl_Ixpvmg_root_ptr(aTHX))
#undef PL_xpvnv_arenaroot
#define PL_xpvnv_arenaroot (*Perl_Ixpvnv_arenaroot_ptr(aTHX))
#undef PL_xpvnv_root
#define PL_xpvnv_root (*Perl_Ixpvnv_root_ptr(aTHX))
#undef PL_xrv_arenaroot
#define PL_xrv_arenaroot (*Perl_Ixrv_arenaroot_ptr(aTHX))
#undef PL_xrv_root
#define PL_xrv_root (*Perl_Ixrv_root_ptr(aTHX))
#undef PL_yychar
#define PL_yychar (*Perl_Iyychar_ptr(aTHX))
#undef PL_yydebug
#define PL_yydebug (*Perl_Iyydebug_ptr(aTHX))
#undef PL_yyerrflag
#define PL_yyerrflag (*Perl_Iyyerrflag_ptr(aTHX))
#undef PL_yylval
#define PL_yylval (*Perl_Iyylval_ptr(aTHX))
#undef PL_yynerrs
#define PL_yynerrs (*Perl_Iyynerrs_ptr(aTHX))
#undef PL_yyval
#define PL_yyval (*Perl_Iyyval_ptr(aTHX))
#undef PL_Sv
#define PL_Sv (*Perl_TSv_ptr(aTHX))
#undef PL_Xpv
#define PL_Xpv (*Perl_TXpv_ptr(aTHX))
#undef PL_av_fetch_sv
#define PL_av_fetch_sv (*Perl_Tav_fetch_sv_ptr(aTHX))
#undef PL_bodytarget
#define PL_bodytarget (*Perl_Tbodytarget_ptr(aTHX))
#undef PL_bostr
#define PL_bostr (*Perl_Tbostr_ptr(aTHX))
#undef PL_chopset
#define PL_chopset (*Perl_Tchopset_ptr(aTHX))
#undef PL_colors
#define PL_colors (*Perl_Tcolors_ptr(aTHX))
#undef PL_colorset
#define PL_colorset (*Perl_Tcolorset_ptr(aTHX))
#undef PL_comppad
#define PL_comppad (*Perl_Tcomppad_ptr(aTHX))
#undef PL_curcop
#define PL_curcop (*Perl_Tcurcop_ptr(aTHX))
#undef PL_curpad
#define PL_curpad (*Perl_Tcurpad_ptr(aTHX))
#undef PL_curpm
#define PL_curpm (*Perl_Tcurpm_ptr(aTHX))
#undef PL_curstack
#define PL_curstack (*Perl_Tcurstack_ptr(aTHX))
#undef PL_curstackinfo
#define PL_curstackinfo (*Perl_Tcurstackinfo_ptr(aTHX))
#undef PL_curstash
#define PL_curstash (*Perl_Tcurstash_ptr(aTHX))
#undef PL_defoutgv
#define PL_defoutgv (*Perl_Tdefoutgv_ptr(aTHX))
#undef PL_defstash
#define PL_defstash (*Perl_Tdefstash_ptr(aTHX))
#undef PL_delaymagic
#define PL_delaymagic (*Perl_Tdelaymagic_ptr(aTHX))
#undef PL_dirty
#define PL_dirty (*Perl_Tdirty_ptr(aTHX))
#undef PL_dumpindent
#define PL_dumpindent (*Perl_Tdumpindent_ptr(aTHX))
#undef PL_efloatbuf
#define PL_efloatbuf (*Perl_Tefloatbuf_ptr(aTHX))
#undef PL_efloatsize
#define PL_efloatsize (*Perl_Tefloatsize_ptr(aTHX))
#undef PL_errors
#define PL_errors (*Perl_Terrors_ptr(aTHX))
#undef PL_extralen
#define PL_extralen (*Perl_Textralen_ptr(aTHX))
#undef PL_firstgv
#define PL_firstgv (*Perl_Tfirstgv_ptr(aTHX))
#undef PL_formtarget
#define PL_formtarget (*Perl_Tformtarget_ptr(aTHX))
#undef PL_hv_fetch_ent_mh
#define PL_hv_fetch_ent_mh (*Perl_Thv_fetch_ent_mh_ptr(aTHX))
#undef PL_hv_fetch_sv
#define PL_hv_fetch_sv (*Perl_Thv_fetch_sv_ptr(aTHX))
#undef PL_in_eval
#define PL_in_eval (*Perl_Tin_eval_ptr(aTHX))
#undef PL_last_in_gv
#define PL_last_in_gv (*Perl_Tlast_in_gv_ptr(aTHX))
#undef PL_lastgotoprobe
#define PL_lastgotoprobe (*Perl_Tlastgotoprobe_ptr(aTHX))
#undef PL_lastscream
#define PL_lastscream (*Perl_Tlastscream_ptr(aTHX))
#undef PL_localizing
#define PL_localizing (*Perl_Tlocalizing_ptr(aTHX))
#undef PL_mainstack
#define PL_mainstack (*Perl_Tmainstack_ptr(aTHX))
#undef PL_markstack
#define PL_markstack (*Perl_Tmarkstack_ptr(aTHX))
#undef PL_markstack_max
#define PL_markstack_max (*Perl_Tmarkstack_max_ptr(aTHX))
#undef PL_markstack_ptr
#define PL_markstack_ptr (*Perl_Tmarkstack_ptr_ptr(aTHX))
#undef PL_maxscream
#define PL_maxscream (*Perl_Tmaxscream_ptr(aTHX))
#undef PL_modcount
#define PL_modcount (*Perl_Tmodcount_ptr(aTHX))
#undef PL_na
#define PL_na (*Perl_Tna_ptr(aTHX))
#undef PL_nrs
#define PL_nrs (*Perl_Tnrs_ptr(aTHX))
#undef PL_ofs_sv
#define PL_ofs_sv (*Perl_Tofs_sv_ptr(aTHX))
#undef PL_op
#define PL_op (*Perl_Top_ptr(aTHX))
#undef PL_opsave
#define PL_opsave (*Perl_Topsave_ptr(aTHX))
#undef PL_peepp
#define PL_peepp (*Perl_Tpeepp_ptr(aTHX))
#undef PL_protect
#define PL_protect (*Perl_Tprotect_ptr(aTHX))
#undef PL_reg_call_cc
#define PL_reg_call_cc (*Perl_Treg_call_cc_ptr(aTHX))
#undef PL_reg_curpm
#define PL_reg_curpm (*Perl_Treg_curpm_ptr(aTHX))
#undef PL_reg_eval_set
#define PL_reg_eval_set (*Perl_Treg_eval_set_ptr(aTHX))
#undef PL_reg_flags
#define PL_reg_flags (*Perl_Treg_flags_ptr(aTHX))
#undef PL_reg_ganch
#define PL_reg_ganch (*Perl_Treg_ganch_ptr(aTHX))
#undef PL_reg_leftiter
#define PL_reg_leftiter (*Perl_Treg_leftiter_ptr(aTHX))
#undef PL_reg_magic
#define PL_reg_magic (*Perl_Treg_magic_ptr(aTHX))
#undef PL_reg_match_utf8
#define PL_reg_match_utf8 (*Perl_Treg_match_utf8_ptr(aTHX))
#undef PL_reg_maxiter
#define PL_reg_maxiter (*Perl_Treg_maxiter_ptr(aTHX))
#undef PL_reg_oldcurpm
#define PL_reg_oldcurpm (*Perl_Treg_oldcurpm_ptr(aTHX))
#undef PL_reg_oldpos
#define PL_reg_oldpos (*Perl_Treg_oldpos_ptr(aTHX))
#undef PL_reg_oldsaved
#define PL_reg_oldsaved (*Perl_Treg_oldsaved_ptr(aTHX))
#undef PL_reg_oldsavedlen
#define PL_reg_oldsavedlen (*Perl_Treg_oldsavedlen_ptr(aTHX))
#undef PL_reg_poscache
#define PL_reg_poscache (*Perl_Treg_poscache_ptr(aTHX))
#undef PL_reg_poscache_size
#define PL_reg_poscache_size (*Perl_Treg_poscache_size_ptr(aTHX))
#undef PL_reg_re
#define PL_reg_re (*Perl_Treg_re_ptr(aTHX))
#undef PL_reg_start_tmp
#define PL_reg_start_tmp (*Perl_Treg_start_tmp_ptr(aTHX))
#undef PL_reg_start_tmpl
#define PL_reg_start_tmpl (*Perl_Treg_start_tmpl_ptr(aTHX))
#undef PL_reg_starttry
#define PL_reg_starttry (*Perl_Treg_starttry_ptr(aTHX))
#undef PL_reg_sv
#define PL_reg_sv (*Perl_Treg_sv_ptr(aTHX))
#undef PL_reg_whilem_seen
#define PL_reg_whilem_seen (*Perl_Treg_whilem_seen_ptr(aTHX))
#undef PL_regbol
#define PL_regbol (*Perl_Tregbol_ptr(aTHX))
#undef PL_regcc
#define PL_regcc (*Perl_Tregcc_ptr(aTHX))
#undef PL_regcode
#define PL_regcode (*Perl_Tregcode_ptr(aTHX))
#undef PL_regcomp_parse
#define PL_regcomp_parse (*Perl_Tregcomp_parse_ptr(aTHX))
#undef PL_regcomp_rx
#define PL_regcomp_rx (*Perl_Tregcomp_rx_ptr(aTHX))
#undef PL_regcompat1
#define PL_regcompat1 (*Perl_Tregcompat1_ptr(aTHX))
#undef PL_regcompp
#define PL_regcompp (*Perl_Tregcompp_ptr(aTHX))
#undef PL_regdata
#define PL_regdata (*Perl_Tregdata_ptr(aTHX))
#undef PL_regdummy
#define PL_regdummy (*Perl_Tregdummy_ptr(aTHX))
#undef PL_regendp
#define PL_regendp (*Perl_Tregendp_ptr(aTHX))
#undef PL_regeol
#define PL_regeol (*Perl_Tregeol_ptr(aTHX))
#undef PL_regexecp
#define PL_regexecp (*Perl_Tregexecp_ptr(aTHX))
#undef PL_regflags
#define PL_regflags (*Perl_Tregflags_ptr(aTHX))
#undef PL_regfree
#define PL_regfree (*Perl_Tregfree_ptr(aTHX))
#undef PL_regindent
#define PL_regindent (*Perl_Tregindent_ptr(aTHX))
#undef PL_reginput
#define PL_reginput (*Perl_Treginput_ptr(aTHX))
#undef PL_regint_start
#define PL_regint_start (*Perl_Tregint_start_ptr(aTHX))
#undef PL_regint_string
#define PL_regint_string (*Perl_Tregint_string_ptr(aTHX))
#undef PL_reginterp_cnt
#define PL_reginterp_cnt (*Perl_Treginterp_cnt_ptr(aTHX))
#undef PL_reglastcloseparen
#define PL_reglastcloseparen (*Perl_Treglastcloseparen_ptr(aTHX))
#undef PL_reglastparen
#define PL_reglastparen (*Perl_Treglastparen_ptr(aTHX))
#undef PL_regnarrate
#define PL_regnarrate (*Perl_Tregnarrate_ptr(aTHX))
#undef PL_regnaughty
#define PL_regnaughty (*Perl_Tregnaughty_ptr(aTHX))
#undef PL_regnpar
#define PL_regnpar (*Perl_Tregnpar_ptr(aTHX))
#undef PL_regprecomp
#define PL_regprecomp (*Perl_Tregprecomp_ptr(aTHX))
#undef PL_regprogram
#define PL_regprogram (*Perl_Tregprogram_ptr(aTHX))
#undef PL_regsawback
#define PL_regsawback (*Perl_Tregsawback_ptr(aTHX))
#undef PL_regseen
#define PL_regseen (*Perl_Tregseen_ptr(aTHX))
#undef PL_regsize
#define PL_regsize (*Perl_Tregsize_ptr(aTHX))
#undef PL_regstartp
#define PL_regstartp (*Perl_Tregstartp_ptr(aTHX))
#undef PL_regtill
#define PL_regtill (*Perl_Tregtill_ptr(aTHX))
#undef PL_regxend
#define PL_regxend (*Perl_Tregxend_ptr(aTHX))
#undef PL_restartop
#define PL_restartop (*Perl_Trestartop_ptr(aTHX))
#undef PL_retstack
#define PL_retstack (*Perl_Tretstack_ptr(aTHX))
#undef PL_retstack_ix
#define PL_retstack_ix (*Perl_Tretstack_ix_ptr(aTHX))
#undef PL_retstack_max
#define PL_retstack_max (*Perl_Tretstack_max_ptr(aTHX))
#undef PL_rs
#define PL_rs (*Perl_Trs_ptr(aTHX))
#undef PL_savestack
#define PL_savestack (*Perl_Tsavestack_ptr(aTHX))
#undef PL_savestack_ix
#define PL_savestack_ix (*Perl_Tsavestack_ix_ptr(aTHX))
#undef PL_savestack_max
#define PL_savestack_max (*Perl_Tsavestack_max_ptr(aTHX))
#undef PL_scopestack
#define PL_scopestack (*Perl_Tscopestack_ptr(aTHX))
#undef PL_scopestack_ix
#define PL_scopestack_ix (*Perl_Tscopestack_ix_ptr(aTHX))
#undef PL_scopestack_max
#define PL_scopestack_max (*Perl_Tscopestack_max_ptr(aTHX))
#undef PL_screamfirst
#define PL_screamfirst (*Perl_Tscreamfirst_ptr(aTHX))
#undef PL_screamnext
#define PL_screamnext (*Perl_Tscreamnext_ptr(aTHX))
#undef PL_secondgv
#define PL_secondgv (*Perl_Tsecondgv_ptr(aTHX))
#undef PL_seen_evals
#define PL_seen_evals (*Perl_Tseen_evals_ptr(aTHX))
#undef PL_seen_zerolen
#define PL_seen_zerolen (*Perl_Tseen_zerolen_ptr(aTHX))
#undef PL_sortcop
#define PL_sortcop (*Perl_Tsortcop_ptr(aTHX))
#undef PL_sortcxix
#define PL_sortcxix (*Perl_Tsortcxix_ptr(aTHX))
#undef PL_sortstash
#define PL_sortstash (*Perl_Tsortstash_ptr(aTHX))
#undef PL_stack_base
#define PL_stack_base (*Perl_Tstack_base_ptr(aTHX))
#undef PL_stack_max
#define PL_stack_max (*Perl_Tstack_max_ptr(aTHX))
#undef PL_stack_sp
#define PL_stack_sp (*Perl_Tstack_sp_ptr(aTHX))
#undef PL_start_env
#define PL_start_env (*Perl_Tstart_env_ptr(aTHX))
#undef PL_statbuf
#define PL_statbuf (*Perl_Tstatbuf_ptr(aTHX))
#undef PL_statcache
#define PL_statcache (*Perl_Tstatcache_ptr(aTHX))
#undef PL_statgv
#define PL_statgv (*Perl_Tstatgv_ptr(aTHX))
#undef PL_statname
#define PL_statname (*Perl_Tstatname_ptr(aTHX))
#undef PL_tainted
#define PL_tainted (*Perl_Ttainted_ptr(aTHX))
#undef PL_timesbuf
#define PL_timesbuf (*Perl_Ttimesbuf_ptr(aTHX))
#undef PL_tmps_floor
#define PL_tmps_floor (*Perl_Ttmps_floor_ptr(aTHX))
#undef PL_tmps_ix
#define PL_tmps_ix (*Perl_Ttmps_ix_ptr(aTHX))
#undef PL_tmps_max
#define PL_tmps_max (*Perl_Ttmps_max_ptr(aTHX))
#undef PL_tmps_stack
#define PL_tmps_stack (*Perl_Ttmps_stack_ptr(aTHX))
#undef PL_top_env
#define PL_top_env (*Perl_Ttop_env_ptr(aTHX))
#undef PL_toptarget
#define PL_toptarget (*Perl_Ttoptarget_ptr(aTHX))
#undef PL_watchaddr
#define PL_watchaddr (*Perl_Twatchaddr_ptr(aTHX))
#undef PL_watchok
#define PL_watchok (*Perl_Twatchok_ptr(aTHX))
#undef PL_No
#define PL_No (*Perl_GNo_ptr(NULL))
#undef PL_Yes
#define PL_Yes (*Perl_GYes_ptr(NULL))
#undef PL_csighandlerp
#define PL_csighandlerp (*Perl_Gcsighandlerp_ptr(NULL))
#undef PL_curinterp
#define PL_curinterp (*Perl_Gcurinterp_ptr(NULL))
#undef PL_do_undump
#define PL_do_undump (*Perl_Gdo_undump_ptr(NULL))
#undef PL_dollarzero_mutex
#define PL_dollarzero_mutex (*Perl_Gdollarzero_mutex_ptr(NULL))
#undef PL_hexdigit
#define PL_hexdigit (*Perl_Ghexdigit_ptr(NULL))
#undef PL_malloc_mutex
#define PL_malloc_mutex (*Perl_Gmalloc_mutex_ptr(NULL))
#undef PL_op_mutex
#define PL_op_mutex (*Perl_Gop_mutex_ptr(NULL))
#undef PL_patleave
#define PL_patleave (*Perl_Gpatleave_ptr(NULL))
#undef PL_sh_path
#define PL_sh_path (*Perl_Gsh_path_ptr(NULL))
#undef PL_sigfpe_saved
#define PL_sigfpe_saved (*Perl_Gsigfpe_saved_ptr(NULL))
#undef PL_sv_placeholder
#define PL_sv_placeholder (*Perl_Gsv_placeholder_ptr(NULL))
#undef PL_thr_key
#define PL_thr_key (*Perl_Gthr_key_ptr(NULL))
#undef PL_use_safe_putenv
#define PL_use_safe_putenv (*Perl_Guse_safe_putenv_ptr(NULL))
#endif /* !PERL_CORE */
#endif /* MULTIPLICITY */
#endif /* __perlapi_h__ */
|
96599553ea63473ac29c50783d4db151af4e4ea0
|
bed3ac926beac0f4e0293303d7b2a6031ee476c9
|
/Modules/ThirdParty/MINC/src/libminc/volume_io/MNI_formats/gen_xfs.c
|
4d1c7d43dada72b7fab4f5260c80dc121a4eaab8
|
[
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-hdf5",
"MIT",
"NTP",
"LicenseRef-scancode-mit-old-style",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
InsightSoftwareConsortium/ITK
|
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
|
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
|
refs/heads/master
| 2023-08-31T17:21:47.754304
| 2023-08-31T00:58:51
| 2023-08-31T14:12:21
| 800,928
| 1,229
| 656
|
Apache-2.0
| 2023-09-14T17:54:00
| 2010-07-27T15:48:04
|
C++
|
UTF-8
|
C
| false
| false
| 39,845
|
c
|
gen_xfs.c
|
/* ----------------------------------------------------------------------------
@COPYRIGHT :
Copyright 1993,1994,1995 David MacDonald,
McConnell Brain Imaging Centre,
Montreal Neurological Institute, McGill University.
Permission to use, copy, modify, and distribute this
software and its documentation for any purpose and without
fee is hereby granted, provided that the above copyright
notice appear in all copies. The author and McGill University
make no representations about the suitability of this
software for any purpose. It is provided "as is" without
express or implied warranty.
---------------------------------------------------------------------------- */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /*HAVE_CONFIG_H*/
#include <internal_volume_io.h>
/* ----------------------------- MNI Header -----------------------------------
@NAME : alloc_linear_transform
@INPUT : transform
@OUTPUT :
@RETURNS :
@DESCRIPTION: Allocates memory for the linear transform and its inverse.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
static void alloc_linear_transform(
VIO_General_transform *transform )
{
transform->type = LINEAR;
transform->inverse_flag = FALSE;
ALLOC( transform->linear_transform, 1 );
ALLOC( transform->inverse_linear_transform, 1 );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_linear_transform
@INPUT : linear_transform
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a general transform of type linear, copying the
linear_transform and computing its inverse. If the linear
transform is NULL, the identity transform is created.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void create_linear_transform(
VIO_General_transform *transform,
VIO_Transform *linear_transform )
{
alloc_linear_transform( transform );
if( linear_transform != (VIO_Transform *) NULL &&
compute_transform_inverse( linear_transform,
transform->inverse_linear_transform ) )
{
*(transform->linear_transform) = *linear_transform;
}
else
{
make_identity_transform( transform->linear_transform );
make_identity_transform( transform->inverse_linear_transform );
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : initialize_thin_plate_transform
@INPUT : transform
n_dimensions
n_points
@OUTPUT :
@RETURNS :
@DESCRIPTION: Initializes a VIO_General_transform structure for thin plate
transforms.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : Feb. 21, 1995 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
static void initialize_thin_plate_transform(
VIO_General_transform *transform,
int n_dimensions,
int n_points )
{
transform->type = THIN_PLATE_SPLINE;
transform->inverse_flag = FALSE;
transform->n_dimensions = n_dimensions;
transform->n_points = n_points;
transform->displacement_volume = NULL;
VIO_ALLOC2D( transform->points, n_points, n_dimensions );
VIO_ALLOC2D( transform->displacements, n_points + n_dimensions + 1,
n_dimensions );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_thin_plate_transform_real
@INPUT : n_dimensions
n_points
points
displacements
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a general transform of type thin plate spline, given
VIO_Real-type points and displacements.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED : Feb. 21, 1995 David MacDonald - make a real and float version
---------------------------------------------------------------------------- */
VIOAPI void create_thin_plate_transform_real(
VIO_General_transform *transform,
int n_dimensions,
int n_points,
VIO_Real **points,
VIO_Real **displacements )
{
int p, d;
initialize_thin_plate_transform( transform, n_dimensions, n_points );
for_less( p, 0, n_points )
{
for_less( d, 0, n_dimensions )
transform->points[p][d] = points[p][d];
}
for_less( p, 0, n_points + n_dimensions + 1 )
{
for_less( d, 0, n_dimensions )
transform->displacements[p][d] = displacements[p][d];
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_thin_plate_transform
@INPUT : n_dimensions
n_points
points
displacements
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a general transform of type thin plate spline.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED : Feb. 21, 1995 David MacDonald - make a real and float version
---------------------------------------------------------------------------- */
VIOAPI void create_thin_plate_transform(
VIO_General_transform *transform,
int n_dimensions,
int n_points,
float **points,
float **displacements )
{
int p, d;
initialize_thin_plate_transform( transform, n_dimensions, n_points );
for_less( p, 0, n_points )
{
for_less( d, 0, n_dimensions )
transform->points[p][d] = (VIO_Real) points[p][d];
}
for_less( p, 0, n_points + n_dimensions + 1 )
{
for_less( d, 0, n_dimensions )
transform->displacements[p][d] = (VIO_Real) displacements[p][d];
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : internal_create_grid_transform
@INPUT : displacement_volume
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a general transform of type grid.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : Feb. 21, 1995 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
static void internal_create_grid_transform(
VIO_General_transform *transform,
VIO_Volume displacement_volume,
VIO_BOOL copy_flag,
VIO_STR displacement_volume_file
)
{
int dim, sizes[VIO_MAX_DIMENSIONS], vector_dim = -1;
VIO_STR *dim_names;
VIO_Volume copy;
VIO_BOOL volume_ok, dim_found[VIO_N_DIMENSIONS];
volume_ok = TRUE;
/*TODO: initialize strings?*/
if( displacement_volume )
{
if( get_volume_n_dimensions(displacement_volume) != 4 )
{
volume_ok = FALSE;
print_error( "Grid transform must be 4 dimensional.\n" );
}
else
{
dim_names = get_volume_dimension_names( displacement_volume );
get_volume_sizes( displacement_volume, sizes );
dim_found[VIO_X] = FALSE;
dim_found[VIO_Y] = FALSE;
dim_found[VIO_Z] = FALSE;
vector_dim = -1;
for_less( dim, 0, 4 )
{
if( equal_strings( dim_names[dim], MIxspace ) )
dim_found[VIO_X] = TRUE;
else if( equal_strings( dim_names[dim], MIyspace ) )
dim_found[VIO_Y] = TRUE;
else if( equal_strings( dim_names[dim], MIzspace ) )
dim_found[VIO_Z] = TRUE;
else
{
if( sizes[dim] != 3 )
{
print_error(
"displacement_volume must have 3 components on " );
print_error( "the non-spatial axis.\n" );
volume_ok = FALSE;
}
vector_dim = dim;
}
}
if( !dim_found[VIO_X] || !dim_found[VIO_Y] || !dim_found[VIO_Z] )
{
print_error(
"Must have an x, y, and z dimension in displacement volume.\n" );
volume_ok = FALSE;
}
delete_dimension_names( displacement_volume, dim_names );
}
if( !volume_ok )
{
create_linear_transform( transform, NULL ); /*--- make identity */
return;
}
if( copy_flag )
copy = copy_volume( displacement_volume );
else
copy = displacement_volume;
transform->type = GRID_TRANSFORM;
transform->inverse_flag = FALSE;
/* --- force 4th dimension to be vector dimension */
replace_string( ©->dimension_names[vector_dim],
create_string(MIvector_dimension) );
transform->displacement_volume = (void *) copy;
} else {
/*we are probably dealing with a case when only a placeholder is needed*/
transform->type = GRID_TRANSFORM;
transform->inverse_flag = FALSE;
transform->displacement_volume = NULL;
}
/*Will be initialized on save*/
if(displacement_volume_file)
transform->displacement_volume_file = create_string( displacement_volume_file );
else
transform->displacement_volume_file = NULL;
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_grid_transform
@INPUT : displacement_volume
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a grid transform VIO_General_transform. Makes a copy of
the displacement volume and puts it in the VIO_General_transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : Feb. 21, 1995 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void create_grid_transform(
VIO_General_transform *transform,
VIO_Volume displacement_volume,
VIO_STR displacement_volume_file)
{
internal_create_grid_transform( transform, displacement_volume, TRUE, displacement_volume_file );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_grid_transform_no_copy
@INPUT : displacement_volume
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a grid transform VIO_General_transform. Places the
displacement volume into the VIO_General_transform; therefore the
calling program should not delete the volume.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : Feb. 21, 1995 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void create_grid_transform_no_copy(
VIO_General_transform *transform,
VIO_Volume displacement_volume,
VIO_STR displacement_volume_file )
{
internal_create_grid_transform( transform, displacement_volume, FALSE,displacement_volume_file );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_user_transform
@INPUT : user_data
size_user_data
transform_function
inverse_transform_function
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Creates a general transform of type user transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void create_user_transform(
VIO_General_transform *transform,
void *user_data,
size_t size_user_data,
VIO_User_transform_function transform_function,
VIO_User_transform_function inverse_transform_function )
{
unsigned char *byte_ptr;
transform->type = USER_TRANSFORM;
transform->inverse_flag = FALSE;
transform->size_user_data = size_user_data;
ALLOC( byte_ptr, size_user_data );
transform->user_data = byte_ptr;
(void) memcpy( transform->user_data, user_data, size_user_data );
transform->user_transform_function = transform_function;
transform->user_inverse_transform_function = inverse_transform_function;
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : get_transform_type
@INPUT : transform
@OUTPUT :
@RETURNS : type
@DESCRIPTION: Returns the type of the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Transform_types get_transform_type(
VIO_General_transform *transform )
{
return( transform->type );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : get_n_concated_transforms
@INPUT : transform
@OUTPUT :
@RETURNS : # transforms
@DESCRIPTION: Returns the number of concatenated transforms if the transform
type is concatenated, otherwise, 1.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI int get_n_concated_transforms(
VIO_General_transform *transform )
{
if( transform->type == CONCATENATED_TRANSFORM )
return( transform->n_transforms );
else
return( 1 );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : get_nth_general_transform
@INPUT : transform
n
@OUTPUT :
@RETURNS : pointer to nth transform
@DESCRIPTION: Returns a pointer to the nth transform of the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_General_transform *get_nth_general_transform(
VIO_General_transform *transform,
int n )
{
if( n < 0 || n >= get_n_concated_transforms( transform ) )
{
handle_internal_error( "get_nth_general_transform" );
return( (VIO_General_transform *) NULL );
}
else if( transform->type == CONCATENATED_TRANSFORM )
return( &transform->transforms[n] );
else
return( transform );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : get_linear_transform_ptr
@INPUT : transform
@OUTPUT :
@RETURNS : pointer to linear transform
@DESCRIPTION: Returns a pointer to the linear transform of the general
transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Transform *get_linear_transform_ptr(
VIO_General_transform *transform )
{
if( transform->type == LINEAR )
{
if( transform->inverse_flag )
return( transform->inverse_linear_transform );
else
return( transform->linear_transform );
}
else
{
handle_internal_error( "get_linear_transform_ptr" );
return( (VIO_Transform *) NULL );
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : get_inverse_linear_transform_ptr
@INPUT : transform
@OUTPUT :
@RETURNS : pointer to inverse linear transform
@DESCRIPTION: Returns a pointer to the inverse linear transform of the general
transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Transform *get_inverse_linear_transform_ptr(
VIO_General_transform *transform )
{
if( transform->type == LINEAR )
{
if( transform->inverse_flag )
return( transform->linear_transform );
else
return( transform->inverse_linear_transform );
}
else
{
handle_internal_error( "get_inverse_linear_transform_ptr" );
return( (VIO_Transform *) NULL );
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : transform_or_invert_point_with_input_steps
@INPUT : transform
inverse_flag
x
y
z
input_volume_steps
@OUTPUT : x_transformed
y_transformed
z_transformed
@RETURNS :
@DESCRIPTION: Transforms a point by the general transform or its inverse,
depending on inverse_flag.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED : Feb. 27, 1995 D. MacDonald - added grid transforms
@MODIFIED : 2013, June 10, Matthijs van Eede, added the possibility to pass
along the step sizes of the input file which is
being resampled to determine the appropriate error
margin (ftol) in
grid_inverse_transform_point_with_input_steps
---------------------------------------------------------------------------- */
static VIO_Status transform_or_invert_point_with_input_steps(
VIO_General_transform *transform,
VIO_BOOL inverse_flag,
VIO_Real x,
VIO_Real y,
VIO_Real z,
VIO_Real *input_volume_steps,
VIO_Real *x_transformed,
VIO_Real *y_transformed,
VIO_Real *z_transformed )
{
int trans;
VIO_Status status=VIO_ERROR;
switch( transform->type )
{
case LINEAR:
if( inverse_flag )
return transform_point( transform->inverse_linear_transform,
x, y, z,
x_transformed, y_transformed, z_transformed );
else
return transform_point( transform->linear_transform,
x, y, z,
x_transformed, y_transformed, z_transformed );
break;
case THIN_PLATE_SPLINE:
if( inverse_flag )
{
return thin_plate_spline_inverse_transform( transform->n_dimensions,
transform->n_points,
transform->points,
transform->displacements,
x, y, z,
x_transformed, y_transformed,
z_transformed );
}
else
{
return thin_plate_spline_transform( transform->n_dimensions,
transform->n_points,
transform->points,
transform->displacements,
x, y, z,
x_transformed, y_transformed,
z_transformed );
}
break;
case GRID_TRANSFORM:
if( !transform->displacement_volume ) {
handle_internal_error( "Not initialized grid transform, make sure you have MINC1" );
return VIO_ERROR;
break;
}
if( inverse_flag )
{
return grid_inverse_transform_point_with_input_steps( transform,
x, y, z, input_volume_steps,
x_transformed, y_transformed,
z_transformed );
}
else
{
return grid_transform_point( transform,
x, y, z,
x_transformed, y_transformed,
z_transformed );
}
break;
case USER_TRANSFORM:
if( inverse_flag )
{
transform->user_inverse_transform_function(
transform->user_data, x, y, z,
x_transformed, y_transformed, z_transformed );
/*TODO: add error handling?*/
}
else
{
transform->user_transform_function(
transform->user_data, x, y, z,
x_transformed, y_transformed, z_transformed );
/*TODO: add error handling?*/
}
return VIO_OK;
break;
case CONCATENATED_TRANSFORM:
*x_transformed = x;
*y_transformed = y;
*z_transformed = z;
if( inverse_flag )
{
for( trans = transform->n_transforms-1; trans >= 0; --trans )
{
if( (status=general_inverse_transform_point_with_input_steps( &transform->transforms[trans],
*x_transformed, *y_transformed, *z_transformed, input_volume_steps,
x_transformed, y_transformed, z_transformed )) != VIO_OK)
return status;
}
}
else
{
for_less( trans, 0, transform->n_transforms )
{
if((status=general_transform_point_with_input_steps( &transform->transforms[trans],
*x_transformed, *y_transformed, *z_transformed, input_volume_steps,
x_transformed, y_transformed, z_transformed )) != VIO_OK)
return status;
}
}
break;
default:
handle_internal_error( "transform_or_invert_point_with_input_steps" );
return VIO_ERROR;
break;
}
return status;
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : general_transform_point_with_input_steps
@INPUT : transform
x
y
z
input_volume_steps
@OUTPUT : x_transformed
y_transformed
z_transformed
@RETURNS :
@DESCRIPTION: Transforms a point by the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
@MODIFIED : 2013, June 10, Matthijs van Eede, added the possibility to pass
along the step sizes of the input file which is
being resampled to determine the appropriate error
margin (ftol) in grid_inverse_transform_point_with_input_steps
---------------------------------------------------------------------------- */
VIOAPI VIO_Status general_transform_point_with_input_steps(
VIO_General_transform *transform,
VIO_Real x,
VIO_Real y,
VIO_Real z,
VIO_Real *input_volume_steps,
VIO_Real *x_transformed,
VIO_Real *y_transformed,
VIO_Real *z_transformed )
{
return transform_or_invert_point_with_input_steps( transform, transform->inverse_flag, x, y, z,
input_volume_steps,
x_transformed, y_transformed, z_transformed );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : general_inverse_transform_point_with_input_steps
@INPUT : transform
x
y
z
input_volume_steps
@OUTPUT : x_transformed
y_transformed
z_transformed
@RETURNS :
@DESCRIPTION: Transforms a point by the inverse of the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Status general_inverse_transform_point_with_input_steps(
VIO_General_transform *transform,
VIO_Real x,
VIO_Real y,
VIO_Real z,
VIO_Real *input_volume_steps,
VIO_Real *x_transformed,
VIO_Real *y_transformed,
VIO_Real *z_transformed )
{
return transform_or_invert_point_with_input_steps( transform, !transform->inverse_flag, x, y, z,
input_volume_steps,
x_transformed, y_transformed, z_transformed );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : general_transform_point
@INPUT : transform
x
y
z
@OUTPUT : x_transformed
y_transformed
z_transformed
@RETURNS :
@DESCRIPTION: Transforms a point by the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Status general_transform_point(
VIO_General_transform *transform,
VIO_Real x,
VIO_Real y,
VIO_Real z,
VIO_Real *x_transformed,
VIO_Real *y_transformed,
VIO_Real *z_transformed )
{
return general_transform_point_with_input_steps( transform, x, y, z,
NULL,
x_transformed, y_transformed, z_transformed );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : general_inverse_transform_point
@INPUT : transform
x
y
z
@OUTPUT : x_transformed
y_transformed
z_transformed
@RETURNS :
@DESCRIPTION: Transforms a point by the inverse of the general transform.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI VIO_Status general_inverse_transform_point(
VIO_General_transform *transform,
VIO_Real x,
VIO_Real y,
VIO_Real z,
VIO_Real *x_transformed,
VIO_Real *y_transformed,
VIO_Real *z_transformed )
{
return general_inverse_transform_point_with_input_steps( transform, x, y, z,
NULL,
x_transformed, y_transformed, z_transformed );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : copy_and_invert_transform
@INPUT : transform
invert_it
@OUTPUT : copy
@RETURNS :
@DESCRIPTION: Copies the transform or its inverse to copy.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
@MODIFIED : Feb. 27, 1995 D. MacDonald - added grid transforms
---------------------------------------------------------------------------- */
static void copy_and_invert_transform(
VIO_General_transform *transform,
VIO_BOOL invert_it,
VIO_General_transform *copy )
{
unsigned char *byte_ptr;
VIO_Transform *swap;
int i, j, trans;
*copy = *transform;
switch( transform->type )
{
case LINEAR:
alloc_linear_transform( copy );
*(copy->linear_transform) = *(transform->linear_transform);
*(copy->inverse_linear_transform) =
*(transform->inverse_linear_transform);
if( transform->inverse_flag )
invert_it = !invert_it;
if( invert_it )
{
swap = copy->linear_transform;
copy->linear_transform = copy->inverse_linear_transform;
copy->inverse_linear_transform = swap;
}
copy->inverse_flag = FALSE;
break;
case THIN_PLATE_SPLINE:
VIO_ALLOC2D( copy->points, copy->n_points, copy->n_dimensions);
VIO_ALLOC2D( copy->displacements, copy->n_points + copy->n_dimensions + 1,
copy->n_dimensions);
for_less( i, 0, copy->n_points )
for_less( j, 0, copy->n_dimensions )
copy->points[i][j] = transform->points[i][j];
for_less( i, 0, copy->n_points + copy->n_dimensions + 1 )
for_less( j, 0, copy->n_dimensions )
copy->displacements[i][j] = transform->displacements[i][j];
if( invert_it )
copy->inverse_flag = !copy->inverse_flag;
break;
case GRID_TRANSFORM:
if( transform->displacement_volume )
copy->displacement_volume = (void *) copy_volume(
(VIO_Volume) transform->displacement_volume );
if( transform->displacement_volume_file )
copy->displacement_volume_file =
create_string( transform->displacement_volume_file );
if( invert_it )
copy->inverse_flag = !copy->inverse_flag;
break;
case USER_TRANSFORM:
ALLOC( byte_ptr, copy->size_user_data );
copy->user_data = byte_ptr;
(void) memcpy( copy->user_data, transform->user_data,
copy->size_user_data );
if( invert_it )
copy->inverse_flag = !copy->inverse_flag;
break;
case CONCATENATED_TRANSFORM:
ALLOC( copy->transforms, copy->n_transforms );
for_less( trans, 0, copy->n_transforms )
{
copy_general_transform( &transform->transforms[trans],
©->transforms[trans] );
}
if( invert_it )
copy->inverse_flag = !copy->inverse_flag;
break;
default:
handle_internal_error( "copy_and_invert_transform" );
break;
}
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : copy_general_transform
@INPUT : transform
@OUTPUT : copy
@RETURNS :
@DESCRIPTION: Copies the general transform to copy.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void copy_general_transform(
VIO_General_transform *transform,
VIO_General_transform *copy )
{
copy_and_invert_transform( transform, FALSE, copy );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : invert_general_transform
@INPUT : transform
@OUTPUT : transform
@RETURNS :
@DESCRIPTION: Inverts a general transform in place.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : Nov. 20, 1995 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void invert_general_transform(
VIO_General_transform *transform )
{
transform->inverse_flag = !transform->inverse_flag;
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : create_inverse_general_transform
@INPUT : transform
@OUTPUT : inverse
@RETURNS :
@DESCRIPTION: Creates a general transform that is the inverse of the given one.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void create_inverse_general_transform(
VIO_General_transform *transform,
VIO_General_transform *inverse )
{
copy_and_invert_transform( transform, TRUE, inverse );
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : concat_general_transforms
@INPUT : first
second
@OUTPUT : result
@RETURNS :
@DESCRIPTION: Concatenates two general transforms into result. Transforming
a point by result is the same as transforming it by 'first',
then transforming by 'second'.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
---------------------------------------------------------------------------- */
VIOAPI void concat_general_transforms(
VIO_General_transform *first,
VIO_General_transform *second,
VIO_General_transform *result )
{
int first_start, first_end, first_step;
int second_start, second_end, second_step;
int i, trans;
VIO_BOOL crunching_linear;
VIO_BOOL first_inverted_concat, second_inverted_concat;
VIO_Transform *first_transform, *first_inverse;
VIO_Transform *second_transform, *second_inverse;
VIO_General_transform result_tmp, *result_ptr;
VIO_General_transform *transform;
if( result == first || result == second )
result_ptr = &result_tmp;
else
result_ptr = result;
first_inverted_concat = first->type == CONCATENATED_TRANSFORM &&
first->inverse_flag;
second_inverted_concat = second->type == CONCATENATED_TRANSFORM &&
second->inverse_flag;
if( first->inverse_flag )
{
first_start = get_n_concated_transforms( first ) - 1;
first_end = 0;
first_step = -1;
}
else
{
first_start = 0;
first_end = get_n_concated_transforms( first ) - 1;
first_step = 1;
}
if( second->inverse_flag )
{
second_start = get_n_concated_transforms( second ) - 1;
second_end = 0;
second_step = -1;
}
else
{
second_start = 0;
second_end = get_n_concated_transforms( second ) - 1;
second_step = 1;
}
result_ptr->n_transforms = VIO_ABS( first_end - first_start ) + 1 +
VIO_ABS( second_end - second_start ) + 1;
crunching_linear = FALSE;
if( get_nth_general_transform( first, first_end )->type == LINEAR &&
get_nth_general_transform( second, second_start )->type == LINEAR )
{
--result_ptr->n_transforms;
crunching_linear = TRUE;
first_end -= first_step;
second_start += second_step;
}
if( result_ptr->n_transforms == 1 )
result_ptr->type = LINEAR;
else
{
result_ptr->type = CONCATENATED_TRANSFORM;
ALLOC( result_ptr->transforms, result_ptr->n_transforms );
}
result_ptr->inverse_flag = FALSE;
trans = 0;
for( i = first_start; i != first_end + first_step; i += first_step )
{
copy_and_invert_transform( get_nth_general_transform( first, i ),
first_inverted_concat,
get_nth_general_transform(result_ptr,trans));
++trans;
}
if( crunching_linear )
{
transform = get_nth_general_transform( result_ptr, trans );
alloc_linear_transform( transform );
if( first_inverted_concat )
{
first_inverse = get_linear_transform_ptr(
get_nth_general_transform(first,first_end+first_step));
first_transform = get_inverse_linear_transform_ptr(
get_nth_general_transform(first,first_end+first_step));
}
else
{
first_transform = get_linear_transform_ptr(
get_nth_general_transform(first,first_end+first_step));
first_inverse = get_inverse_linear_transform_ptr(
get_nth_general_transform(first,first_end+first_step));
}
if( second_inverted_concat )
{
second_inverse = get_linear_transform_ptr(
get_nth_general_transform(second,second_start-second_step));
second_transform = get_inverse_linear_transform_ptr(
get_nth_general_transform(second,second_start-second_step));
}
else
{
second_transform = get_linear_transform_ptr(
get_nth_general_transform(second,second_start-second_step));
second_inverse = get_inverse_linear_transform_ptr(
get_nth_general_transform(second,second_start-second_step));
}
concat_transforms( get_linear_transform_ptr(transform),
first_transform, second_transform );
concat_transforms( get_inverse_linear_transform_ptr(transform),
second_inverse, first_inverse );
++trans;
}
for( i = second_start; i != second_end + second_step; i += second_step )
{
copy_and_invert_transform( get_nth_general_transform( second, i ),
second_inverted_concat,
get_nth_general_transform(result_ptr,trans));
++trans;
}
if( result == first || result == second )
*result = *result_ptr;
}
/* ----------------------------- MNI Header -----------------------------------
@NAME : delete_general_transform
@INPUT : transform
@OUTPUT :
@RETURNS :
@DESCRIPTION: Deletes the transform, freeing up memory.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : 1993 David MacDonald
@MODIFIED :
@MODIFIED : Feb. 27, 1995 D. MacDonald - added grid transforms
---------------------------------------------------------------------------- */
VIOAPI void delete_general_transform(
VIO_General_transform *transform )
{
int trans;
switch( transform->type )
{
case LINEAR:
FREE( transform->linear_transform );
FREE( transform->inverse_linear_transform );
break;
case THIN_PLATE_SPLINE:
if( transform->n_points > 0 && transform->n_dimensions > 0 )
{
VIO_FREE2D( transform->points );
VIO_FREE2D( transform->displacements );
}
break;
case GRID_TRANSFORM:
if( transform->displacement_volume )
delete_volume( (VIO_Volume) transform->displacement_volume );
if( transform->displacement_volume_file )
delete_string(transform->displacement_volume_file);
transform->displacement_volume_file=NULL;
break;
case USER_TRANSFORM:
if( transform->size_user_data )
FREE( transform->user_data );
break;
case CONCATENATED_TRANSFORM:
for_less( trans, 0, transform->n_transforms )
delete_general_transform( &transform->transforms[trans] );
if( transform->n_transforms > 0 )
FREE( transform->transforms );
break;
default:
handle_internal_error( "delete_general_transform" );
break;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.