filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
272581.c | /*-
* Copyright (c) 2005 David Schultz <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/11.1/lib/msun/src/s_cargf.c 174561 2007-12-12 23:43:51Z das $");
#include <complex.h>
#include <math.h>
float
cargf(float complex z)
{
return (atan2f(cimagf(z), crealf(z)));
}
|
969983.c | #ifdef FLA_ENABLE_XBLAS
/* ../netlib/zla_porfsx_extended.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* Table of constant values */
static integer c__1 = 1;
static doublecomplex c_b11 =
{
-1.,0.
}
;
static doublecomplex c_b12 =
{
1.,0.
}
;
static doublereal c_b34 = 1.;
/* > \brief \b ZLA_PORFSX_EXTENDED improves the computed solution to a system of linear equations for symmetri c or Hermitian positive-definite matrices by performing extra-precise iterative refinement and provide s error bounds and backward error estimates fo */
/* r the solution. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZLA_PORFSX_EXTENDED + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zla_por fsx_extended.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zla_por fsx_extended.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zla_por fsx_extended.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZLA_PORFSX_EXTENDED( PREC_TYPE, UPLO, N, NRHS, A, LDA, */
/* AF, LDAF, COLEQU, C, B, LDB, Y, */
/* LDY, BERR_OUT, N_NORMS, */
/* ERR_BNDS_NORM, ERR_BNDS_COMP, RES, */
/* AYB, DY, Y_TAIL, RCOND, ITHRESH, */
/* RTHRESH, DZ_UB, IGNORE_CWISE, */
/* INFO ) */
/* .. Scalar Arguments .. */
/* INTEGER INFO, LDA, LDAF, LDB, LDY, N, NRHS, PREC_TYPE, */
/* $ N_NORMS, ITHRESH */
/* CHARACTER UPLO */
/* LOGICAL COLEQU, IGNORE_CWISE */
/* DOUBLE PRECISION RTHRESH, DZ_UB */
/* .. */
/* .. Array Arguments .. */
/* COMPLEX*16 A( LDA, * ), AF( LDAF, * ), B( LDB, * ), */
/* $ Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * ) */
/* DOUBLE PRECISION C( * ), AYB( * ), RCOND, BERR_OUT( * ), */
/* $ ERR_BNDS_NORM( NRHS, * ), */
/* $ ERR_BNDS_COMP( NRHS, * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZLA_PORFSX_EXTENDED improves the computed solution to a system of */
/* > linear equations by performing extra-precise iterative refinement */
/* > and provides error bounds and backward error estimates for the solution. */
/* > This subroutine is called by ZPORFSX to perform iterative refinement. */
/* > In addition to normwise error bound, the code provides maximum */
/* > componentwise error bound if possible. See comments for ERR_BNDS_NORM */
/* > and ERR_BNDS_COMP for details of the error bounds. Note that this */
/* > subroutine is only resonsible for setting the second fields of */
/* > ERR_BNDS_NORM and ERR_BNDS_COMP. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] PREC_TYPE */
/* > \verbatim */
/* > PREC_TYPE is INTEGER */
/* > Specifies the intermediate precision to be used in refinement. */
/* > The value is defined by ILAPREC(P) where P is a CHARACTER and */
/* > P = 'S': Single */
/* > = 'D': Double */
/* > = 'I': Indigenous */
/* > = 'X', 'E': Extra */
/* > \endverbatim */
/* > */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > = 'U': Upper triangle of A is stored;
*/
/* > = 'L': Lower triangle of A is stored. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of linear equations, i.e., the order of the */
/* > matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right-hand-sides, i.e., the number of columns of the */
/* > matrix B. */
/* > \endverbatim */
/* > */
/* > \param[in] A */
/* > \verbatim */
/* > A is COMPLEX*16 array, dimension (LDA,N) */
/* > On entry, the N-by-N matrix A. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] AF */
/* > \verbatim */
/* > AF is COMPLEX*16 array, dimension (LDAF,N) */
/* > The triangular factor U or L from the Cholesky factorization */
/* > A = U**T*U or A = L*L**T, as computed by ZPOTRF. */
/* > \endverbatim */
/* > */
/* > \param[in] LDAF */
/* > \verbatim */
/* > LDAF is INTEGER */
/* > The leading dimension of the array AF. LDAF >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] COLEQU */
/* > \verbatim */
/* > COLEQU is LOGICAL */
/* > If .TRUE. then column equilibration was done to A before calling */
/* > this routine. This is needed to compute the solution and error */
/* > bounds correctly. */
/* > \endverbatim */
/* > */
/* > \param[in] C */
/* > \verbatim */
/* > C is DOUBLE PRECISION array, dimension (N) */
/* > The column scale factors for A. If COLEQU = .FALSE., C */
/* > is not accessed. If C is input, each element of C should be a power */
/* > of the radix to ensure a reliable solution and error estimates. */
/* > Scaling by powers of the radix does not cause rounding errors unless */
/* > the result underflows or overflows. Rounding errors during scaling */
/* > lead to refining with a matrix that is not equivalent to the */
/* > input matrix, producing error estimates that may not be */
/* > reliable. */
/* > \endverbatim */
/* > */
/* > \param[in] B */
/* > \verbatim */
/* > B is COMPLEX*16 array, dimension (LDB,NRHS) */
/* > The right-hand-side matrix B. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] Y */
/* > \verbatim */
/* > Y is COMPLEX*16 array, dimension */
/* > (LDY,NRHS) */
/* > On entry, the solution matrix X, as computed by ZPOTRS. */
/* > On exit, the improved solution matrix Y. */
/* > \endverbatim */
/* > */
/* > \param[in] LDY */
/* > \verbatim */
/* > LDY is INTEGER */
/* > The leading dimension of the array Y. LDY >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] BERR_OUT */
/* > \verbatim */
/* > BERR_OUT is DOUBLE PRECISION array, dimension (NRHS) */
/* > On exit, BERR_OUT(j) contains the componentwise relative backward */
/* > error for right-hand-side j from the formula */
/* > max(i) ( f2c_abs(RES(i)) / ( f2c_abs(op(A_s))*f2c_abs(Y) + f2c_abs(B_s) )(i) ) */
/* > where f2c_abs(Z) is the componentwise absolute value of the matrix */
/* > or vector Z. This is computed by ZLA_LIN_BERR. */
/* > \endverbatim */
/* > */
/* > \param[in] N_NORMS */
/* > \verbatim */
/* > N_NORMS is INTEGER */
/* > Determines which error bounds to return (see ERR_BNDS_NORM */
/* > and ERR_BNDS_COMP). */
/* > If N_NORMS >= 1 return normwise error bounds. */
/* > If N_NORMS >= 2 return componentwise error bounds. */
/* > \endverbatim */
/* > */
/* > \param[in,out] ERR_BNDS_NORM */
/* > \verbatim */
/* > ERR_BNDS_NORM is DOUBLE PRECISION array, dimension */
/* > (NRHS, N_ERR_BNDS) */
/* > For each right-hand side, this array contains information about */
/* > various error bounds and condition numbers corresponding to the */
/* > normwise relative error, which is defined as follows: */
/* > */
/* > Normwise relative error in the ith solution vector: */
/* > max_j (f2c_abs(XTRUE(j,i) - X(j,i))) */
/* > ------------------------------ */
/* > max_j f2c_abs(X(j,i)) */
/* > */
/* > The array is indexed by the type of error information as described */
/* > below. There currently are up to three pieces of information */
/* > returned. */
/* > */
/* > The first index in ERR_BNDS_NORM(i,:) corresponds to the ith */
/* > right-hand side. */
/* > */
/* > The second index in ERR_BNDS_NORM(:,err) contains the following */
/* > three fields: */
/* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */
/* > reciprocal condition number is less than the threshold */
/* > sqrt(n) * slamch('Epsilon'). */
/* > */
/* > err = 2 "Guaranteed" error bound: The estimated forward error, */
/* > almost certainly within a factor of 10 of the true error */
/* > so long as the next entry is greater than the threshold */
/* > sqrt(n) * slamch('Epsilon'). This error bound should only */
/* > be trusted if the previous boolean is true. */
/* > */
/* > err = 3 Reciprocal condition number: Estimated normwise */
/* > reciprocal condition number. Compared with the threshold */
/* > sqrt(n) * slamch('Epsilon') to determine if the error */
/* > estimate is "guaranteed". These reciprocal condition */
/* > numbers are 1 / (norm(Z^{
-1}
,inf) * norm(Z,inf)) for some */
/* > appropriately scaled matrix Z. */
/* > Let Z = S*A, where S scales each row by a power of the */
/* > radix so all absolute row sums of Z are approximately 1. */
/* > */
/* > This subroutine is only responsible for setting the second field */
/* > above. */
/* > See Lapack Working Note 165 for further details and extra */
/* > cautions. */
/* > \endverbatim */
/* > */
/* > \param[in,out] ERR_BNDS_COMP */
/* > \verbatim */
/* > ERR_BNDS_COMP is DOUBLE PRECISION array, dimension */
/* > (NRHS, N_ERR_BNDS) */
/* > For each right-hand side, this array contains information about */
/* > various error bounds and condition numbers corresponding to the */
/* > componentwise relative error, which is defined as follows: */
/* > */
/* > Componentwise relative error in the ith solution vector: */
/* > f2c_abs(XTRUE(j,i) - X(j,i)) */
/* > max_j ---------------------- */
/* > f2c_abs(X(j,i)) */
/* > */
/* > The array is indexed by the right-hand side i (on which the */
/* > componentwise relative error depends), and the type of error */
/* > information as described below. There currently are up to three */
/* > pieces of information returned for each right-hand side. If */
/* > componentwise accuracy is not requested (PARAMS(3) = 0.0), then */
/* > ERR_BNDS_COMP is not accessed. If N_ERR_BNDS .LT. 3, then at most */
/* > the first (:,N_ERR_BNDS) entries are returned. */
/* > */
/* > The first index in ERR_BNDS_COMP(i,:) corresponds to the ith */
/* > right-hand side. */
/* > */
/* > The second index in ERR_BNDS_COMP(:,err) contains the following */
/* > three fields: */
/* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */
/* > reciprocal condition number is less than the threshold */
/* > sqrt(n) * slamch('Epsilon'). */
/* > */
/* > err = 2 "Guaranteed" error bound: The estimated forward error, */
/* > almost certainly within a factor of 10 of the true error */
/* > so long as the next entry is greater than the threshold */
/* > sqrt(n) * slamch('Epsilon'). This error bound should only */
/* > be trusted if the previous boolean is true. */
/* > */
/* > err = 3 Reciprocal condition number: Estimated componentwise */
/* > reciprocal condition number. Compared with the threshold */
/* > sqrt(n) * slamch('Epsilon') to determine if the error */
/* > estimate is "guaranteed". These reciprocal condition */
/* > numbers are 1 / (norm(Z^{
-1}
,inf) * norm(Z,inf)) for some */
/* > appropriately scaled matrix Z. */
/* > Let Z = S*(A*diag(x)), where x is the solution for the */
/* > current right-hand side and S scales each row of */
/* > A*diag(x) by a power of the radix so all absolute row */
/* > sums of Z are approximately 1. */
/* > */
/* > This subroutine is only responsible for setting the second field */
/* > above. */
/* > See Lapack Working Note 165 for further details and extra */
/* > cautions. */
/* > \endverbatim */
/* > */
/* > \param[in] RES */
/* > \verbatim */
/* > RES is COMPLEX*16 array, dimension (N) */
/* > Workspace to hold the intermediate residual. */
/* > \endverbatim */
/* > */
/* > \param[in] AYB */
/* > \verbatim */
/* > AYB is DOUBLE PRECISION array, dimension (N) */
/* > Workspace. */
/* > \endverbatim */
/* > */
/* > \param[in] DY */
/* > \verbatim */
/* > DY is COMPLEX*16 PRECISION array, dimension (N) */
/* > Workspace to hold the intermediate solution. */
/* > \endverbatim */
/* > */
/* > \param[in] Y_TAIL */
/* > \verbatim */
/* > Y_TAIL is COMPLEX*16 array, dimension (N) */
/* > Workspace to hold the trailing bits of the intermediate solution. */
/* > \endverbatim */
/* > */
/* > \param[in] RCOND */
/* > \verbatim */
/* > RCOND is DOUBLE PRECISION */
/* > Reciprocal scaled condition number. This is an estimate of the */
/* > reciprocal Skeel condition number of the matrix A after */
/* > equilibration (if done). If this is less than the machine */
/* > precision (in particular, if it is zero), the matrix is singular */
/* > to working precision. Note that the error may still be small even */
/* > if this number is very small and the matrix appears ill- */
/* > conditioned. */
/* > \endverbatim */
/* > */
/* > \param[in] ITHRESH */
/* > \verbatim */
/* > ITHRESH is INTEGER */
/* > The maximum number of residual computations allowed for */
/* > refinement. The default is 10. For 'aggressive' set to 100 to */
/* > permit convergence using approximate factorizations or */
/* > factorizations other than LU. If the factorization uses a */
/* > technique other than Gaussian elimination, the guarantees in */
/* > ERR_BNDS_NORM and ERR_BNDS_COMP may no longer be trustworthy. */
/* > \endverbatim */
/* > */
/* > \param[in] RTHRESH */
/* > \verbatim */
/* > RTHRESH is DOUBLE PRECISION */
/* > Determines when to stop refinement if the error estimate stops */
/* > decreasing. Refinement will stop when the next solution no longer */
/* > satisfies norm(dx_{
i+1}
) < RTHRESH * norm(dx_i) where norm(Z) is */
/* > the infinity norm of Z. RTHRESH satisfies 0 < RTHRESH <= 1. The */
/* > default value is 0.5. For 'aggressive' set to 0.9 to permit */
/* > convergence on extremely ill-conditioned matrices. See LAWN 165 */
/* > for more details. */
/* > \endverbatim */
/* > */
/* > \param[in] DZ_UB */
/* > \verbatim */
/* > DZ_UB is DOUBLE PRECISION */
/* > Determines when to start considering componentwise convergence. */
/* > Componentwise convergence is only considered after each component */
/* > of the solution Y is stable, which we definte as the relative */
/* > change in each component being less than DZ_UB. The default value */
/* > is 0.25, requiring the first bit to be stable. See LAWN 165 for */
/* > more details. */
/* > \endverbatim */
/* > */
/* > \param[in] IGNORE_CWISE */
/* > \verbatim */
/* > IGNORE_CWISE is LOGICAL */
/* > If .TRUE. then ignore componentwise convergence. Default value */
/* > is .FALSE.. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: Successful exit. */
/* > < 0: if INFO = -i, the ith argument to ZPOTRS had an illegal */
/* > value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date September 2012 */
/* > \ingroup complex16POcomputational */
/* ===================================================================== */
/* Subroutine */
int zla_porfsx_extended_(integer *prec_type__, char *uplo, integer *n, integer *nrhs, doublecomplex *a, integer *lda, doublecomplex *af, integer *ldaf, logical *colequ, doublereal *c__, doublecomplex *b, integer *ldb, doublecomplex *y, integer *ldy, doublereal *berr_out__, integer *n_norms__, doublereal * err_bnds_norm__, doublereal *err_bnds_comp__, doublecomplex *res, doublereal *ayb, doublecomplex *dy, doublecomplex *y_tail__, doublereal *rcond, integer *ithresh, doublereal *rthresh, doublereal * dz_ub__, logical *ignore_cwise__, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, af_dim1, af_offset, b_dim1, b_offset, y_dim1, y_offset, err_bnds_norm_dim1, err_bnds_norm_offset, err_bnds_comp_dim1, err_bnds_comp_offset, i__1, i__2, i__3, i__4;
doublereal d__1, d__2;
/* Builtin functions */
double d_imag(doublecomplex *);
/* Local variables */
doublereal dxratmax, dzratmax;
integer i__, j;
logical incr_prec__;
extern /* Subroutine */
int zla_heamv_(integer *, integer *, doublereal * , doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, integer *);
doublereal prev_dz_z__, yk, final_dx_x__, final_dz_z__;
extern /* Subroutine */
int zla_wwaddw_(integer *, doublecomplex *, doublecomplex *, doublecomplex *);
doublereal prevnormdx;
integer cnt;
doublereal dyk, eps, incr_thresh__, dx_x__, dz_z__, ymin;
extern /* Subroutine */
int zla_lin_berr_(integer *, integer *, integer * , doublecomplex *, doublereal *, doublereal *);
integer y_prec_state__;
extern /* Subroutine */
int blas_zhemv_x_(integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *) ;
integer uplo2;
extern logical lsame_(char *, char *);
extern /* Subroutine */
int blas_zhemv2_x_(integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *);
doublereal dxrat, dzrat;
extern /* Subroutine */
int zhemv_(char *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *);
doublereal normx, normy;
extern /* Subroutine */
int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *);
extern doublereal dlamch_(char *);
doublereal normdx;
extern /* Subroutine */
int zpotrs_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer *);
doublereal hugeval;
extern integer ilauplo_(char *);
integer x_state__, z_state__;
/* -- LAPACK computational routine (version 3.4.2) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* September 2012 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ===================================================================== */
/* .. Local Scalars .. */
/* .. */
/* .. Parameters .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Statement Functions .. */
/* .. */
/* .. Statement Function Definitions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
err_bnds_comp_dim1 = *nrhs;
err_bnds_comp_offset = 1 + err_bnds_comp_dim1;
err_bnds_comp__ -= err_bnds_comp_offset;
err_bnds_norm_dim1 = *nrhs;
err_bnds_norm_offset = 1 + err_bnds_norm_dim1;
err_bnds_norm__ -= err_bnds_norm_offset;
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
af_dim1 = *ldaf;
af_offset = 1 + af_dim1;
af -= af_offset;
--c__;
b_dim1 = *ldb;
b_offset = 1 + b_dim1;
b -= b_offset;
y_dim1 = *ldy;
y_offset = 1 + y_dim1;
y -= y_offset;
--berr_out__;
--res;
--ayb;
--dy;
--y_tail__;
/* Function Body */
if (*info != 0)
{
return 0;
}
eps = dlamch_("Epsilon");
hugeval = dlamch_("Overflow");
/* Force HUGEVAL to Inf */
hugeval *= hugeval;
/* Using HUGEVAL may lead to spurious underflows. */
incr_thresh__ = (doublereal) (*n) * eps;
if (lsame_(uplo, "L"))
{
uplo2 = ilauplo_("L");
}
else
{
uplo2 = ilauplo_("U");
}
i__1 = *nrhs;
for (j = 1;
j <= i__1;
++j)
{
y_prec_state__ = 1;
if (y_prec_state__ == 2)
{
i__2 = *n;
for (i__ = 1;
i__ <= i__2;
++i__)
{
i__3 = i__;
y_tail__[i__3].r = 0.;
y_tail__[i__3].i = 0.; // , expr subst
}
}
dxrat = 0.;
dxratmax = 0.;
dzrat = 0.;
dzratmax = 0.;
final_dx_x__ = hugeval;
final_dz_z__ = hugeval;
prevnormdx = hugeval;
prev_dz_z__ = hugeval;
dz_z__ = hugeval;
dx_x__ = hugeval;
x_state__ = 1;
z_state__ = 0;
incr_prec__ = FALSE_;
i__2 = *ithresh;
for (cnt = 1;
cnt <= i__2;
++cnt)
{
/* Compute residual RES = B_s - op(A_s) * Y, */
/* op(A) = A, A**T, or A**H depending on TRANS (and type). */
zcopy_(n, &b[j * b_dim1 + 1], &c__1, &res[1], &c__1);
if (y_prec_state__ == 0)
{
zhemv_(uplo, n, &c_b11, &a[a_offset], lda, &y[j * y_dim1 + 1], &c__1, &c_b12, &res[1], &c__1);
}
else if (y_prec_state__ == 1)
{
blas_zhemv_x_(&uplo2, n, &c_b11, &a[a_offset], lda, &y[j * y_dim1 + 1], &c__1, &c_b12, &res[1], &c__1, prec_type__);
}
else
{
blas_zhemv2_x_(&uplo2, n, &c_b11, &a[a_offset], lda, &y[j * y_dim1 + 1], &y_tail__[1], &c__1, &c_b12, &res[1], & c__1, prec_type__);
}
/* XXX: RES is no longer needed. */
zcopy_(n, &res[1], &c__1, &dy[1], &c__1);
zpotrs_(uplo, n, &c__1, &af[af_offset], ldaf, &dy[1], n, info);
/* Calculate relative changes DX_X, DZ_Z and ratios DXRAT, DZRAT. */
normx = 0.;
normy = 0.;
normdx = 0.;
dz_z__ = 0.;
ymin = hugeval;
i__3 = *n;
for (i__ = 1;
i__ <= i__3;
++i__)
{
i__4 = i__ + j * y_dim1;
yk = (d__1 = y[i__4].r, f2c_abs(d__1)) + (d__2 = d_imag(&y[i__ + j * y_dim1]), f2c_abs(d__2));
i__4 = i__;
dyk = (d__1 = dy[i__4].r, f2c_abs(d__1)) + (d__2 = d_imag(&dy[i__] ), f2c_abs(d__2));
if (yk != 0.)
{
/* Computing MAX */
d__1 = dz_z__;
d__2 = dyk / yk; // , expr subst
dz_z__ = max(d__1,d__2);
}
else if (dyk != 0.)
{
dz_z__ = hugeval;
}
ymin = min(ymin,yk);
normy = max(normy,yk);
if (*colequ)
{
/* Computing MAX */
d__1 = normx;
d__2 = yk * c__[i__]; // , expr subst
normx = max(d__1,d__2);
/* Computing MAX */
d__1 = normdx;
d__2 = dyk * c__[i__]; // , expr subst
normdx = max(d__1,d__2);
}
else
{
normx = normy;
normdx = max(normdx,dyk);
}
}
if (normx != 0.)
{
dx_x__ = normdx / normx;
}
else if (normdx == 0.)
{
dx_x__ = 0.;
}
else
{
dx_x__ = hugeval;
}
dxrat = normdx / prevnormdx;
dzrat = dz_z__ / prev_dz_z__;
/* Check termination criteria. */
if (ymin * *rcond < incr_thresh__ * normy && y_prec_state__ < 2)
{
incr_prec__ = TRUE_;
}
if (x_state__ == 3 && dxrat <= *rthresh)
{
x_state__ = 1;
}
if (x_state__ == 1)
{
if (dx_x__ <= eps)
{
x_state__ = 2;
}
else if (dxrat > *rthresh)
{
if (y_prec_state__ != 2)
{
incr_prec__ = TRUE_;
}
else
{
x_state__ = 3;
}
}
else
{
if (dxrat > dxratmax)
{
dxratmax = dxrat;
}
}
if (x_state__ > 1)
{
final_dx_x__ = dx_x__;
}
}
if (z_state__ == 0 && dz_z__ <= *dz_ub__)
{
z_state__ = 1;
}
if (z_state__ == 3 && dzrat <= *rthresh)
{
z_state__ = 1;
}
if (z_state__ == 1)
{
if (dz_z__ <= eps)
{
z_state__ = 2;
}
else if (dz_z__ > *dz_ub__)
{
z_state__ = 0;
dzratmax = 0.;
final_dz_z__ = hugeval;
}
else if (dzrat > *rthresh)
{
if (y_prec_state__ != 2)
{
incr_prec__ = TRUE_;
}
else
{
z_state__ = 3;
}
}
else
{
if (dzrat > dzratmax)
{
dzratmax = dzrat;
}
}
if (z_state__ > 1)
{
final_dz_z__ = dz_z__;
}
}
if (x_state__ != 1 && (*ignore_cwise__ || z_state__ != 1))
{
goto L666;
}
if (incr_prec__)
{
incr_prec__ = FALSE_;
++y_prec_state__;
i__3 = *n;
for (i__ = 1;
i__ <= i__3;
++i__)
{
i__4 = i__;
y_tail__[i__4].r = 0.;
y_tail__[i__4].i = 0.; // , expr subst
}
}
prevnormdx = normdx;
prev_dz_z__ = dz_z__;
/* Update soluton. */
if (y_prec_state__ < 2)
{
zaxpy_(n, &c_b12, &dy[1], &c__1, &y[j * y_dim1 + 1], &c__1);
}
else
{
zla_wwaddw_(n, &y[j * y_dim1 + 1], &y_tail__[1], &dy[1]);
}
}
/* Target of "IF (Z_STOP .AND. X_STOP)". Sun's f77 won't CALL F90_EXIT. */
L666: /* Set final_* when cnt hits ithresh. */
if (x_state__ == 1)
{
final_dx_x__ = dx_x__;
}
if (z_state__ == 1)
{
final_dz_z__ = dz_z__;
}
/* Compute error bounds. */
if (*n_norms__ >= 1)
{
err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = final_dx_x__ / ( 1 - dxratmax);
}
if (*n_norms__ >= 2)
{
err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = final_dz_z__ / ( 1 - dzratmax);
}
/* Compute componentwise relative backward error from formula */
/* max(i) ( f2c_abs(R(i)) / ( f2c_abs(op(A_s))*f2c_abs(Y) + f2c_abs(B_s) )(i) ) */
/* where f2c_abs(Z) is the componentwise absolute value of the matrix */
/* or vector Z. */
/* Compute residual RES = B_s - op(A_s) * Y, */
/* op(A) = A, A**T, or A**H depending on TRANS (and type). */
zcopy_(n, &b[j * b_dim1 + 1], &c__1, &res[1], &c__1);
zhemv_(uplo, n, &c_b11, &a[a_offset], lda, &y[j * y_dim1 + 1], &c__1, &c_b12, &res[1], &c__1);
i__2 = *n;
for (i__ = 1;
i__ <= i__2;
++i__)
{
i__3 = i__ + j * b_dim1;
ayb[i__] = (d__1 = b[i__3].r, f2c_abs(d__1)) + (d__2 = d_imag(&b[i__ + j * b_dim1]), f2c_abs(d__2));
}
/* Compute f2c_abs(op(A_s))*f2c_abs(Y) + f2c_abs(B_s). */
zla_heamv_(&uplo2, n, &c_b34, &a[a_offset], lda, &y[j * y_dim1 + 1], &c__1, &c_b34, &ayb[1], &c__1);
zla_lin_berr_(n, n, &c__1, &res[1], &ayb[1], &berr_out__[j]);
/* End of loop for each RHS. */
}
return 0;
}
/* zla_porfsx_extended__ */
#endif
|
495431.c | /*
* X.509 test certificates
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#include "common.h"
#include "mbedtls/certs.h"
#if defined(MBEDTLS_CERTS_C)
/*
* Test CA Certificates
*
* We define test CA certificates for each choice of the following parameters:
* - PEM or DER encoding
* - SHA-1 or SHA-256 hash
* - RSA or EC key
*
* Things to add:
* - multiple EC curve types
*
*/
/* This is taken from tests/data_files/test-ca2.crt */
/* BEGIN FILE string macro TEST_CA_CRT_EC_PEM tests/data_files/test-ca2.crt */
#define TEST_CA_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIICBDCCAYigAwIBAgIJAMFD4n5iQ8zoMAwGCCqGSM49BAMCBQAwPjELMAkGA1UE\r\n" \
"BhMCTkwxETAPBgNVBAoMCFBvbGFyU1NMMRwwGgYDVQQDDBNQb2xhcnNzbCBUZXN0\r\n" \
"IEVDIENBMB4XDTE5MDIxMDE0NDQwMFoXDTI5MDIxMDE0NDQwMFowPjELMAkGA1UE\r\n" \
"BhMCTkwxETAPBgNVBAoMCFBvbGFyU1NMMRwwGgYDVQQDDBNQb2xhcnNzbCBUZXN0\r\n" \
"IEVDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEw9orNEE3WC+HVv78ibopQ0tO\r\n" \
"4G7DDldTMzlY1FK0kZU5CyPfXxckYkj8GpUpziwth8KIUoCv1mqrId240xxuWLjK\r\n" \
"6LJpjvNBrSnDtF91p0dv1RkpVWmaUzsgtGYWYDMeo1AwTjAMBgNVHRMEBTADAQH/\r\n" \
"MB0GA1UdDgQWBBSdbSAkSQE/K8t4tRm8fiTJ2/s2fDAfBgNVHSMEGDAWgBSdbSAk\r\n" \
"SQE/K8t4tRm8fiTJ2/s2fDAMBggqhkjOPQQDAgUAA2gAMGUCMFHKrjAPpHB0BN1a\r\n" \
"LH8TwcJ3vh0AxeKZj30mRdOKBmg/jLS3rU3g8VQBHpn8sOTTBwIxANxPO5AerimZ\r\n" \
"hCjMe0d4CTHf1gFZMF70+IqEP+o5VHsIp2Cqvflb0VGWFC5l9a4cQg==\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/test-ca2.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_CRT_EC_DER tests/data_files/test-ca2.crt.der */
#define TEST_CA_CRT_EC_DER { \
0x30, 0x82, 0x02, 0x04, 0x30, 0x82, 0x01, 0x88, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x09, 0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8, \
0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, \
0x05, 0x00, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, \
0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, \
0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x50, \
0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, \
0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x39, \
0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, 0x5a, 0x17, \
0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, \
0x30, 0x5a, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, \
0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, \
0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x50, \
0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, \
0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, \
0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, \
0x00, 0x22, 0x03, 0x62, 0x00, 0x04, 0xc3, 0xda, 0x2b, 0x34, 0x41, 0x37, \
0x58, 0x2f, 0x87, 0x56, 0xfe, 0xfc, 0x89, 0xba, 0x29, 0x43, 0x4b, 0x4e, \
0xe0, 0x6e, 0xc3, 0x0e, 0x57, 0x53, 0x33, 0x39, 0x58, 0xd4, 0x52, 0xb4, \
0x91, 0x95, 0x39, 0x0b, 0x23, 0xdf, 0x5f, 0x17, 0x24, 0x62, 0x48, 0xfc, \
0x1a, 0x95, 0x29, 0xce, 0x2c, 0x2d, 0x87, 0xc2, 0x88, 0x52, 0x80, 0xaf, \
0xd6, 0x6a, 0xab, 0x21, 0xdd, 0xb8, 0xd3, 0x1c, 0x6e, 0x58, 0xb8, 0xca, \
0xe8, 0xb2, 0x69, 0x8e, 0xf3, 0x41, 0xad, 0x29, 0xc3, 0xb4, 0x5f, 0x75, \
0xa7, 0x47, 0x6f, 0xd5, 0x19, 0x29, 0x55, 0x69, 0x9a, 0x53, 0x3b, 0x20, \
0xb4, 0x66, 0x16, 0x60, 0x33, 0x1e, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x0c, \
0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, \
0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x9d, \
0x6d, 0x20, 0x24, 0x49, 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, \
0x7e, 0x24, 0xc9, 0xdb, 0xfb, 0x36, 0x7c, 0x30, 0x1f, 0x06, 0x03, 0x55, \
0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, \
0x49, 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, \
0xdb, 0xfb, 0x36, 0x7c, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, \
0x30, 0x51, 0xca, 0xae, 0x30, 0x0f, 0xa4, 0x70, 0x74, 0x04, 0xdd, 0x5a, \
0x2c, 0x7f, 0x13, 0xc1, 0xc2, 0x77, 0xbe, 0x1d, 0x00, 0xc5, 0xe2, 0x99, \
0x8f, 0x7d, 0x26, 0x45, 0xd3, 0x8a, 0x06, 0x68, 0x3f, 0x8c, 0xb4, 0xb7, \
0xad, 0x4d, 0xe0, 0xf1, 0x54, 0x01, 0x1e, 0x99, 0xfc, 0xb0, 0xe4, 0xd3, \
0x07, 0x02, 0x31, 0x00, 0xdc, 0x4f, 0x3b, 0x90, 0x1e, 0xae, 0x29, 0x99, \
0x84, 0x28, 0xcc, 0x7b, 0x47, 0x78, 0x09, 0x31, 0xdf, 0xd6, 0x01, 0x59, \
0x30, 0x5e, 0xf4, 0xf8, 0x8a, 0x84, 0x3f, 0xea, 0x39, 0x54, 0x7b, 0x08, \
0xa7, 0x60, 0xaa, 0xbd, 0xf9, 0x5b, 0xd1, 0x51, 0x96, 0x14, 0x2e, 0x65, \
0xf5, 0xae, 0x1c, 0x42 \
}
/* END FILE */
/* This is taken from tests/data_files/test-ca2.key.enc */
/* BEGIN FILE string macro TEST_CA_KEY_EC_PEM tests/data_files/test-ca2.key.enc */
#define TEST_CA_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"Proc-Type: 4,ENCRYPTED\r\n" \
"DEK-Info: DES-EDE3-CBC,307EAB469933D64E\r\n" \
"\r\n" \
"IxbrRmKcAzctJqPdTQLA4SWyBYYGYJVkYEna+F7Pa5t5Yg/gKADrFKcm6B72e7DG\r\n" \
"ihExtZI648s0zdYw6qSJ74vrPSuWDe5qm93BqsfVH9svtCzWHW0pm1p0KTBCFfUq\r\n" \
"UsuWTITwJImcnlAs1gaRZ3sAWm7cOUidL0fo2G0fYUFNcYoCSLffCFTEHBuPnagb\r\n" \
"a77x/sY1Bvii8S9/XhDTb6pTMx06wzrm\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
#define TEST_CA_PWD_EC_PEM "PolarSSLTest"
/* This is generated from tests/data_files/test-ca2.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_KEY_EC_DER tests/data_files/test-ca2.key.der */
#define TEST_CA_KEY_EC_DER { \
0x30, 0x81, 0xa4, 0x02, 0x01, 0x01, 0x04, 0x30, 0x83, 0xd9, 0x15, 0x0e, \
0xa0, 0x71, 0xf0, 0x57, 0x10, 0x33, 0xa3, 0x38, 0xb8, 0x86, 0xc1, 0xa6, \
0x11, 0x5d, 0x6d, 0xb4, 0x03, 0xe1, 0x29, 0x76, 0x45, 0xd7, 0x87, 0x6f, \
0x23, 0xab, 0x44, 0x20, 0xea, 0x64, 0x7b, 0x85, 0xb1, 0x76, 0xe7, 0x85, \
0x95, 0xaa, 0x74, 0xd6, 0xd1, 0xa4, 0x5e, 0xea, 0xa0, 0x07, 0x06, 0x05, \
0x2b, 0x81, 0x04, 0x00, 0x22, 0xa1, 0x64, 0x03, 0x62, 0x00, 0x04, 0xc3, \
0xda, 0x2b, 0x34, 0x41, 0x37, 0x58, 0x2f, 0x87, 0x56, 0xfe, 0xfc, 0x89, \
0xba, 0x29, 0x43, 0x4b, 0x4e, 0xe0, 0x6e, 0xc3, 0x0e, 0x57, 0x53, 0x33, \
0x39, 0x58, 0xd4, 0x52, 0xb4, 0x91, 0x95, 0x39, 0x0b, 0x23, 0xdf, 0x5f, \
0x17, 0x24, 0x62, 0x48, 0xfc, 0x1a, 0x95, 0x29, 0xce, 0x2c, 0x2d, 0x87, \
0xc2, 0x88, 0x52, 0x80, 0xaf, 0xd6, 0x6a, 0xab, 0x21, 0xdd, 0xb8, 0xd3, \
0x1c, 0x6e, 0x58, 0xb8, 0xca, 0xe8, 0xb2, 0x69, 0x8e, 0xf3, 0x41, 0xad, \
0x29, 0xc3, 0xb4, 0x5f, 0x75, 0xa7, 0x47, 0x6f, 0xd5, 0x19, 0x29, 0x55, \
0x69, 0x9a, 0x53, 0x3b, 0x20, 0xb4, 0x66, 0x16, 0x60, 0x33, 0x1e \
}
/* END FILE */
/* This is taken from tests/data_files/test-ca-sha256.crt. */
/* BEGIN FILE string macro TEST_CA_CRT_RSA_SHA256_PEM tests/data_files/test-ca-sha256.crt */
#define TEST_CA_CRT_RSA_SHA256_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDQTCCAimgAwIBAgIBAzANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTkwMjEwMTQ0NDAwWhcNMjkwMjEwMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \
"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \
"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \
"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \
"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \
"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \
"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \
"UDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/\r\n" \
"MB8GA1UdIwQYMBaAFLRa5KWz3tJS9rnVppUP6z68x/3/MA0GCSqGSIb3DQEBCwUA\r\n" \
"A4IBAQA4qFSCth2q22uJIdE4KGHJsJjVEfw2/xn+MkTvCMfxVrvmRvqCtjE4tKDl\r\n" \
"oK4MxFOek07oDZwvtAT9ijn1hHftTNS7RH9zd/fxNpfcHnMZXVC4w4DNA1fSANtW\r\n" \
"5sY1JB5Je9jScrsLSS+mAjyv0Ow3Hb2Bix8wu7xNNrV5fIf7Ubm+wt6SqEBxu3Kb\r\n" \
"+EfObAT4huf3czznhH3C17ed6NSbXwoXfby7stWUDeRJv08RaFOykf/Aae7bY5PL\r\n" \
"yTVrkAnikMntJ9YI+hNNYt3inqq11A5cN0+rVTst8UKCxzQ4GpvroSwPKTFkbMw4\r\n" \
"/anT1dVxr/BtwJfiESoK3/4CeXR1\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/test-ca-sha256.crt.der
* using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_CRT_RSA_SHA256_DER tests/data_files/test-ca-sha256.crt.der */
#define TEST_CA_CRT_RSA_SHA256_DER { \
0x30, 0x82, 0x03, 0x41, 0x30, 0x82, 0x02, 0x29, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x03, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \
0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \
0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \
0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, \
0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \
0x34, 0x30, 0x30, 0x5a, 0x30, 0x3b, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \
0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x54, 0x65, \
0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, \
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, \
0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, \
0x01, 0x00, 0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, \
0x86, 0xde, 0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, \
0x99, 0xd4, 0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, \
0x9b, 0xc5, 0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, \
0xc0, 0x8d, 0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, \
0x93, 0xe8, 0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, \
0xe7, 0x40, 0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, \
0xf9, 0x3e, 0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, \
0x29, 0x00, 0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, \
0xbd, 0x83, 0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, \
0x60, 0xc3, 0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, \
0x32, 0xbe, 0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, \
0xfb, 0xf5, 0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, \
0xee, 0xe2, 0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, \
0x47, 0xb1, 0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, \
0xf1, 0x79, 0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, \
0x6f, 0x27, 0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, \
0xa1, 0x30, 0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, \
0x28, 0xd1, 0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, \
0x09, 0xea, 0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, \
0xc9, 0xab, 0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, \
0x9e, 0x99, 0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, \
0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, \
0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, \
0x04, 0x16, 0x04, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, \
0xf6, 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, \
0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, \
0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, \
0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, \
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, \
0x03, 0x82, 0x01, 0x01, 0x00, 0x38, 0xa8, 0x54, 0x82, 0xb6, 0x1d, 0xaa, \
0xdb, 0x6b, 0x89, 0x21, 0xd1, 0x38, 0x28, 0x61, 0xc9, 0xb0, 0x98, 0xd5, \
0x11, 0xfc, 0x36, 0xff, 0x19, 0xfe, 0x32, 0x44, 0xef, 0x08, 0xc7, 0xf1, \
0x56, 0xbb, 0xe6, 0x46, 0xfa, 0x82, 0xb6, 0x31, 0x38, 0xb4, 0xa0, 0xe5, \
0xa0, 0xae, 0x0c, 0xc4, 0x53, 0x9e, 0x93, 0x4e, 0xe8, 0x0d, 0x9c, 0x2f, \
0xb4, 0x04, 0xfd, 0x8a, 0x39, 0xf5, 0x84, 0x77, 0xed, 0x4c, 0xd4, 0xbb, \
0x44, 0x7f, 0x73, 0x77, 0xf7, 0xf1, 0x36, 0x97, 0xdc, 0x1e, 0x73, 0x19, \
0x5d, 0x50, 0xb8, 0xc3, 0x80, 0xcd, 0x03, 0x57, 0xd2, 0x00, 0xdb, 0x56, \
0xe6, 0xc6, 0x35, 0x24, 0x1e, 0x49, 0x7b, 0xd8, 0xd2, 0x72, 0xbb, 0x0b, \
0x49, 0x2f, 0xa6, 0x02, 0x3c, 0xaf, 0xd0, 0xec, 0x37, 0x1d, 0xbd, 0x81, \
0x8b, 0x1f, 0x30, 0xbb, 0xbc, 0x4d, 0x36, 0xb5, 0x79, 0x7c, 0x87, 0xfb, \
0x51, 0xb9, 0xbe, 0xc2, 0xde, 0x92, 0xa8, 0x40, 0x71, 0xbb, 0x72, 0x9b, \
0xf8, 0x47, 0xce, 0x6c, 0x04, 0xf8, 0x86, 0xe7, 0xf7, 0x73, 0x3c, 0xe7, \
0x84, 0x7d, 0xc2, 0xd7, 0xb7, 0x9d, 0xe8, 0xd4, 0x9b, 0x5f, 0x0a, 0x17, \
0x7d, 0xbc, 0xbb, 0xb2, 0xd5, 0x94, 0x0d, 0xe4, 0x49, 0xbf, 0x4f, 0x11, \
0x68, 0x53, 0xb2, 0x91, 0xff, 0xc0, 0x69, 0xee, 0xdb, 0x63, 0x93, 0xcb, \
0xc9, 0x35, 0x6b, 0x90, 0x09, 0xe2, 0x90, 0xc9, 0xed, 0x27, 0xd6, 0x08, \
0xfa, 0x13, 0x4d, 0x62, 0xdd, 0xe2, 0x9e, 0xaa, 0xb5, 0xd4, 0x0e, 0x5c, \
0x37, 0x4f, 0xab, 0x55, 0x3b, 0x2d, 0xf1, 0x42, 0x82, 0xc7, 0x34, 0x38, \
0x1a, 0x9b, 0xeb, 0xa1, 0x2c, 0x0f, 0x29, 0x31, 0x64, 0x6c, 0xcc, 0x38, \
0xfd, 0xa9, 0xd3, 0xd5, 0xd5, 0x71, 0xaf, 0xf0, 0x6d, 0xc0, 0x97, 0xe2, \
0x11, 0x2a, 0x0a, 0xdf, 0xfe, 0x02, 0x79, 0x74, 0x75 \
}
/* END FILE */
/* This is taken from tests/data_files/test-ca-sha1.crt. */
/* BEGIN FILE string macro TEST_CA_CRT_RSA_SHA1_PEM tests/data_files/test-ca-sha1.crt */
#define TEST_CA_CRT_RSA_SHA1_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDQTCCAimgAwIBAgIBAzANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTEwMjEyMTQ0NDAwWhcNMjEwMjEyMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \
"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \
"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \
"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \
"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \
"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \
"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \
"UDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/\r\n" \
"MB8GA1UdIwQYMBaAFLRa5KWz3tJS9rnVppUP6z68x/3/MA0GCSqGSIb3DQEBBQUA\r\n" \
"A4IBAQABE3OEPfEd/bcJW5ZdU3/VgPNS4tMzh8gnJP/V2FcvFtGylMpQq6YnEBYI\r\n" \
"yBHAL4DRvlMY5rnXGBp3ODR8MpqHC6AquRTCLzjS57iYff//4QFQqW9n92zctspv\r\n" \
"czkaPKgjqo1No3Uq0Xaz10rcxyTUPrf5wNVRZ2V0KvllvAAVSzbI4mpdUXztjhST\r\n" \
"S5A2BeWQAAOr0zq1F7TSRVJpJs7jmB2ai/igkh1IAjcuwV6VwlP+sbw0gjQ0NpGM\r\n" \
"iHpnlzRAi/tIbtOvMIGOBU2TIfax/5jq1agUx5aPmT5TWAiJPOOP6l5xXnDwxeYS\r\n" \
"NWqiX9GyusBZjezaCaHabjDLU0qQ\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is taken from tests/data_files/test-ca-sha1.crt.der. */
/* BEGIN FILE binary macro TEST_CA_CRT_RSA_SHA1_DER tests/data_files/test-ca-sha1.crt.der */
#define TEST_CA_CRT_RSA_SHA1_DER { \
0x30, 0x82, 0x03, 0x41, 0x30, 0x82, 0x02, 0x29, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x03, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \
0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \
0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, \
0x5a, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, \
0x34, 0x30, 0x30, 0x5a, 0x30, 0x3b, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \
0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x54, 0x65, \
0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, \
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, \
0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, \
0x01, 0x00, 0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, \
0x86, 0xde, 0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, \
0x99, 0xd4, 0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, \
0x9b, 0xc5, 0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, \
0xc0, 0x8d, 0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, \
0x93, 0xe8, 0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, \
0xe7, 0x40, 0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, \
0xf9, 0x3e, 0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, \
0x29, 0x00, 0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, \
0xbd, 0x83, 0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, \
0x60, 0xc3, 0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, \
0x32, 0xbe, 0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, \
0xfb, 0xf5, 0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, \
0xee, 0xe2, 0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, \
0x47, 0xb1, 0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, \
0xf1, 0x79, 0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, \
0x6f, 0x27, 0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, \
0xa1, 0x30, 0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, \
0x28, 0xd1, 0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, \
0x09, 0xea, 0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, \
0xc9, 0xab, 0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, \
0x9e, 0x99, 0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, \
0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, \
0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, \
0x04, 0x16, 0x04, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, \
0xf6, 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, \
0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, \
0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, \
0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, \
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, \
0x03, 0x82, 0x01, 0x01, 0x00, 0x01, 0x13, 0x73, 0x84, 0x3d, 0xf1, 0x1d, \
0xfd, 0xb7, 0x09, 0x5b, 0x96, 0x5d, 0x53, 0x7f, 0xd5, 0x80, 0xf3, 0x52, \
0xe2, 0xd3, 0x33, 0x87, 0xc8, 0x27, 0x24, 0xff, 0xd5, 0xd8, 0x57, 0x2f, \
0x16, 0xd1, 0xb2, 0x94, 0xca, 0x50, 0xab, 0xa6, 0x27, 0x10, 0x16, 0x08, \
0xc8, 0x11, 0xc0, 0x2f, 0x80, 0xd1, 0xbe, 0x53, 0x18, 0xe6, 0xb9, 0xd7, \
0x18, 0x1a, 0x77, 0x38, 0x34, 0x7c, 0x32, 0x9a, 0x87, 0x0b, 0xa0, 0x2a, \
0xb9, 0x14, 0xc2, 0x2f, 0x38, 0xd2, 0xe7, 0xb8, 0x98, 0x7d, 0xff, 0xff, \
0xe1, 0x01, 0x50, 0xa9, 0x6f, 0x67, 0xf7, 0x6c, 0xdc, 0xb6, 0xca, 0x6f, \
0x73, 0x39, 0x1a, 0x3c, 0xa8, 0x23, 0xaa, 0x8d, 0x4d, 0xa3, 0x75, 0x2a, \
0xd1, 0x76, 0xb3, 0xd7, 0x4a, 0xdc, 0xc7, 0x24, 0xd4, 0x3e, 0xb7, 0xf9, \
0xc0, 0xd5, 0x51, 0x67, 0x65, 0x74, 0x2a, 0xf9, 0x65, 0xbc, 0x00, 0x15, \
0x4b, 0x36, 0xc8, 0xe2, 0x6a, 0x5d, 0x51, 0x7c, 0xed, 0x8e, 0x14, 0x93, \
0x4b, 0x90, 0x36, 0x05, 0xe5, 0x90, 0x00, 0x03, 0xab, 0xd3, 0x3a, 0xb5, \
0x17, 0xb4, 0xd2, 0x45, 0x52, 0x69, 0x26, 0xce, 0xe3, 0x98, 0x1d, 0x9a, \
0x8b, 0xf8, 0xa0, 0x92, 0x1d, 0x48, 0x02, 0x37, 0x2e, 0xc1, 0x5e, 0x95, \
0xc2, 0x53, 0xfe, 0xb1, 0xbc, 0x34, 0x82, 0x34, 0x34, 0x36, 0x91, 0x8c, \
0x88, 0x7a, 0x67, 0x97, 0x34, 0x40, 0x8b, 0xfb, 0x48, 0x6e, 0xd3, 0xaf, \
0x30, 0x81, 0x8e, 0x05, 0x4d, 0x93, 0x21, 0xf6, 0xb1, 0xff, 0x98, 0xea, \
0xd5, 0xa8, 0x14, 0xc7, 0x96, 0x8f, 0x99, 0x3e, 0x53, 0x58, 0x08, 0x89, \
0x3c, 0xe3, 0x8f, 0xea, 0x5e, 0x71, 0x5e, 0x70, 0xf0, 0xc5, 0xe6, 0x12, \
0x35, 0x6a, 0xa2, 0x5f, 0xd1, 0xb2, 0xba, 0xc0, 0x59, 0x8d, 0xec, 0xda, \
0x09, 0xa1, 0xda, 0x6e, 0x30, 0xcb, 0x53, 0x4a, 0x90 \
}
/* END FILE */
/* This is taken from tests/data_files/test-ca.key */
/* BEGIN FILE string macro TEST_CA_KEY_RSA_PEM tests/data_files/test-ca.key */
#define TEST_CA_KEY_RSA_PEM \
"-----BEGIN RSA PRIVATE KEY-----\r\n" \
"Proc-Type: 4,ENCRYPTED\r\n" \
"DEK-Info: DES-EDE3-CBC,A8A95B05D5B7206B\r\n" \
"\r\n" \
"9Qd9GeArejl1GDVh2lLV1bHt0cPtfbh5h/5zVpAVaFpqtSPMrElp50Rntn9et+JA\r\n" \
"7VOyboR+Iy2t/HU4WvA687k3Bppe9GwKHjHhtl//8xFKwZr3Xb5yO5JUP8AUctQq\r\n" \
"Nb8CLlZyuUC+52REAAthdWgsX+7dJO4yabzUcQ22Tp9JSD0hiL43BlkWYUNK3dAo\r\n" \
"PZlmiptjnzVTjg1MxsBSydZinWOLBV8/JQgxSPo2yD4uEfig28qbvQ2wNIn0pnAb\r\n" \
"GxnSAOazkongEGfvcjIIs+LZN9gXFhxcOh6kc4Q/c99B7QWETwLLkYgZ+z1a9VY9\r\n" \
"gEU7CwCxYCD+h9hY6FPmsK0/lC4O7aeRKpYq00rPPxs6i7phiexg6ax6yTMmArQq\r\n" \
"QmK3TAsJm8V/J5AWpLEV6jAFgRGymGGHnof0DXzVWZidrcZJWTNuGEX90nB3ee2w\r\n" \
"PXJEFWKoD3K3aFcSLdHYr3mLGxP7H9ThQai9VsycxZKS5kwvBKQ//YMrmFfwPk8x\r\n" \
"vTeY4KZMaUrveEel5tWZC94RSMKgxR6cyE1nBXyTQnDOGbfpNNgBKxyKbINWoOJU\r\n" \
"WJZAwlsQn+QzCDwpri7+sV1mS3gBE6UY7aQmnmiiaC2V3Hbphxct/en5QsfDOt1X\r\n" \
"JczSfpRWLlbPznZg8OQh/VgCMA58N5DjOzTIK7sJJ5r+94ZBTCpgAMbF588f0NTR\r\n" \
"KCe4yrxGJR7X02M4nvD4IwOlpsQ8xQxZtOSgXv4LkxvdU9XJJKWZ/XNKJeWztxSe\r\n" \
"Z1vdTc2YfsDBA2SEv33vxHx2g1vqtw8SjDRT2RaQSS0QuSaMJimdOX6mTOCBKk1J\r\n" \
"9Q5mXTrER+/LnK0jEmXsBXWA5bqqVZIyahXSx4VYZ7l7w/PHiUDtDgyRhMMKi4n2\r\n" \
"iQvQcWSQTjrpnlJbca1/DkpRt3YwrvJwdqb8asZU2VrNETh5x0QVefDRLFiVpif/\r\n" \
"tUaeAe/P1F8OkS7OIZDs1SUbv/sD2vMbhNkUoCms3/PvNtdnvgL4F0zhaDpKCmlT\r\n" \
"P8vx49E7v5CyRNmED9zZg4o3wmMqrQO93PtTug3Eu9oVx1zPQM1NVMyBa2+f29DL\r\n" \
"1nuTCeXdo9+ni45xx+jAI4DCwrRdhJ9uzZyC6962H37H6D+5naNvClFR1s6li1Gb\r\n" \
"nqPoiy/OBsEx9CaDGcqQBp5Wme/3XW+6z1ISOx+igwNTVCT14mHdBMbya0eIKft5\r\n" \
"X+GnwtgEMyCYyyWuUct8g4RzErcY9+yW9Om5Hzpx4zOuW4NPZgPDTgK+t2RSL/Yq\r\n" \
"rE1njrgeGYcVeG3f+OftH4s6fPbq7t1A5ZgUscbLMBqr9tK+OqygR4EgKBPsH6Cz\r\n" \
"L6zlv/2RV0qAHvVuDJcIDIgwY5rJtINEm32rhOeFNJwZS5MNIC1czXZx5//ugX7l\r\n" \
"I4sy5nbVhwSjtAk8Xg5dZbdTZ6mIrb7xqH+fdakZor1khG7bC2uIwibD3cSl2XkR\r\n" \
"wN48lslbHnqqagr6Xm1nNOSVl8C/6kbJEsMpLhAezfRtGwvOucoaE+WbeUNolGde\r\n" \
"P/eQiddSf0brnpiLJRh7qZrl9XuqYdpUqnoEdMAfotDOID8OtV7gt8a48ad8VPW2\r\n" \
"-----END RSA PRIVATE KEY-----\r\n"
/* END FILE */
#define TEST_CA_PWD_RSA_PEM "PolarSSLTest"
/* This was generated from test-ca.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_KEY_RSA_DER tests/data_files/test-ca.key.der */
#define TEST_CA_KEY_RSA_DER { \
0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \
0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, 0x86, 0xde, \
0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, 0x99, 0xd4, \
0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, 0x9b, 0xc5, \
0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, 0xc0, 0x8d, \
0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, 0x93, 0xe8, \
0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, 0xe7, 0x40, \
0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, 0xf9, 0x3e, \
0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, 0x29, 0x00, \
0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, 0xbd, 0x83, \
0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, 0x60, 0xc3, \
0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, 0x32, 0xbe, \
0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, 0xfb, 0xf5, \
0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, 0xee, 0xe2, \
0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, 0x47, 0xb1, \
0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, 0xf1, 0x79, \
0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, 0x6f, 0x27, \
0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, 0xa1, 0x30, \
0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, 0x28, 0xd1, \
0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, 0x09, 0xea, \
0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, 0xc9, 0xab, \
0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, 0x9e, 0x99, \
0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \
0x00, 0x3f, 0xf7, 0x07, 0xd3, 0x34, 0x6f, 0xdb, 0xc9, 0x37, 0xb7, 0x84, \
0xdc, 0x37, 0x45, 0xe1, 0x63, 0xad, 0xb8, 0xb6, 0x75, 0xb1, 0xc7, 0x35, \
0xb4, 0x77, 0x2a, 0x5b, 0x77, 0xf9, 0x7e, 0xe0, 0xc1, 0xa3, 0xd1, 0xb7, \
0xcb, 0xa9, 0x5a, 0xc1, 0x87, 0xda, 0x5a, 0xfa, 0x17, 0xe4, 0xd5, 0x38, \
0x03, 0xde, 0x68, 0x98, 0x81, 0xec, 0xb5, 0xf2, 0x2a, 0x8d, 0xe9, 0x2c, \
0xf3, 0xa6, 0xe5, 0x32, 0x17, 0x7f, 0x33, 0x81, 0xe8, 0x38, 0x72, 0xd5, \
0x9c, 0xfa, 0x4e, 0xfb, 0x26, 0xf5, 0x15, 0x0b, 0xaf, 0x84, 0x66, 0xab, \
0x02, 0xe0, 0x18, 0xd5, 0x91, 0x7c, 0xd6, 0x8f, 0xc9, 0x4b, 0x76, 0x08, \
0x2b, 0x1d, 0x81, 0x68, 0x30, 0xe1, 0xfa, 0x70, 0x6c, 0x13, 0x4e, 0x10, \
0x03, 0x35, 0x3e, 0xc5, 0xca, 0x58, 0x20, 0x8a, 0x21, 0x18, 0x38, 0xa0, \
0x0f, 0xed, 0xc4, 0xbb, 0x45, 0x6f, 0xf5, 0x84, 0x5b, 0xb0, 0xcf, 0x4e, \
0x9d, 0x58, 0x13, 0x6b, 0x35, 0x35, 0x69, 0xa1, 0xd2, 0xc4, 0xf2, 0xc1, \
0x48, 0x04, 0x20, 0x51, 0xb9, 0x6b, 0xa4, 0x5d, 0xa5, 0x4b, 0x84, 0x88, \
0x43, 0x48, 0x99, 0x2c, 0xbb, 0xa4, 0x97, 0xd6, 0xd6, 0x18, 0xf6, 0xec, \
0x5c, 0xd1, 0x31, 0x49, 0xc9, 0xf2, 0x8f, 0x0b, 0x4d, 0xef, 0x09, 0x02, \
0xfe, 0x7d, 0xfd, 0xbb, 0xaf, 0x2b, 0x83, 0x94, 0x22, 0xc4, 0xa7, 0x3e, \
0x66, 0xf5, 0xe0, 0x57, 0xdc, 0xf2, 0xed, 0x2c, 0x3e, 0x81, 0x74, 0x76, \
0x1e, 0x96, 0x6f, 0x74, 0x1e, 0x32, 0x0e, 0x14, 0x31, 0xd0, 0x74, 0xf0, \
0xf4, 0x07, 0xbd, 0xc3, 0xd1, 0x22, 0xc2, 0xa8, 0x95, 0x92, 0x06, 0x7f, \
0x43, 0x02, 0x91, 0xbc, 0xdd, 0x23, 0x01, 0x89, 0x94, 0x20, 0x44, 0x64, \
0xf5, 0x1d, 0x67, 0xd2, 0x8f, 0xe8, 0x69, 0xa5, 0x29, 0x25, 0xe6, 0x50, \
0x9c, 0xe3, 0xe9, 0xcb, 0x75, 0x02, 0x81, 0x81, 0x00, 0xe2, 0x29, 0x3e, \
0xaa, 0x6b, 0xd5, 0x59, 0x1e, 0x9c, 0xe6, 0x47, 0xd5, 0xb6, 0xd7, 0xe3, \
0xf1, 0x8e, 0x9e, 0xe9, 0x83, 0x5f, 0x10, 0x9f, 0x63, 0xec, 0x04, 0x44, \
0xcc, 0x3f, 0xf8, 0xd9, 0x3a, 0x17, 0xe0, 0x4f, 0xfe, 0xd8, 0x4d, 0xcd, \
0x46, 0x54, 0x74, 0xbf, 0x0a, 0xc4, 0x67, 0x9c, 0xa7, 0xd8, 0x89, 0x65, \
0x4c, 0xfd, 0x58, 0x2a, 0x47, 0x0f, 0xf4, 0x37, 0xb6, 0x55, 0xb0, 0x1d, \
0xed, 0xa7, 0x39, 0xfc, 0x4f, 0xa3, 0xc4, 0x75, 0x3a, 0xa3, 0x98, 0xa7, \
0x45, 0xf5, 0x66, 0xcb, 0x7c, 0x65, 0xfb, 0x80, 0x23, 0xe6, 0xff, 0xfd, \
0x99, 0x1f, 0x8e, 0x6b, 0xff, 0x5e, 0x93, 0x66, 0xdf, 0x6c, 0x6f, 0xc3, \
0xf6, 0x38, 0x2e, 0xff, 0x69, 0xb5, 0xac, 0xae, 0xbb, 0xc6, 0x71, 0x16, \
0x6b, 0xd0, 0xf8, 0x22, 0xd9, 0xf8, 0xa2, 0x72, 0x20, 0xd2, 0xe2, 0x3a, \
0x70, 0x4b, 0xde, 0xab, 0x2f, 0x02, 0x81, 0x81, 0x00, 0xda, 0x51, 0x9b, \
0xb8, 0xb2, 0x2a, 0x14, 0x75, 0x58, 0x40, 0x8d, 0x27, 0x70, 0xfa, 0x31, \
0x48, 0xb0, 0x20, 0x21, 0x34, 0xfa, 0x4c, 0x57, 0xa8, 0x11, 0x88, 0xf3, \
0xa7, 0xae, 0x21, 0xe9, 0xb6, 0x2b, 0xd1, 0xcd, 0xa7, 0xf8, 0xd8, 0x0c, \
0x8a, 0x76, 0x22, 0x35, 0x44, 0xce, 0x3f, 0x25, 0x29, 0x83, 0x7d, 0x79, \
0xa7, 0x31, 0xd6, 0xec, 0xb2, 0xbf, 0xda, 0x34, 0xb6, 0xf6, 0xb2, 0x3b, \
0xf3, 0x78, 0x5a, 0x04, 0x83, 0x33, 0x3e, 0xa2, 0xe2, 0x81, 0x82, 0x13, \
0xd4, 0x35, 0x17, 0x63, 0x9b, 0x9e, 0xc4, 0x8d, 0x91, 0x4c, 0x03, 0x77, \
0xc7, 0x71, 0x5b, 0xee, 0x83, 0x6d, 0xd5, 0x78, 0x88, 0xf6, 0x2c, 0x79, \
0xc2, 0x4a, 0xb4, 0x79, 0x90, 0x70, 0xbf, 0xdf, 0x34, 0x56, 0x96, 0x71, \
0xe3, 0x0e, 0x68, 0x91, 0xbc, 0xea, 0xcb, 0x33, 0xc0, 0xbe, 0x45, 0xd7, \
0xfc, 0x30, 0xfd, 0x01, 0x3b, 0x02, 0x81, 0x81, 0x00, 0xd2, 0x9f, 0x2a, \
0xb7, 0x38, 0x19, 0xc7, 0x17, 0x95, 0x73, 0x78, 0xae, 0xf5, 0xcb, 0x75, \
0x83, 0x7f, 0x19, 0x4b, 0xcb, 0x86, 0xfb, 0x4a, 0x15, 0x9a, 0xb6, 0x17, \
0x04, 0x49, 0x07, 0x8d, 0xf6, 0x66, 0x4a, 0x06, 0xf6, 0x05, 0xa7, 0xdf, \
0x66, 0x82, 0x3c, 0xff, 0xb6, 0x1d, 0x57, 0x89, 0x33, 0x5f, 0x9c, 0x05, \
0x75, 0x7f, 0xf3, 0x5d, 0xdc, 0x34, 0x65, 0x72, 0x85, 0x22, 0xa4, 0x14, \
0x1b, 0x41, 0xc3, 0xe4, 0xd0, 0x9e, 0x69, 0xd5, 0xeb, 0x38, 0x74, 0x70, \
0x43, 0xdc, 0xd9, 0x50, 0xe4, 0x97, 0x6d, 0x73, 0xd6, 0xfb, 0xc8, 0xa7, \
0xfa, 0xb4, 0xc2, 0xc4, 0x9d, 0x5d, 0x0c, 0xd5, 0x9f, 0x79, 0xb3, 0x54, \
0xc2, 0xb7, 0x6c, 0x3d, 0x7d, 0xcb, 0x2d, 0xf8, 0xc4, 0xf3, 0x78, 0x5a, \
0x33, 0x2a, 0xb8, 0x0c, 0x6d, 0x06, 0xfa, 0xf2, 0x62, 0xd3, 0x42, 0xd0, \
0xbd, 0xc8, 0x4a, 0xa5, 0x0d, 0x02, 0x81, 0x81, 0x00, 0xd4, 0xa9, 0x90, \
0x15, 0xde, 0xbf, 0x2c, 0xc4, 0x8d, 0x9d, 0xfb, 0xa1, 0xc2, 0xe4, 0x83, \
0xe3, 0x79, 0x65, 0x22, 0xd3, 0xb7, 0x49, 0x6c, 0x4d, 0x94, 0x1f, 0x22, \
0xb1, 0x60, 0xe7, 0x3a, 0x00, 0xb1, 0x38, 0xa2, 0xab, 0x0f, 0xb4, 0x6c, \
0xaa, 0xe7, 0x9e, 0x34, 0xe3, 0x7c, 0x40, 0x78, 0x53, 0xb2, 0xf9, 0x23, \
0xea, 0xa0, 0x9a, 0xea, 0x60, 0xc8, 0x8f, 0xa6, 0xaf, 0xdf, 0x29, 0x09, \
0x4b, 0x06, 0x1e, 0x31, 0xad, 0x17, 0xda, 0xd8, 0xd1, 0xe9, 0x33, 0xab, \
0x5b, 0x18, 0x08, 0x5b, 0x87, 0xf8, 0xa5, 0x1f, 0xfd, 0xbb, 0xdc, 0xd8, \
0xed, 0x97, 0x57, 0xe4, 0xc3, 0x73, 0xd6, 0xf0, 0x9e, 0x01, 0xa6, 0x9b, \
0x48, 0x8e, 0x7a, 0xb4, 0xbb, 0xe5, 0x88, 0x91, 0xc5, 0x2a, 0xdf, 0x4b, \
0xba, 0xd0, 0x8b, 0x3e, 0x03, 0x97, 0x77, 0x2f, 0x47, 0x7e, 0x51, 0x0c, \
0xae, 0x65, 0x8d, 0xde, 0x87, 0x02, 0x81, 0x80, 0x20, 0x24, 0x0f, 0xd2, \
0xaf, 0xc2, 0x28, 0x3b, 0x97, 0x20, 0xb2, 0x92, 0x49, 0xeb, 0x09, 0x68, \
0x40, 0xb2, 0xbe, 0xd1, 0xc3, 0x83, 0x94, 0x34, 0x38, 0xd6, 0xc9, 0xec, \
0x34, 0x09, 0xf9, 0x41, 0x6d, 0x5c, 0x42, 0x94, 0xf7, 0x04, 0xfc, 0x32, \
0x39, 0x69, 0xbc, 0x1c, 0xfb, 0x3e, 0x61, 0x98, 0xc0, 0x80, 0xd8, 0x36, \
0x47, 0xc3, 0x6d, 0xc2, 0x2e, 0xe7, 0x81, 0x2a, 0x17, 0x34, 0x64, 0x30, \
0x4e, 0x96, 0xbb, 0x26, 0x16, 0xb9, 0x41, 0x36, 0xfe, 0x8a, 0xd6, 0x53, \
0x7c, 0xaa, 0xec, 0x39, 0x42, 0x50, 0xef, 0xe3, 0xb3, 0x01, 0x28, 0x32, \
0xca, 0x6d, 0xf5, 0x9a, 0x1e, 0x9f, 0x37, 0xbe, 0xfe, 0x38, 0x20, 0x22, \
0x91, 0x8c, 0xcd, 0x95, 0x02, 0xf2, 0x4d, 0x6f, 0x1a, 0xb4, 0x43, 0xf0, \
0x19, 0xdf, 0x65, 0xc0, 0x92, 0xe7, 0x9d, 0x2f, 0x09, 0xe7, 0xec, 0x69, \
0xa8, 0xc2, 0x8f, 0x0d \
}
/* END FILE */
/*
* Test server Certificates
*
* Test server certificates are defined for each choice
* of the following parameters:
* - PEM or DER encoding
* - SHA-1 or SHA-256 hash
* - RSA or EC key
*
* Things to add:
* - multiple EC curve types
*/
/* This is taken from tests/data_files/server5.crt. */
/* BEGIN FILE string macro TEST_SRV_CRT_EC_PEM tests/data_files/server5.crt */
#define TEST_SRV_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIICHzCCAaWgAwIBAgIBCTAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN\r\n" \
"MTMwOTI0MTU1MjA0WhcNMjMwOTIyMTU1MjA0WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEG\r\n" \
"CCqGSM49AwEHA0IABDfMVtl2CR5acj7HWS3/IG7ufPkGkXTQrRS192giWWKSTuUA\r\n" \
"2CMR/+ov0jRdXRa9iojCa3cNVc2KKg76Aci07f+jgZ0wgZowCQYDVR0TBAIwADAd\r\n" \
"BgNVHQ4EFgQUUGGlj9QH2deCAQzlZX+MY0anE74wbgYDVR0jBGcwZYAUnW0gJEkB\r\n" \
"PyvLeLUZvH4kydv7NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xh\r\n" \
"clNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAoG\r\n" \
"CCqGSM49BAMCA2gAMGUCMQCaLFzXptui5WQN8LlO3ddh1hMxx6tzgLvT03MTVK2S\r\n" \
"C12r0Lz3ri/moSEpNZWqPjkCMCE2f53GXcYLqyfyJR078c/xNSUU5+Xxl7VZ414V\r\n" \
"fGa5kHvHARBPc8YAIVIqDvHH1Q==\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/server5.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_SRV_CRT_EC_DER tests/data_files/server5.crt.der */
#define TEST_SRV_CRT_EC_DER { \
0x30, 0x82, 0x02, 0x1f, 0x30, 0x82, 0x01, 0xa5, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x09, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, \
0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, \
0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x33, 0x30, 0x39, 0x32, 0x34, 0x31, 0x35, 0x35, 0x32, 0x30, 0x34, \
0x5a, 0x17, 0x0d, 0x32, 0x33, 0x30, 0x39, 0x32, 0x32, 0x31, 0x35, 0x35, \
0x32, 0x30, 0x34, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, \
0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x59, \
0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, \
0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, \
0x04, 0x37, 0xcc, 0x56, 0xd9, 0x76, 0x09, 0x1e, 0x5a, 0x72, 0x3e, 0xc7, \
0x59, 0x2d, 0xff, 0x20, 0x6e, 0xee, 0x7c, 0xf9, 0x06, 0x91, 0x74, 0xd0, \
0xad, 0x14, 0xb5, 0xf7, 0x68, 0x22, 0x59, 0x62, 0x92, 0x4e, 0xe5, 0x00, \
0xd8, 0x23, 0x11, 0xff, 0xea, 0x2f, 0xd2, 0x34, 0x5d, 0x5d, 0x16, 0xbd, \
0x8a, 0x88, 0xc2, 0x6b, 0x77, 0x0d, 0x55, 0xcd, 0x8a, 0x2a, 0x0e, 0xfa, \
0x01, 0xc8, 0xb4, 0xed, 0xff, 0xa3, 0x81, 0x9d, 0x30, 0x81, 0x9a, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, \
0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x50, 0x61, 0xa5, \
0x8f, 0xd4, 0x07, 0xd9, 0xd7, 0x82, 0x01, 0x0c, 0xe5, 0x65, 0x7f, 0x8c, \
0x63, 0x46, 0xa7, 0x13, 0xbe, 0x30, 0x6e, 0x06, 0x03, 0x55, 0x1d, 0x23, \
0x04, 0x67, 0x30, 0x65, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, 0x49, 0x01, \
0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, 0xdb, 0xfb, \
0x36, 0x7c, 0xa1, 0x42, 0xa4, 0x40, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, \
0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \
0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, \
0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, \
0x03, 0x13, 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, \
0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x82, 0x09, \
0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8, 0x30, 0x0a, 0x06, \
0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x68, 0x00, \
0x30, 0x65, 0x02, 0x31, 0x00, 0x9a, 0x2c, 0x5c, 0xd7, 0xa6, 0xdb, 0xa2, \
0xe5, 0x64, 0x0d, 0xf0, 0xb9, 0x4e, 0xdd, 0xd7, 0x61, 0xd6, 0x13, 0x31, \
0xc7, 0xab, 0x73, 0x80, 0xbb, 0xd3, 0xd3, 0x73, 0x13, 0x54, 0xad, 0x92, \
0x0b, 0x5d, 0xab, 0xd0, 0xbc, 0xf7, 0xae, 0x2f, 0xe6, 0xa1, 0x21, 0x29, \
0x35, 0x95, 0xaa, 0x3e, 0x39, 0x02, 0x30, 0x21, 0x36, 0x7f, 0x9d, 0xc6, \
0x5d, 0xc6, 0x0b, 0xab, 0x27, 0xf2, 0x25, 0x1d, 0x3b, 0xf1, 0xcf, 0xf1, \
0x35, 0x25, 0x14, 0xe7, 0xe5, 0xf1, 0x97, 0xb5, 0x59, 0xe3, 0x5e, 0x15, \
0x7c, 0x66, 0xb9, 0x90, 0x7b, 0xc7, 0x01, 0x10, 0x4f, 0x73, 0xc6, 0x00, \
0x21, 0x52, 0x2a, 0x0e, 0xf1, 0xc7, 0xd5 \
}
/* END FILE */
/* This is taken from tests/data_files/server5.key. */
/* BEGIN FILE string macro TEST_SRV_KEY_EC_PEM tests/data_files/server5.key */
#define TEST_SRV_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"MHcCAQEEIPEqEyB2AnCoPL/9U/YDHvdqXYbIogTywwyp6/UfDw6noAoGCCqGSM49\r\n" \
"AwEHoUQDQgAEN8xW2XYJHlpyPsdZLf8gbu58+QaRdNCtFLX3aCJZYpJO5QDYIxH/\r\n" \
"6i/SNF1dFr2KiMJrdw1VzYoqDvoByLTt/w==\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/server5.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_SRV_KEY_EC_DER tests/data_files/server5.key.der */
#define TEST_SRV_KEY_EC_DER { \
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0xf1, 0x2a, 0x13, 0x20, 0x76, \
0x02, 0x70, 0xa8, 0x3c, 0xbf, 0xfd, 0x53, 0xf6, 0x03, 0x1e, 0xf7, 0x6a, \
0x5d, 0x86, 0xc8, 0xa2, 0x04, 0xf2, 0xc3, 0x0c, 0xa9, 0xeb, 0xf5, 0x1f, \
0x0f, 0x0e, 0xa7, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x37, 0xcc, 0x56, \
0xd9, 0x76, 0x09, 0x1e, 0x5a, 0x72, 0x3e, 0xc7, 0x59, 0x2d, 0xff, 0x20, \
0x6e, 0xee, 0x7c, 0xf9, 0x06, 0x91, 0x74, 0xd0, 0xad, 0x14, 0xb5, 0xf7, \
0x68, 0x22, 0x59, 0x62, 0x92, 0x4e, 0xe5, 0x00, 0xd8, 0x23, 0x11, 0xff, \
0xea, 0x2f, 0xd2, 0x34, 0x5d, 0x5d, 0x16, 0xbd, 0x8a, 0x88, 0xc2, 0x6b, \
0x77, 0x0d, 0x55, 0xcd, 0x8a, 0x2a, 0x0e, 0xfa, 0x01, 0xc8, 0xb4, 0xed, \
0xff \
}
/* END FILE */
/* This is taken from tests/data_files/server2-sha256.crt. */
/* BEGIN FILE string macro TEST_SRV_CRT_RSA_SHA256_PEM tests/data_files/server2-sha256.crt */
#define TEST_SRV_CRT_RSA_SHA256_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" \
"AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n" \
"owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n" \
"NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n" \
"tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\r\n" \
"hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n" \
"HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n" \
"VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n" \
"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQELBQADggEBAC465FJh\r\n" \
"Pqel7zJngHIHJrqj/wVAxGAFOTF396XKATGAp+HRCqJ81Ry60CNK1jDzk8dv6M6U\r\n" \
"HoS7RIFiM/9rXQCbJfiPD5xMTejZp5n5UYHAmxsxDaazfA5FuBhkfokKK6jD4Eq9\r\n" \
"1C94xGKb6X4/VkaPF7cqoBBw/bHxawXc0UEPjqayiBpCYU/rJoVZgLqFVP7Px3sv\r\n" \
"a1nOrNx8rPPI1hJ+ZOg8maiPTxHZnBVLakSSLQy/sWeWyazO1RnrbxjrbgQtYKz0\r\n" \
"e3nwGpu1w13vfckFmUSBhHXH7AAS/HpKC4IH7G2GAk3+n8iSSN71sZzpxonQwVbo\r\n" \
"pMZqLmbBm/7WPLc=\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is taken from tests/data_files/server2-sha256.crt.der. */
/* BEGIN FILE binary macro TEST_SRV_CRT_RSA_SHA256_DER tests/data_files/server2-sha256.crt.der */
#define TEST_SRV_CRT_RSA_SHA256_DER { \
0x30, 0x82, 0x03, 0x37, 0x30, 0x82, 0x02, 0x1f, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \
0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \
0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \
0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \
0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \
0x34, 0x30, 0x36, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \
0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x82, \
0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, \
0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, \
0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc1, 0x4d, 0xa3, 0xdd, 0xe7, \
0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, 0xb8, 0x99, 0xac, 0x0e, 0x78, \
0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, 0x16, 0xd0, 0x5a, 0xe4, 0xcd, \
0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, 0x96, 0xa7, 0x52, 0xb4, 0x90, \
0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, 0xfc, 0xb6, 0x34, 0xac, 0x24, \
0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, 0xb0, 0x28, 0x7d, 0xa1, 0xda, \
0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, 0xfe, 0xc1, 0x04, 0x52, 0xb3, \
0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, 0xd8, 0x90, 0xc1, 0x61, 0xb4, \
0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, 0xab, 0x74, 0x5e, 0x07, 0x7d, \
0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, 0xd9, 0x0d, 0x1c, 0x2d, 0x49, \
0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, 0x0b, 0x8a, 0x4f, 0x69, 0x0c, \
0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, 0x66, 0x7d, 0xae, 0x54, 0x2b, \
0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, 0xc3, 0xcd, 0x40, 0x49, 0x08, \
0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, 0x46, 0xbf, 0xd0, 0xb8, 0xaa, \
0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, 0x1e, 0x44, 0x18, 0x0f, 0x0f, \
0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, 0x18, 0xc6, 0x62, 0x2f, 0xc7, \
0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, 0x27, 0x89, 0x29, 0x01, 0xc5, \
0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, 0x4a, 0x0e, 0xef, 0xd6, 0xde, \
0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, 0x7a, 0xc4, 0x02, 0x3c, 0x9a, \
0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, 0xcb, 0x73, 0x4b, 0x52, 0x96, \
0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, 0x39, 0x5a, 0xd3, 0x0f, 0xb0, \
0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, 0x12, 0x01, 0x30, 0x97, 0x02, \
0x03, 0x01, 0x00, 0x01, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, \
0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xa5, 0x05, 0xe8, 0x64, 0xb8, 0xdc, \
0xdf, 0x60, 0x0f, 0x50, 0x12, 0x4d, 0x60, 0xa8, 0x64, 0xaf, 0x4d, 0x8b, \
0x43, 0x93, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, \
0x16, 0x80, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, \
0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, \
0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, \
0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x2e, 0x3a, 0xe4, 0x52, 0x61, \
0x3e, 0xa7, 0xa5, 0xef, 0x32, 0x67, 0x80, 0x72, 0x07, 0x26, 0xba, 0xa3, \
0xff, 0x05, 0x40, 0xc4, 0x60, 0x05, 0x39, 0x31, 0x77, 0xf7, 0xa5, 0xca, \
0x01, 0x31, 0x80, 0xa7, 0xe1, 0xd1, 0x0a, 0xa2, 0x7c, 0xd5, 0x1c, 0xba, \
0xd0, 0x23, 0x4a, 0xd6, 0x30, 0xf3, 0x93, 0xc7, 0x6f, 0xe8, 0xce, 0x94, \
0x1e, 0x84, 0xbb, 0x44, 0x81, 0x62, 0x33, 0xff, 0x6b, 0x5d, 0x00, 0x9b, \
0x25, 0xf8, 0x8f, 0x0f, 0x9c, 0x4c, 0x4d, 0xe8, 0xd9, 0xa7, 0x99, 0xf9, \
0x51, 0x81, 0xc0, 0x9b, 0x1b, 0x31, 0x0d, 0xa6, 0xb3, 0x7c, 0x0e, 0x45, \
0xb8, 0x18, 0x64, 0x7e, 0x89, 0x0a, 0x2b, 0xa8, 0xc3, 0xe0, 0x4a, 0xbd, \
0xd4, 0x2f, 0x78, 0xc4, 0x62, 0x9b, 0xe9, 0x7e, 0x3f, 0x56, 0x46, 0x8f, \
0x17, 0xb7, 0x2a, 0xa0, 0x10, 0x70, 0xfd, 0xb1, 0xf1, 0x6b, 0x05, 0xdc, \
0xd1, 0x41, 0x0f, 0x8e, 0xa6, 0xb2, 0x88, 0x1a, 0x42, 0x61, 0x4f, 0xeb, \
0x26, 0x85, 0x59, 0x80, 0xba, 0x85, 0x54, 0xfe, 0xcf, 0xc7, 0x7b, 0x2f, \
0x6b, 0x59, 0xce, 0xac, 0xdc, 0x7c, 0xac, 0xf3, 0xc8, 0xd6, 0x12, 0x7e, \
0x64, 0xe8, 0x3c, 0x99, 0xa8, 0x8f, 0x4f, 0x11, 0xd9, 0x9c, 0x15, 0x4b, \
0x6a, 0x44, 0x92, 0x2d, 0x0c, 0xbf, 0xb1, 0x67, 0x96, 0xc9, 0xac, 0xce, \
0xd5, 0x19, 0xeb, 0x6f, 0x18, 0xeb, 0x6e, 0x04, 0x2d, 0x60, 0xac, 0xf4, \
0x7b, 0x79, 0xf0, 0x1a, 0x9b, 0xb5, 0xc3, 0x5d, 0xef, 0x7d, 0xc9, 0x05, \
0x99, 0x44, 0x81, 0x84, 0x75, 0xc7, 0xec, 0x00, 0x12, 0xfc, 0x7a, 0x4a, \
0x0b, 0x82, 0x07, 0xec, 0x6d, 0x86, 0x02, 0x4d, 0xfe, 0x9f, 0xc8, 0x92, \
0x48, 0xde, 0xf5, 0xb1, 0x9c, 0xe9, 0xc6, 0x89, 0xd0, 0xc1, 0x56, 0xe8, \
0xa4, 0xc6, 0x6a, 0x2e, 0x66, 0xc1, 0x9b, 0xfe, 0xd6, 0x3c, 0xb7 \
}
/* END FILE */
/* This is taken from tests/data_files/server2.crt. */
/* BEGIN FILE string macro TEST_SRV_CRT_RSA_SHA1_PEM tests/data_files/server2.crt */
#define TEST_SRV_CRT_RSA_SHA1_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" \
"AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n" \
"owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n" \
"NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n" \
"tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\r\n" \
"hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n" \
"HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n" \
"VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n" \
"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJklg3Q4\r\n" \
"cB7v7BzsxM/vLyKccO6op0/gZzM4ghuLq2Y32kl0sM6kSNUUmduuq3u/+GmUZN2A\r\n" \
"O/7c+Hw7hDFEIvZk98aBGjCLqn3DmgHIv8ToQ67nellQxx2Uj309PdgjNi/r9HOc\r\n" \
"KNAYPbBcg6MJGWWj2TI6vNaceios/DhOYx5V0j5nfqSJ/pnU0g9Ign2LAhgYpGJE\r\n" \
"iEM9wW7hEMkwmk0h/sqZsrJsGH5YsF/VThSq/JVO1e2mZH2vruyZKJVBq+8tDNYp\r\n" \
"HkK6tSyVYQhzIt3StMJWKMl/o5k2AYz6tSC164+1oG+ML3LWg8XrGKa91H4UOKap\r\n" \
"Awgk0+4m0T25cNs=\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is taken from tests/data_files/server2.crt.der. */
/* BEGIN FILE binary macro TEST_SRV_CRT_RSA_SHA1_DER tests/data_files/server2.crt.der */
#define TEST_SRV_CRT_RSA_SHA1_DER { \
0x30, 0x82, 0x03, 0x37, 0x30, 0x82, 0x02, 0x1f, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \
0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \
0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \
0x5a, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, \
0x34, 0x30, 0x36, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \
0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x82, \
0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, \
0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, \
0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc1, 0x4d, 0xa3, 0xdd, 0xe7, \
0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, 0xb8, 0x99, 0xac, 0x0e, 0x78, \
0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, 0x16, 0xd0, 0x5a, 0xe4, 0xcd, \
0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, 0x96, 0xa7, 0x52, 0xb4, 0x90, \
0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, 0xfc, 0xb6, 0x34, 0xac, 0x24, \
0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, 0xb0, 0x28, 0x7d, 0xa1, 0xda, \
0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, 0xfe, 0xc1, 0x04, 0x52, 0xb3, \
0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, 0xd8, 0x90, 0xc1, 0x61, 0xb4, \
0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, 0xab, 0x74, 0x5e, 0x07, 0x7d, \
0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, 0xd9, 0x0d, 0x1c, 0x2d, 0x49, \
0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, 0x0b, 0x8a, 0x4f, 0x69, 0x0c, \
0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, 0x66, 0x7d, 0xae, 0x54, 0x2b, \
0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, 0xc3, 0xcd, 0x40, 0x49, 0x08, \
0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, 0x46, 0xbf, 0xd0, 0xb8, 0xaa, \
0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, 0x1e, 0x44, 0x18, 0x0f, 0x0f, \
0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, 0x18, 0xc6, 0x62, 0x2f, 0xc7, \
0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, 0x27, 0x89, 0x29, 0x01, 0xc5, \
0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, 0x4a, 0x0e, 0xef, 0xd6, 0xde, \
0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, 0x7a, 0xc4, 0x02, 0x3c, 0x9a, \
0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, 0xcb, 0x73, 0x4b, 0x52, 0x96, \
0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, 0x39, 0x5a, 0xd3, 0x0f, 0xb0, \
0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, 0x12, 0x01, 0x30, 0x97, 0x02, \
0x03, 0x01, 0x00, 0x01, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, \
0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xa5, 0x05, 0xe8, 0x64, 0xb8, 0xdc, \
0xdf, 0x60, 0x0f, 0x50, 0x12, 0x4d, 0x60, 0xa8, 0x64, 0xaf, 0x4d, 0x8b, \
0x43, 0x93, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, \
0x16, 0x80, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, \
0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, \
0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, \
0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x01, 0x73, 0x0b, 0x4a, 0xc5, \
0xcb, 0xa0, 0xde, 0xf1, 0x63, 0x1c, 0x76, 0x04, 0x2b, 0x13, 0x0d, 0xc0, \
0x84, 0x11, 0xc5, 0x8f, 0x3a, 0xa7, 0xc5, 0x9c, 0x35, 0x7a, 0x77, 0xb8, \
0x20, 0x14, 0x82, 0xee, 0x54, 0xf0, 0xf2, 0xb0, 0x52, 0xcb, 0x78, 0xce, \
0x59, 0x07, 0x4f, 0x51, 0x69, 0xfe, 0xd3, 0x2f, 0xe9, 0x09, 0xe7, 0x85, \
0x92, 0xd8, 0xba, 0xb1, 0xeb, 0xc5, 0x76, 0x5d, 0x61, 0x2d, 0xe9, 0x86, \
0xb5, 0xde, 0x2a, 0xf9, 0x3f, 0x53, 0x28, 0x42, 0x86, 0x83, 0x73, 0x43, \
0xe0, 0x04, 0x5f, 0x07, 0x90, 0x14, 0x65, 0x9f, 0x6e, 0x10, 0x7a, 0xbc, \
0x58, 0x19, 0x22, 0xc2, 0xeb, 0x39, 0x72, 0x51, 0x92, 0xd7, 0xb4, 0x1d, \
0x75, 0x2f, 0xd3, 0x3a, 0x2b, 0x01, 0xe7, 0xdb, 0x50, 0xae, 0xe2, 0xf1, \
0xd4, 0x4d, 0x5b, 0x3c, 0xbb, 0x41, 0x2b, 0x2a, 0xa4, 0xe2, 0x4a, 0x02, \
0xe5, 0x60, 0x14, 0x2c, 0x9c, 0x1f, 0xa6, 0xcc, 0x06, 0x4b, 0x25, 0x89, \
0x4e, 0x96, 0x30, 0x22, 0x9c, 0x5c, 0x58, 0x4d, 0xc3, 0xda, 0xd0, 0x6e, \
0x50, 0x1e, 0x8c, 0x65, 0xf5, 0xd9, 0x17, 0x35, 0xa6, 0x58, 0x43, 0xb2, \
0x29, 0xb7, 0xa8, 0x5e, 0x35, 0xde, 0xf0, 0x60, 0x42, 0x1a, 0x01, 0xcb, \
0xcb, 0x0b, 0xd8, 0x0e, 0xc1, 0x90, 0xdf, 0xa1, 0xd2, 0x1a, 0xd1, 0x2c, \
0x02, 0xf4, 0x76, 0x41, 0xa4, 0xcb, 0x4b, 0x15, 0x98, 0x71, 0xf9, 0x35, \
0x7d, 0xb0, 0xe7, 0xe2, 0x34, 0x96, 0x91, 0xbe, 0x32, 0x67, 0x2d, 0x6b, \
0xd3, 0x55, 0x04, 0x8a, 0x01, 0x50, 0xb4, 0xe3, 0x62, 0x78, 0x6c, 0x11, \
0x15, 0xa5, 0x2a, 0x11, 0xc1, 0x49, 0x1c, 0x9b, 0xc4, 0x10, 0x65, 0x60, \
0x87, 0xd9, 0x1e, 0x69, 0x59, 0x4e, 0x8f, 0x6b, 0xeb, 0xc1, 0xfe, 0x6b, \
0xe2, 0x63, 0x78, 0x95, 0x6e, 0xe0, 0x2d, 0xd7, 0xa7, 0x37, 0xa8 \
}
/* END FILE */
/* This is taken from tests/data_files/server2.key. */
/* BEGIN FILE string macro TEST_SRV_KEY_RSA_PEM tests/data_files/server2.key */
#define TEST_SRV_KEY_RSA_PEM \
"-----BEGIN RSA PRIVATE KEY-----\r\n" \
"MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\r\n" \
"lqdStJDvLXJ6PiSa/LY0rCT1d+AmZIycsCh9odrqjObJHJa8/sEEUrM21KP64bF2\r\n" \
"2JDBYbRmUjaiJlOqq3ReB30Zgtsq2B+g2Q0cLUlm91slc0boC4pPaQy1AJDh2oIQ\r\n" \
"Zn2uVCuLZXmRoeJhw81ASQjuaAzxi4bSRr/QuKoRAx5/VqgaHkQYDw+Fi9qLRF7i\r\n" \
"GMZiL8dmjfpd2H3zJ4kpAcWQDj8n8TDISg7v1t7HxydrxwU9esQCPJodPg/oNJhb\r\n" \
"y3NLUpbYEaIsgIhpOVrTD7DeWS8Rx/fqEgEwlwIDAQABAoIBAQCXR0S8EIHFGORZ\r\n" \
"++AtOg6eENxD+xVs0f1IeGz57Tjo3QnXX7VBZNdj+p1ECvhCE/G7XnkgU5hLZX+G\r\n" \
"Z0jkz/tqJOI0vRSdLBbipHnWouyBQ4e/A1yIJdlBtqXxJ1KE/ituHRbNc4j4kL8Z\r\n" \
"/r6pvwnTI0PSx2Eqs048YdS92LT6qAv4flbNDxMn2uY7s4ycS4Q8w1JXnCeaAnYm\r\n" \
"WYI5wxO+bvRELR2Mcz5DmVnL8jRyml6l6582bSv5oufReFIbyPZbQWlXgYnpu6He\r\n" \
"GTc7E1zKYQGG/9+DQUl/1vQuCPqQwny0tQoX2w5tdYpdMdVm+zkLtbajzdTviJJa\r\n" \
"TWzL6lt5AoGBAN86+SVeJDcmQJcv4Eq6UhtRr4QGMiQMz0Sod6ettYxYzMgxtw28\r\n" \
"CIrgpozCc+UaZJLo7UxvC6an85r1b2nKPCLQFaggJ0H4Q0J/sZOhBIXaoBzWxveK\r\n" \
"nupceKdVxGsFi8CDy86DBfiyFivfBj+47BbaQzPBj7C4rK7UlLjab2rDAoGBAN2u\r\n" \
"AM2gchoFiu4v1HFL8D7lweEpi6ZnMJjnEu/dEgGQJFjwdpLnPbsj4c75odQ4Gz8g\r\n" \
"sw9lao9VVzbusoRE/JGI4aTdO0pATXyG7eG1Qu+5Yc1YGXcCrliA2xM9xx+d7f+s\r\n" \
"mPzN+WIEg5GJDYZDjAzHG5BNvi/FfM1C9dOtjv2dAoGAF0t5KmwbjWHBhcVqO4Ic\r\n" \
"BVvN3BIlc1ue2YRXEDlxY5b0r8N4XceMgKmW18OHApZxfl8uPDauWZLXOgl4uepv\r\n" \
"whZC3EuWrSyyICNhLY21Ah7hbIEBPF3L3ZsOwC+UErL+dXWLdB56Jgy3gZaBeW7b\r\n" \
"vDrEnocJbqCm7IukhXHOBK8CgYEAwqdHB0hqyNSzIOGY7v9abzB6pUdA3BZiQvEs\r\n" \
"3LjHVd4HPJ2x0N8CgrBIWOE0q8+0hSMmeE96WW/7jD3fPWwCR5zlXknxBQsfv0gP\r\n" \
"3BC5PR0Qdypz+d+9zfMf625kyit4T/hzwhDveZUzHnk1Cf+IG7Q+TOEnLnWAWBED\r\n" \
"ISOWmrUCgYAFEmRxgwAc/u+D6t0syCwAYh6POtscq9Y0i9GyWk89NzgC4NdwwbBH\r\n" \
"4AgahOxIxXx2gxJnq3yfkJfIjwf0s2DyP0kY2y6Ua1OeomPeY9mrIS4tCuDQ6LrE\r\n" \
"TB6l9VGoxJL4fyHnZb8L5gGvnB1bbD8cL6YPaDiOhcRseC9vBiEuVg==\r\n" \
"-----END RSA PRIVATE KEY-----\r\n"
/* END FILE */
/* This was generated from tests/data_files/server2.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_SRV_KEY_RSA_DER tests/data_files/server2.key.der */
#define TEST_SRV_KEY_RSA_DER { \
0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \
0xc1, 0x4d, 0xa3, 0xdd, 0xe7, 0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, \
0xb8, 0x99, 0xac, 0x0e, 0x78, 0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, \
0x16, 0xd0, 0x5a, 0xe4, 0xcd, 0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, \
0x96, 0xa7, 0x52, 0xb4, 0x90, 0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, \
0xfc, 0xb6, 0x34, 0xac, 0x24, 0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, \
0xb0, 0x28, 0x7d, 0xa1, 0xda, 0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, \
0xfe, 0xc1, 0x04, 0x52, 0xb3, 0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, \
0xd8, 0x90, 0xc1, 0x61, 0xb4, 0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, \
0xab, 0x74, 0x5e, 0x07, 0x7d, 0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, \
0xd9, 0x0d, 0x1c, 0x2d, 0x49, 0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, \
0x0b, 0x8a, 0x4f, 0x69, 0x0c, 0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, \
0x66, 0x7d, 0xae, 0x54, 0x2b, 0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, \
0xc3, 0xcd, 0x40, 0x49, 0x08, 0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, \
0x46, 0xbf, 0xd0, 0xb8, 0xaa, 0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, \
0x1e, 0x44, 0x18, 0x0f, 0x0f, 0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, \
0x18, 0xc6, 0x62, 0x2f, 0xc7, 0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, \
0x27, 0x89, 0x29, 0x01, 0xc5, 0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, \
0x4a, 0x0e, 0xef, 0xd6, 0xde, 0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, \
0x7a, 0xc4, 0x02, 0x3c, 0x9a, 0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, \
0xcb, 0x73, 0x4b, 0x52, 0x96, 0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, \
0x39, 0x5a, 0xd3, 0x0f, 0xb0, 0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, \
0x12, 0x01, 0x30, 0x97, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \
0x01, 0x00, 0x97, 0x47, 0x44, 0xbc, 0x10, 0x81, 0xc5, 0x18, 0xe4, 0x59, \
0xfb, 0xe0, 0x2d, 0x3a, 0x0e, 0x9e, 0x10, 0xdc, 0x43, 0xfb, 0x15, 0x6c, \
0xd1, 0xfd, 0x48, 0x78, 0x6c, 0xf9, 0xed, 0x38, 0xe8, 0xdd, 0x09, 0xd7, \
0x5f, 0xb5, 0x41, 0x64, 0xd7, 0x63, 0xfa, 0x9d, 0x44, 0x0a, 0xf8, 0x42, \
0x13, 0xf1, 0xbb, 0x5e, 0x79, 0x20, 0x53, 0x98, 0x4b, 0x65, 0x7f, 0x86, \
0x67, 0x48, 0xe4, 0xcf, 0xfb, 0x6a, 0x24, 0xe2, 0x34, 0xbd, 0x14, 0x9d, \
0x2c, 0x16, 0xe2, 0xa4, 0x79, 0xd6, 0xa2, 0xec, 0x81, 0x43, 0x87, 0xbf, \
0x03, 0x5c, 0x88, 0x25, 0xd9, 0x41, 0xb6, 0xa5, 0xf1, 0x27, 0x52, 0x84, \
0xfe, 0x2b, 0x6e, 0x1d, 0x16, 0xcd, 0x73, 0x88, 0xf8, 0x90, 0xbf, 0x19, \
0xfe, 0xbe, 0xa9, 0xbf, 0x09, 0xd3, 0x23, 0x43, 0xd2, 0xc7, 0x61, 0x2a, \
0xb3, 0x4e, 0x3c, 0x61, 0xd4, 0xbd, 0xd8, 0xb4, 0xfa, 0xa8, 0x0b, 0xf8, \
0x7e, 0x56, 0xcd, 0x0f, 0x13, 0x27, 0xda, 0xe6, 0x3b, 0xb3, 0x8c, 0x9c, \
0x4b, 0x84, 0x3c, 0xc3, 0x52, 0x57, 0x9c, 0x27, 0x9a, 0x02, 0x76, 0x26, \
0x59, 0x82, 0x39, 0xc3, 0x13, 0xbe, 0x6e, 0xf4, 0x44, 0x2d, 0x1d, 0x8c, \
0x73, 0x3e, 0x43, 0x99, 0x59, 0xcb, 0xf2, 0x34, 0x72, 0x9a, 0x5e, 0xa5, \
0xeb, 0x9f, 0x36, 0x6d, 0x2b, 0xf9, 0xa2, 0xe7, 0xd1, 0x78, 0x52, 0x1b, \
0xc8, 0xf6, 0x5b, 0x41, 0x69, 0x57, 0x81, 0x89, 0xe9, 0xbb, 0xa1, 0xde, \
0x19, 0x37, 0x3b, 0x13, 0x5c, 0xca, 0x61, 0x01, 0x86, 0xff, 0xdf, 0x83, \
0x41, 0x49, 0x7f, 0xd6, 0xf4, 0x2e, 0x08, 0xfa, 0x90, 0xc2, 0x7c, 0xb4, \
0xb5, 0x0a, 0x17, 0xdb, 0x0e, 0x6d, 0x75, 0x8a, 0x5d, 0x31, 0xd5, 0x66, \
0xfb, 0x39, 0x0b, 0xb5, 0xb6, 0xa3, 0xcd, 0xd4, 0xef, 0x88, 0x92, 0x5a, \
0x4d, 0x6c, 0xcb, 0xea, 0x5b, 0x79, 0x02, 0x81, 0x81, 0x00, 0xdf, 0x3a, \
0xf9, 0x25, 0x5e, 0x24, 0x37, 0x26, 0x40, 0x97, 0x2f, 0xe0, 0x4a, 0xba, \
0x52, 0x1b, 0x51, 0xaf, 0x84, 0x06, 0x32, 0x24, 0x0c, 0xcf, 0x44, 0xa8, \
0x77, 0xa7, 0xad, 0xb5, 0x8c, 0x58, 0xcc, 0xc8, 0x31, 0xb7, 0x0d, 0xbc, \
0x08, 0x8a, 0xe0, 0xa6, 0x8c, 0xc2, 0x73, 0xe5, 0x1a, 0x64, 0x92, 0xe8, \
0xed, 0x4c, 0x6f, 0x0b, 0xa6, 0xa7, 0xf3, 0x9a, 0xf5, 0x6f, 0x69, 0xca, \
0x3c, 0x22, 0xd0, 0x15, 0xa8, 0x20, 0x27, 0x41, 0xf8, 0x43, 0x42, 0x7f, \
0xb1, 0x93, 0xa1, 0x04, 0x85, 0xda, 0xa0, 0x1c, 0xd6, 0xc6, 0xf7, 0x8a, \
0x9e, 0xea, 0x5c, 0x78, 0xa7, 0x55, 0xc4, 0x6b, 0x05, 0x8b, 0xc0, 0x83, \
0xcb, 0xce, 0x83, 0x05, 0xf8, 0xb2, 0x16, 0x2b, 0xdf, 0x06, 0x3f, 0xb8, \
0xec, 0x16, 0xda, 0x43, 0x33, 0xc1, 0x8f, 0xb0, 0xb8, 0xac, 0xae, 0xd4, \
0x94, 0xb8, 0xda, 0x6f, 0x6a, 0xc3, 0x02, 0x81, 0x81, 0x00, 0xdd, 0xae, \
0x00, 0xcd, 0xa0, 0x72, 0x1a, 0x05, 0x8a, 0xee, 0x2f, 0xd4, 0x71, 0x4b, \
0xf0, 0x3e, 0xe5, 0xc1, 0xe1, 0x29, 0x8b, 0xa6, 0x67, 0x30, 0x98, 0xe7, \
0x12, 0xef, 0xdd, 0x12, 0x01, 0x90, 0x24, 0x58, 0xf0, 0x76, 0x92, 0xe7, \
0x3d, 0xbb, 0x23, 0xe1, 0xce, 0xf9, 0xa1, 0xd4, 0x38, 0x1b, 0x3f, 0x20, \
0xb3, 0x0f, 0x65, 0x6a, 0x8f, 0x55, 0x57, 0x36, 0xee, 0xb2, 0x84, 0x44, \
0xfc, 0x91, 0x88, 0xe1, 0xa4, 0xdd, 0x3b, 0x4a, 0x40, 0x4d, 0x7c, 0x86, \
0xed, 0xe1, 0xb5, 0x42, 0xef, 0xb9, 0x61, 0xcd, 0x58, 0x19, 0x77, 0x02, \
0xae, 0x58, 0x80, 0xdb, 0x13, 0x3d, 0xc7, 0x1f, 0x9d, 0xed, 0xff, 0xac, \
0x98, 0xfc, 0xcd, 0xf9, 0x62, 0x04, 0x83, 0x91, 0x89, 0x0d, 0x86, 0x43, \
0x8c, 0x0c, 0xc7, 0x1b, 0x90, 0x4d, 0xbe, 0x2f, 0xc5, 0x7c, 0xcd, 0x42, \
0xf5, 0xd3, 0xad, 0x8e, 0xfd, 0x9d, 0x02, 0x81, 0x80, 0x17, 0x4b, 0x79, \
0x2a, 0x6c, 0x1b, 0x8d, 0x61, 0xc1, 0x85, 0xc5, 0x6a, 0x3b, 0x82, 0x1c, \
0x05, 0x5b, 0xcd, 0xdc, 0x12, 0x25, 0x73, 0x5b, 0x9e, 0xd9, 0x84, 0x57, \
0x10, 0x39, 0x71, 0x63, 0x96, 0xf4, 0xaf, 0xc3, 0x78, 0x5d, 0xc7, 0x8c, \
0x80, 0xa9, 0x96, 0xd7, 0xc3, 0x87, 0x02, 0x96, 0x71, 0x7e, 0x5f, 0x2e, \
0x3c, 0x36, 0xae, 0x59, 0x92, 0xd7, 0x3a, 0x09, 0x78, 0xb9, 0xea, 0x6f, \
0xc2, 0x16, 0x42, 0xdc, 0x4b, 0x96, 0xad, 0x2c, 0xb2, 0x20, 0x23, 0x61, \
0x2d, 0x8d, 0xb5, 0x02, 0x1e, 0xe1, 0x6c, 0x81, 0x01, 0x3c, 0x5d, 0xcb, \
0xdd, 0x9b, 0x0e, 0xc0, 0x2f, 0x94, 0x12, 0xb2, 0xfe, 0x75, 0x75, 0x8b, \
0x74, 0x1e, 0x7a, 0x26, 0x0c, 0xb7, 0x81, 0x96, 0x81, 0x79, 0x6e, 0xdb, \
0xbc, 0x3a, 0xc4, 0x9e, 0x87, 0x09, 0x6e, 0xa0, 0xa6, 0xec, 0x8b, 0xa4, \
0x85, 0x71, 0xce, 0x04, 0xaf, 0x02, 0x81, 0x81, 0x00, 0xc2, 0xa7, 0x47, \
0x07, 0x48, 0x6a, 0xc8, 0xd4, 0xb3, 0x20, 0xe1, 0x98, 0xee, 0xff, 0x5a, \
0x6f, 0x30, 0x7a, 0xa5, 0x47, 0x40, 0xdc, 0x16, 0x62, 0x42, 0xf1, 0x2c, \
0xdc, 0xb8, 0xc7, 0x55, 0xde, 0x07, 0x3c, 0x9d, 0xb1, 0xd0, 0xdf, 0x02, \
0x82, 0xb0, 0x48, 0x58, 0xe1, 0x34, 0xab, 0xcf, 0xb4, 0x85, 0x23, 0x26, \
0x78, 0x4f, 0x7a, 0x59, 0x6f, 0xfb, 0x8c, 0x3d, 0xdf, 0x3d, 0x6c, 0x02, \
0x47, 0x9c, 0xe5, 0x5e, 0x49, 0xf1, 0x05, 0x0b, 0x1f, 0xbf, 0x48, 0x0f, \
0xdc, 0x10, 0xb9, 0x3d, 0x1d, 0x10, 0x77, 0x2a, 0x73, 0xf9, 0xdf, 0xbd, \
0xcd, 0xf3, 0x1f, 0xeb, 0x6e, 0x64, 0xca, 0x2b, 0x78, 0x4f, 0xf8, 0x73, \
0xc2, 0x10, 0xef, 0x79, 0x95, 0x33, 0x1e, 0x79, 0x35, 0x09, 0xff, 0x88, \
0x1b, 0xb4, 0x3e, 0x4c, 0xe1, 0x27, 0x2e, 0x75, 0x80, 0x58, 0x11, 0x03, \
0x21, 0x23, 0x96, 0x9a, 0xb5, 0x02, 0x81, 0x80, 0x05, 0x12, 0x64, 0x71, \
0x83, 0x00, 0x1c, 0xfe, 0xef, 0x83, 0xea, 0xdd, 0x2c, 0xc8, 0x2c, 0x00, \
0x62, 0x1e, 0x8f, 0x3a, 0xdb, 0x1c, 0xab, 0xd6, 0x34, 0x8b, 0xd1, 0xb2, \
0x5a, 0x4f, 0x3d, 0x37, 0x38, 0x02, 0xe0, 0xd7, 0x70, 0xc1, 0xb0, 0x47, \
0xe0, 0x08, 0x1a, 0x84, 0xec, 0x48, 0xc5, 0x7c, 0x76, 0x83, 0x12, 0x67, \
0xab, 0x7c, 0x9f, 0x90, 0x97, 0xc8, 0x8f, 0x07, 0xf4, 0xb3, 0x60, 0xf2, \
0x3f, 0x49, 0x18, 0xdb, 0x2e, 0x94, 0x6b, 0x53, 0x9e, 0xa2, 0x63, 0xde, \
0x63, 0xd9, 0xab, 0x21, 0x2e, 0x2d, 0x0a, 0xe0, 0xd0, 0xe8, 0xba, 0xc4, \
0x4c, 0x1e, 0xa5, 0xf5, 0x51, 0xa8, 0xc4, 0x92, 0xf8, 0x7f, 0x21, 0xe7, \
0x65, 0xbf, 0x0b, 0xe6, 0x01, 0xaf, 0x9c, 0x1d, 0x5b, 0x6c, 0x3f, 0x1c, \
0x2f, 0xa6, 0x0f, 0x68, 0x38, 0x8e, 0x85, 0xc4, 0x6c, 0x78, 0x2f, 0x6f, \
0x06, 0x21, 0x2e, 0x56 \
}
/* END FILE */
/*
* Test client Certificates
*
* Test client certificates are defined for each choice
* of the following parameters:
* - PEM or DER encoding
* - RSA or EC key
*
* Things to add:
* - hash type
* - multiple EC curve types
*/
/* This is taken from tests/data_files/cli2.crt. */
/* BEGIN FILE string macro TEST_CLI_CRT_EC_PEM tests/data_files/cli2.crt */
#define TEST_CLI_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIB3zCCAWOgAwIBAgIBDTAMBggqhkjOPQQDAgUAMD4xCzAJBgNVBAYTAk5MMREw\r\n" \
"DwYDVQQKDAhQb2xhclNTTDEcMBoGA1UEAwwTUG9sYXJTU0wgVGVzdCBFQyBDQTAe\r\n" \
"Fw0xOTAyMTAxNDQ0MDBaFw0yOTAyMTAxNDQ0MDBaMEExCzAJBgNVBAYTAk5MMREw\r\n" \
"DwYDVQQKDAhQb2xhclNTTDEfMB0GA1UEAwwWUG9sYXJTU0wgVGVzdCBDbGllbnQg\r\n" \
"MjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABFflrrFz39Osu5O4gf8Sru7mU6zO\r\n" \
"VVP2NA7MLuNjJQvfmOLzXGA2lsDVGBRw5X+f1UtFGOWwbNVc+JaPh3Cj5MejTTBL\r\n" \
"MAkGA1UdEwQCMAAwHQYDVR0OBBYEFHoAX4Zk/OBd5REQO7LmO8QmP8/iMB8GA1Ud\r\n" \
"IwQYMBaAFJ1tICRJAT8ry3i1Gbx+JMnb+zZ8MAwGCCqGSM49BAMCBQADaAAwZQIx\r\n" \
"AMqme4DKMldUlplDET9Q6Eptre7uUWKhsLOF+zPkKDlfzpIkJYEFgcloDHGYw80u\r\n" \
"IgIwNftyPXsabTqMM7iEHgVpX/GRozKklY9yQI/5eoA6gGW7Y+imuGR/oao5ySOb\r\n" \
"a9Vk\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/cli2.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CLI_CRT_EC_DER tests/data_files/cli2.crt.der */
#define TEST_CLI_CRT_EC_DER { \
0x30, 0x82, 0x01, 0xdf, 0x30, 0x82, 0x01, 0x63, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x0d, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, \
0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \
0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, \
0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, \
0x03, 0x0c, 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, \
0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, \
0x17, 0x0d, 0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, \
0x30, 0x30, 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, \
0x34, 0x34, 0x34, 0x30, 0x30, 0x5a, 0x30, 0x41, 0x31, 0x0b, 0x30, 0x09, \
0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \
0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, \
0x72, 0x53, 0x53, 0x4c, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, \
0x03, 0x0c, 0x16, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, \
0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, \
0x32, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, \
0x03, 0x42, 0x00, 0x04, 0x57, 0xe5, 0xae, 0xb1, 0x73, 0xdf, 0xd3, 0xac, \
0xbb, 0x93, 0xb8, 0x81, 0xff, 0x12, 0xae, 0xee, 0xe6, 0x53, 0xac, 0xce, \
0x55, 0x53, 0xf6, 0x34, 0x0e, 0xcc, 0x2e, 0xe3, 0x63, 0x25, 0x0b, 0xdf, \
0x98, 0xe2, 0xf3, 0x5c, 0x60, 0x36, 0x96, 0xc0, 0xd5, 0x18, 0x14, 0x70, \
0xe5, 0x7f, 0x9f, 0xd5, 0x4b, 0x45, 0x18, 0xe5, 0xb0, 0x6c, 0xd5, 0x5c, \
0xf8, 0x96, 0x8f, 0x87, 0x70, 0xa3, 0xe4, 0xc7, 0xa3, 0x4d, 0x30, 0x4b, \
0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, \
0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x7a, 0x00, \
0x5f, 0x86, 0x64, 0xfc, 0xe0, 0x5d, 0xe5, 0x11, 0x10, 0x3b, 0xb2, 0xe6, \
0x3b, 0xc4, 0x26, 0x3f, 0xcf, 0xe2, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, \
0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, 0x49, \
0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, 0xdb, \
0xfb, 0x36, 0x7c, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, 0x31, \
0x00, 0xca, 0xa6, 0x7b, 0x80, 0xca, 0x32, 0x57, 0x54, 0x96, 0x99, 0x43, \
0x11, 0x3f, 0x50, 0xe8, 0x4a, 0x6d, 0xad, 0xee, 0xee, 0x51, 0x62, 0xa1, \
0xb0, 0xb3, 0x85, 0xfb, 0x33, 0xe4, 0x28, 0x39, 0x5f, 0xce, 0x92, 0x24, \
0x25, 0x81, 0x05, 0x81, 0xc9, 0x68, 0x0c, 0x71, 0x98, 0xc3, 0xcd, 0x2e, \
0x22, 0x02, 0x30, 0x35, 0xfb, 0x72, 0x3d, 0x7b, 0x1a, 0x6d, 0x3a, 0x8c, \
0x33, 0xb8, 0x84, 0x1e, 0x05, 0x69, 0x5f, 0xf1, 0x91, 0xa3, 0x32, 0xa4, \
0x95, 0x8f, 0x72, 0x40, 0x8f, 0xf9, 0x7a, 0x80, 0x3a, 0x80, 0x65, 0xbb, \
0x63, 0xe8, 0xa6, 0xb8, 0x64, 0x7f, 0xa1, 0xaa, 0x39, 0xc9, 0x23, 0x9b, \
0x6b, 0xd5, 0x64 \
}
/* END FILE */
/* This is taken from tests/data_files/cli2.key. */
/* BEGIN FILE string macro TEST_CLI_KEY_EC_PEM tests/data_files/cli2.key */
#define TEST_CLI_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"MHcCAQEEIPb3hmTxZ3/mZI3vyk7p3U3wBf+WIop6hDhkFzJhmLcqoAoGCCqGSM49\r\n" \
"AwEHoUQDQgAEV+WusXPf06y7k7iB/xKu7uZTrM5VU/Y0Dswu42MlC9+Y4vNcYDaW\r\n" \
"wNUYFHDlf5/VS0UY5bBs1Vz4lo+HcKPkxw==\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/cli2.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CLI_KEY_EC_DER tests/data_files/cli2.key.der */
#define TEST_CLI_KEY_EC_DER { \
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0xf6, 0xf7, 0x86, 0x64, 0xf1, \
0x67, 0x7f, 0xe6, 0x64, 0x8d, 0xef, 0xca, 0x4e, 0xe9, 0xdd, 0x4d, 0xf0, \
0x05, 0xff, 0x96, 0x22, 0x8a, 0x7a, 0x84, 0x38, 0x64, 0x17, 0x32, 0x61, \
0x98, 0xb7, 0x2a, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x57, 0xe5, 0xae, \
0xb1, 0x73, 0xdf, 0xd3, 0xac, 0xbb, 0x93, 0xb8, 0x81, 0xff, 0x12, 0xae, \
0xee, 0xe6, 0x53, 0xac, 0xce, 0x55, 0x53, 0xf6, 0x34, 0x0e, 0xcc, 0x2e, \
0xe3, 0x63, 0x25, 0x0b, 0xdf, 0x98, 0xe2, 0xf3, 0x5c, 0x60, 0x36, 0x96, \
0xc0, 0xd5, 0x18, 0x14, 0x70, 0xe5, 0x7f, 0x9f, 0xd5, 0x4b, 0x45, 0x18, \
0xe5, 0xb0, 0x6c, 0xd5, 0x5c, 0xf8, 0x96, 0x8f, 0x87, 0x70, 0xa3, 0xe4, \
0xc7 \
}
/* END FILE */
/* This is taken from tests/data_files/cli-rsa-sha256.crt. */
/* BEGIN FILE string macro TEST_CLI_CRT_RSA_PEM tests/data_files/cli-rsa-sha256.crt */
#define TEST_CLI_CRT_RSA_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDPzCCAiegAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxGjAYBgNVBAMMEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\r\n" \
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6f\r\n" \
"M60Nj4o8VmXl3ETZzGaFB9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu\r\n" \
"1C93KYRhTYJQj6eVSHD1bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEw\r\n" \
"MjDV0/YI0FZPRo7yX/k9Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v\r\n" \
"4Jv4EFbMs44TFeY0BGbH7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx/\r\n" \
"/DZrtenNLQNiTrM9AM+vdqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQAB\r\n" \
"o00wSzAJBgNVHRMEAjAAMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITAf\r\n" \
"BgNVHSMEGDAWgBS0WuSls97SUva51aaVD+s+vMf9/zANBgkqhkiG9w0BAQsFAAOC\r\n" \
"AQEAXidv1d4pLlBiKWED95rMycBdgDcgyNqJxakFkRfRyA2y1mlyTn7uBXRkNLY5\r\n" \
"ZFzK82GCjk2Q2OD4RZSCPAJJqLpHHU34t71ciffvy2KK81YvrxczRhMAE64i+qna\r\n" \
"yP3Td2XuWJR05PVPoSemsNELs9gWttdnYy3ce+EY2Y0n7Rsi7982EeLIAA7H6ca4\r\n" \
"2Es/NUH//JZJT32OP0doMxeDRA+vplkKqTLLWf7dX26LIriBkBaRCgR5Yv9LBPFc\r\n" \
"NOtpzu/LbrY7QFXKJMI+JXDudCsOn8KCmiA4d6Emisqfh3V3485l7HEQNcvLTxlD\r\n" \
"6zDQyi0/ykYUYZkwQTK1N2Nvlw==\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This was generated from tests/data_files/cli-rsa-sha256.crt.der
using `xxd -i.` */
/* BEGIN FILE binary macro TEST_CLI_CRT_RSA_DER tests/data_files/cli-rsa-sha256.crt.der */
#define TEST_CLI_CRT_RSA_DER { \
0x30, 0x82, 0x03, 0x3f, 0x30, 0x82, 0x02, 0x27, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x04, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \
0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \
0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \
0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \
0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \
0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \
0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \
0x34, 0x30, 0x36, 0x5a, 0x30, 0x3c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \
0x53, 0x4c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \
0x11, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x43, 0x6c, \
0x69, 0x65, 0x6e, 0x74, 0x20, 0x32, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, \
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, \
0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, \
0x01, 0x01, 0x00, 0xc8, 0x74, 0xc4, 0xcc, 0xb9, 0xf9, 0xb5, 0x79, 0xe9, \
0x45, 0xd9, 0x14, 0x60, 0xb0, 0x7d, 0xbb, 0x93, 0xf2, 0x6b, 0x1e, 0x9f, \
0x33, 0xad, 0x0d, 0x8f, 0x8a, 0x3c, 0x56, 0x65, 0xe5, 0xdc, 0x44, 0xd9, \
0xcc, 0x66, 0x85, 0x07, 0xd5, 0xf8, 0x27, 0xb0, 0x4a, 0x35, 0xd0, 0x63, \
0x9e, 0x0a, 0x6e, 0x1b, 0xb7, 0xda, 0xf0, 0x7e, 0xab, 0xee, 0x0c, 0x10, \
0x93, 0x86, 0x49, 0x18, 0x34, 0xf3, 0xa8, 0x2a, 0xd2, 0x57, 0xf5, 0x2e, \
0xd4, 0x2f, 0x77, 0x29, 0x84, 0x61, 0x4d, 0x82, 0x50, 0x8f, 0xa7, 0x95, \
0x48, 0x70, 0xf5, 0x6e, 0x4d, 0xb2, 0xd5, 0x13, 0xc3, 0xd2, 0x1a, 0xed, \
0xe6, 0x43, 0xea, 0x42, 0x14, 0xeb, 0x74, 0xea, 0xc0, 0xed, 0x1f, 0xd4, \
0x57, 0x4e, 0xa9, 0xf3, 0xa8, 0xed, 0xd2, 0xe0, 0xc1, 0x30, 0x71, 0x30, \
0x32, 0x30, 0xd5, 0xd3, 0xf6, 0x08, 0xd0, 0x56, 0x4f, 0x46, 0x8e, 0xf2, \
0x5f, 0xf9, 0x3d, 0x67, 0x91, 0x88, 0x30, 0x2e, 0x42, 0xb2, 0xdf, 0x7d, \
0xfb, 0xe5, 0x0c, 0x77, 0xff, 0xec, 0x31, 0xc0, 0x78, 0x8f, 0xbf, 0xc2, \
0x7f, 0xca, 0xad, 0x6c, 0x21, 0xd6, 0x8d, 0xd9, 0x8b, 0x6a, 0x8e, 0x6f, \
0xe0, 0x9b, 0xf8, 0x10, 0x56, 0xcc, 0xb3, 0x8e, 0x13, 0x15, 0xe6, 0x34, \
0x04, 0x66, 0xc7, 0xee, 0xf9, 0x36, 0x0e, 0x6a, 0x95, 0xf6, 0x09, 0x9a, \
0x06, 0x67, 0xf4, 0x65, 0x71, 0xf8, 0xca, 0xa4, 0xb1, 0x25, 0xe0, 0xfe, \
0x3c, 0x8b, 0x35, 0x04, 0x67, 0xba, 0xe0, 0x4f, 0x76, 0x85, 0xfc, 0x7f, \
0xfc, 0x36, 0x6b, 0xb5, 0xe9, 0xcd, 0x2d, 0x03, 0x62, 0x4e, 0xb3, 0x3d, \
0x00, 0xcf, 0xaf, 0x76, 0xa0, 0x69, 0x56, 0x83, 0x6a, 0xd2, 0xa8, 0xd4, \
0xe7, 0x50, 0x71, 0xe6, 0xb5, 0x36, 0x05, 0x77, 0x05, 0x6d, 0x7b, 0xc8, \
0xe4, 0xc4, 0xfd, 0x4c, 0xd5, 0x21, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01, \
0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, \
0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, \
0x04, 0x14, 0x71, 0xa1, 0x00, 0x73, 0x72, 0x40, 0x2f, 0x54, 0x76, 0x5e, \
0x33, 0xfc, 0x52, 0x8f, 0xbc, 0xf1, 0xdd, 0x6b, 0x46, 0x21, 0x30, 0x1f, \
0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xb4, \
0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, 0xa6, 0x95, \
0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, \
0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, \
0x01, 0x01, 0x00, 0x5e, 0x27, 0x6f, 0xd5, 0xde, 0x29, 0x2e, 0x50, 0x62, \
0x29, 0x61, 0x03, 0xf7, 0x9a, 0xcc, 0xc9, 0xc0, 0x5d, 0x80, 0x37, 0x20, \
0xc8, 0xda, 0x89, 0xc5, 0xa9, 0x05, 0x91, 0x17, 0xd1, 0xc8, 0x0d, 0xb2, \
0xd6, 0x69, 0x72, 0x4e, 0x7e, 0xee, 0x05, 0x74, 0x64, 0x34, 0xb6, 0x39, \
0x64, 0x5c, 0xca, 0xf3, 0x61, 0x82, 0x8e, 0x4d, 0x90, 0xd8, 0xe0, 0xf8, \
0x45, 0x94, 0x82, 0x3c, 0x02, 0x49, 0xa8, 0xba, 0x47, 0x1d, 0x4d, 0xf8, \
0xb7, 0xbd, 0x5c, 0x89, 0xf7, 0xef, 0xcb, 0x62, 0x8a, 0xf3, 0x56, 0x2f, \
0xaf, 0x17, 0x33, 0x46, 0x13, 0x00, 0x13, 0xae, 0x22, 0xfa, 0xa9, 0xda, \
0xc8, 0xfd, 0xd3, 0x77, 0x65, 0xee, 0x58, 0x94, 0x74, 0xe4, 0xf5, 0x4f, \
0xa1, 0x27, 0xa6, 0xb0, 0xd1, 0x0b, 0xb3, 0xd8, 0x16, 0xb6, 0xd7, 0x67, \
0x63, 0x2d, 0xdc, 0x7b, 0xe1, 0x18, 0xd9, 0x8d, 0x27, 0xed, 0x1b, 0x22, \
0xef, 0xdf, 0x36, 0x11, 0xe2, 0xc8, 0x00, 0x0e, 0xc7, 0xe9, 0xc6, 0xb8, \
0xd8, 0x4b, 0x3f, 0x35, 0x41, 0xff, 0xfc, 0x96, 0x49, 0x4f, 0x7d, 0x8e, \
0x3f, 0x47, 0x68, 0x33, 0x17, 0x83, 0x44, 0x0f, 0xaf, 0xa6, 0x59, 0x0a, \
0xa9, 0x32, 0xcb, 0x59, 0xfe, 0xdd, 0x5f, 0x6e, 0x8b, 0x22, 0xb8, 0x81, \
0x90, 0x16, 0x91, 0x0a, 0x04, 0x79, 0x62, 0xff, 0x4b, 0x04, 0xf1, 0x5c, \
0x34, 0xeb, 0x69, 0xce, 0xef, 0xcb, 0x6e, 0xb6, 0x3b, 0x40, 0x55, 0xca, \
0x24, 0xc2, 0x3e, 0x25, 0x70, 0xee, 0x74, 0x2b, 0x0e, 0x9f, 0xc2, 0x82, \
0x9a, 0x20, 0x38, 0x77, 0xa1, 0x26, 0x8a, 0xca, 0x9f, 0x87, 0x75, 0x77, \
0xe3, 0xce, 0x65, 0xec, 0x71, 0x10, 0x35, 0xcb, 0xcb, 0x4f, 0x19, 0x43, \
0xeb, 0x30, 0xd0, 0xca, 0x2d, 0x3f, 0xca, 0x46, 0x14, 0x61, 0x99, 0x30, \
0x41, 0x32, 0xb5, 0x37, 0x63, 0x6f, 0x97 \
}
/* END FILE */
/* This is taken from tests/data_files/cli-rsa.key. */
/* BEGIN FILE string macro TEST_CLI_KEY_RSA_PEM tests/data_files/cli-rsa.key */
#define TEST_CLI_KEY_RSA_PEM \
"-----BEGIN RSA PRIVATE KEY-----\r\n" \
"MIIEpAIBAAKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6fM60Nj4o8VmXl3ETZzGaF\r\n" \
"B9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu1C93KYRhTYJQj6eVSHD1\r\n" \
"bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEwMjDV0/YI0FZPRo7yX/k9\r\n" \
"Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v4Jv4EFbMs44TFeY0BGbH\r\n" \
"7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx//DZrtenNLQNiTrM9AM+v\r\n" \
"dqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQABAoIBAGdNtfYDiap6bzst\r\n" \
"yhCiI8m9TtrhZw4MisaEaN/ll3XSjaOG2dvV6xMZCMV+5TeXDHOAZnY18Yi18vzz\r\n" \
"4Ut2TnNFzizCECYNaA2fST3WgInnxUkV3YXAyP6CNxJaCmv2aA0yFr2kFVSeaKGt\r\n" \
"ymvljNp2NVkvm7Th8fBQBO7I7AXhz43k0mR7XmPgewe8ApZOG3hstkOaMvbWAvWA\r\n" \
"zCZupdDjZYjOJqlA4eEA4H8/w7F83r5CugeBE8LgEREjLPiyejrU5H1fubEY+h0d\r\n" \
"l5HZBJ68ybTXfQ5U9o/QKA3dd0toBEhhdRUDGzWtjvwkEQfqF1reGWj/tod/gCpf\r\n" \
"DFi6X0ECgYEA4wOv/pjSC3ty6TuOvKX2rOUiBrLXXv2JSxZnMoMiWI5ipLQt+RYT\r\n" \
"VPafL/m7Dn6MbwjayOkcZhBwk5CNz5A6Q4lJ64Mq/lqHznRCQQ2Mc1G8eyDF/fYL\r\n" \
"Ze2pLvwP9VD5jTc2miDfw+MnvJhywRRLcemDFP8k4hQVtm8PMp3ZmNECgYEA4gz7\r\n" \
"wzObR4gn8ibe617uQPZjWzUj9dUHYd+in1gwBCIrtNnaRn9I9U/Q6tegRYpii4ys\r\n" \
"c176NmU+umy6XmuSKV5qD9bSpZWG2nLFnslrN15Lm3fhZxoeMNhBaEDTnLT26yoi\r\n" \
"33gp0mSSWy94ZEqipms+ULF6sY1ZtFW6tpGFoy8CgYAQHhnnvJflIs2ky4q10B60\r\n" \
"ZcxFp3rtDpkp0JxhFLhiizFrujMtZSjYNm5U7KkgPVHhLELEUvCmOnKTt4ap/vZ0\r\n" \
"BxJNe1GZH3pW6SAvGDQpl9sG7uu/vTFP+lCxukmzxB0DrrDcvorEkKMom7ZCCRvW\r\n" \
"KZsZ6YeH2Z81BauRj218kQKBgQCUV/DgKP2985xDTT79N08jUo3hTP5MVYCCuj/+\r\n" \
"UeEw1TvZcx3LJby7P6Xad6a1/BqveaGyFKIfEFIaBUBItk801sDDpDaYc4gL00Xc\r\n" \
"7lFuBHOZkxJYlss5QrGpuOEl9ZwUt5IrFLBdYaKqNHzNVC1pCPfb/JyH6Dr2HUxq\r\n" \
"gxUwAQKBgQCcU6G2L8AG9d9c0UpOyL1tMvFe5Ttw0KjlQVdsh1MP6yigYo9DYuwu\r\n" \
"bHFVW2r0dBTqegP2/KTOxKzaHfC1qf0RGDsUoJCNJrd1cwoCLG8P2EF4w3OBrKqv\r\n" \
"8u4ytY0F+Vlanj5lm3TaoHSVF1+NWPyOTiwevIECGKwSxvlki4fDAA==\r\n" \
"-----END RSA PRIVATE KEY-----\r\n"/* END FILE */
/* This was generated from tests/data_files/cli-rsa.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CLI_KEY_RSA_DER tests/data_files/cli-rsa.key.der */
#define TEST_CLI_KEY_RSA_DER { \
0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \
0xc8, 0x74, 0xc4, 0xcc, 0xb9, 0xf9, 0xb5, 0x79, 0xe9, 0x45, 0xd9, 0x14, \
0x60, 0xb0, 0x7d, 0xbb, 0x93, 0xf2, 0x6b, 0x1e, 0x9f, 0x33, 0xad, 0x0d, \
0x8f, 0x8a, 0x3c, 0x56, 0x65, 0xe5, 0xdc, 0x44, 0xd9, 0xcc, 0x66, 0x85, \
0x07, 0xd5, 0xf8, 0x27, 0xb0, 0x4a, 0x35, 0xd0, 0x63, 0x9e, 0x0a, 0x6e, \
0x1b, 0xb7, 0xda, 0xf0, 0x7e, 0xab, 0xee, 0x0c, 0x10, 0x93, 0x86, 0x49, \
0x18, 0x34, 0xf3, 0xa8, 0x2a, 0xd2, 0x57, 0xf5, 0x2e, 0xd4, 0x2f, 0x77, \
0x29, 0x84, 0x61, 0x4d, 0x82, 0x50, 0x8f, 0xa7, 0x95, 0x48, 0x70, 0xf5, \
0x6e, 0x4d, 0xb2, 0xd5, 0x13, 0xc3, 0xd2, 0x1a, 0xed, 0xe6, 0x43, 0xea, \
0x42, 0x14, 0xeb, 0x74, 0xea, 0xc0, 0xed, 0x1f, 0xd4, 0x57, 0x4e, 0xa9, \
0xf3, 0xa8, 0xed, 0xd2, 0xe0, 0xc1, 0x30, 0x71, 0x30, 0x32, 0x30, 0xd5, \
0xd3, 0xf6, 0x08, 0xd0, 0x56, 0x4f, 0x46, 0x8e, 0xf2, 0x5f, 0xf9, 0x3d, \
0x67, 0x91, 0x88, 0x30, 0x2e, 0x42, 0xb2, 0xdf, 0x7d, 0xfb, 0xe5, 0x0c, \
0x77, 0xff, 0xec, 0x31, 0xc0, 0x78, 0x8f, 0xbf, 0xc2, 0x7f, 0xca, 0xad, \
0x6c, 0x21, 0xd6, 0x8d, 0xd9, 0x8b, 0x6a, 0x8e, 0x6f, 0xe0, 0x9b, 0xf8, \
0x10, 0x56, 0xcc, 0xb3, 0x8e, 0x13, 0x15, 0xe6, 0x34, 0x04, 0x66, 0xc7, \
0xee, 0xf9, 0x36, 0x0e, 0x6a, 0x95, 0xf6, 0x09, 0x9a, 0x06, 0x67, 0xf4, \
0x65, 0x71, 0xf8, 0xca, 0xa4, 0xb1, 0x25, 0xe0, 0xfe, 0x3c, 0x8b, 0x35, \
0x04, 0x67, 0xba, 0xe0, 0x4f, 0x76, 0x85, 0xfc, 0x7f, 0xfc, 0x36, 0x6b, \
0xb5, 0xe9, 0xcd, 0x2d, 0x03, 0x62, 0x4e, 0xb3, 0x3d, 0x00, 0xcf, 0xaf, \
0x76, 0xa0, 0x69, 0x56, 0x83, 0x6a, 0xd2, 0xa8, 0xd4, 0xe7, 0x50, 0x71, \
0xe6, 0xb5, 0x36, 0x05, 0x77, 0x05, 0x6d, 0x7b, 0xc8, 0xe4, 0xc4, 0xfd, \
0x4c, 0xd5, 0x21, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \
0x00, 0x67, 0x4d, 0xb5, 0xf6, 0x03, 0x89, 0xaa, 0x7a, 0x6f, 0x3b, 0x2d, \
0xca, 0x10, 0xa2, 0x23, 0xc9, 0xbd, 0x4e, 0xda, 0xe1, 0x67, 0x0e, 0x0c, \
0x8a, 0xc6, 0x84, 0x68, 0xdf, 0xe5, 0x97, 0x75, 0xd2, 0x8d, 0xa3, 0x86, \
0xd9, 0xdb, 0xd5, 0xeb, 0x13, 0x19, 0x08, 0xc5, 0x7e, 0xe5, 0x37, 0x97, \
0x0c, 0x73, 0x80, 0x66, 0x76, 0x35, 0xf1, 0x88, 0xb5, 0xf2, 0xfc, 0xf3, \
0xe1, 0x4b, 0x76, 0x4e, 0x73, 0x45, 0xce, 0x2c, 0xc2, 0x10, 0x26, 0x0d, \
0x68, 0x0d, 0x9f, 0x49, 0x3d, 0xd6, 0x80, 0x89, 0xe7, 0xc5, 0x49, 0x15, \
0xdd, 0x85, 0xc0, 0xc8, 0xfe, 0x82, 0x37, 0x12, 0x5a, 0x0a, 0x6b, 0xf6, \
0x68, 0x0d, 0x32, 0x16, 0xbd, 0xa4, 0x15, 0x54, 0x9e, 0x68, 0xa1, 0xad, \
0xca, 0x6b, 0xe5, 0x8c, 0xda, 0x76, 0x35, 0x59, 0x2f, 0x9b, 0xb4, 0xe1, \
0xf1, 0xf0, 0x50, 0x04, 0xee, 0xc8, 0xec, 0x05, 0xe1, 0xcf, 0x8d, 0xe4, \
0xd2, 0x64, 0x7b, 0x5e, 0x63, 0xe0, 0x7b, 0x07, 0xbc, 0x02, 0x96, 0x4e, \
0x1b, 0x78, 0x6c, 0xb6, 0x43, 0x9a, 0x32, 0xf6, 0xd6, 0x02, 0xf5, 0x80, \
0xcc, 0x26, 0x6e, 0xa5, 0xd0, 0xe3, 0x65, 0x88, 0xce, 0x26, 0xa9, 0x40, \
0xe1, 0xe1, 0x00, 0xe0, 0x7f, 0x3f, 0xc3, 0xb1, 0x7c, 0xde, 0xbe, 0x42, \
0xba, 0x07, 0x81, 0x13, 0xc2, 0xe0, 0x11, 0x11, 0x23, 0x2c, 0xf8, 0xb2, \
0x7a, 0x3a, 0xd4, 0xe4, 0x7d, 0x5f, 0xb9, 0xb1, 0x18, 0xfa, 0x1d, 0x1d, \
0x97, 0x91, 0xd9, 0x04, 0x9e, 0xbc, 0xc9, 0xb4, 0xd7, 0x7d, 0x0e, 0x54, \
0xf6, 0x8f, 0xd0, 0x28, 0x0d, 0xdd, 0x77, 0x4b, 0x68, 0x04, 0x48, 0x61, \
0x75, 0x15, 0x03, 0x1b, 0x35, 0xad, 0x8e, 0xfc, 0x24, 0x11, 0x07, 0xea, \
0x17, 0x5a, 0xde, 0x19, 0x68, 0xff, 0xb6, 0x87, 0x7f, 0x80, 0x2a, 0x5f, \
0x0c, 0x58, 0xba, 0x5f, 0x41, 0x02, 0x81, 0x81, 0x00, 0xe3, 0x03, 0xaf, \
0xfe, 0x98, 0xd2, 0x0b, 0x7b, 0x72, 0xe9, 0x3b, 0x8e, 0xbc, 0xa5, 0xf6, \
0xac, 0xe5, 0x22, 0x06, 0xb2, 0xd7, 0x5e, 0xfd, 0x89, 0x4b, 0x16, 0x67, \
0x32, 0x83, 0x22, 0x58, 0x8e, 0x62, 0xa4, 0xb4, 0x2d, 0xf9, 0x16, 0x13, \
0x54, 0xf6, 0x9f, 0x2f, 0xf9, 0xbb, 0x0e, 0x7e, 0x8c, 0x6f, 0x08, 0xda, \
0xc8, 0xe9, 0x1c, 0x66, 0x10, 0x70, 0x93, 0x90, 0x8d, 0xcf, 0x90, 0x3a, \
0x43, 0x89, 0x49, 0xeb, 0x83, 0x2a, 0xfe, 0x5a, 0x87, 0xce, 0x74, 0x42, \
0x41, 0x0d, 0x8c, 0x73, 0x51, 0xbc, 0x7b, 0x20, 0xc5, 0xfd, 0xf6, 0x0b, \
0x65, 0xed, 0xa9, 0x2e, 0xfc, 0x0f, 0xf5, 0x50, 0xf9, 0x8d, 0x37, 0x36, \
0x9a, 0x20, 0xdf, 0xc3, 0xe3, 0x27, 0xbc, 0x98, 0x72, 0xc1, 0x14, 0x4b, \
0x71, 0xe9, 0x83, 0x14, 0xff, 0x24, 0xe2, 0x14, 0x15, 0xb6, 0x6f, 0x0f, \
0x32, 0x9d, 0xd9, 0x98, 0xd1, 0x02, 0x81, 0x81, 0x00, 0xe2, 0x0c, 0xfb, \
0xc3, 0x33, 0x9b, 0x47, 0x88, 0x27, 0xf2, 0x26, 0xde, 0xeb, 0x5e, 0xee, \
0x40, 0xf6, 0x63, 0x5b, 0x35, 0x23, 0xf5, 0xd5, 0x07, 0x61, 0xdf, 0xa2, \
0x9f, 0x58, 0x30, 0x04, 0x22, 0x2b, 0xb4, 0xd9, 0xda, 0x46, 0x7f, 0x48, \
0xf5, 0x4f, 0xd0, 0xea, 0xd7, 0xa0, 0x45, 0x8a, 0x62, 0x8b, 0x8c, 0xac, \
0x73, 0x5e, 0xfa, 0x36, 0x65, 0x3e, 0xba, 0x6c, 0xba, 0x5e, 0x6b, 0x92, \
0x29, 0x5e, 0x6a, 0x0f, 0xd6, 0xd2, 0xa5, 0x95, 0x86, 0xda, 0x72, 0xc5, \
0x9e, 0xc9, 0x6b, 0x37, 0x5e, 0x4b, 0x9b, 0x77, 0xe1, 0x67, 0x1a, 0x1e, \
0x30, 0xd8, 0x41, 0x68, 0x40, 0xd3, 0x9c, 0xb4, 0xf6, 0xeb, 0x2a, 0x22, \
0xdf, 0x78, 0x29, 0xd2, 0x64, 0x92, 0x5b, 0x2f, 0x78, 0x64, 0x4a, 0xa2, \
0xa6, 0x6b, 0x3e, 0x50, 0xb1, 0x7a, 0xb1, 0x8d, 0x59, 0xb4, 0x55, 0xba, \
0xb6, 0x91, 0x85, 0xa3, 0x2f, 0x02, 0x81, 0x80, 0x10, 0x1e, 0x19, 0xe7, \
0xbc, 0x97, 0xe5, 0x22, 0xcd, 0xa4, 0xcb, 0x8a, 0xb5, 0xd0, 0x1e, 0xb4, \
0x65, 0xcc, 0x45, 0xa7, 0x7a, 0xed, 0x0e, 0x99, 0x29, 0xd0, 0x9c, 0x61, \
0x14, 0xb8, 0x62, 0x8b, 0x31, 0x6b, 0xba, 0x33, 0x2d, 0x65, 0x28, 0xd8, \
0x36, 0x6e, 0x54, 0xec, 0xa9, 0x20, 0x3d, 0x51, 0xe1, 0x2c, 0x42, 0xc4, \
0x52, 0xf0, 0xa6, 0x3a, 0x72, 0x93, 0xb7, 0x86, 0xa9, 0xfe, 0xf6, 0x74, \
0x07, 0x12, 0x4d, 0x7b, 0x51, 0x99, 0x1f, 0x7a, 0x56, 0xe9, 0x20, 0x2f, \
0x18, 0x34, 0x29, 0x97, 0xdb, 0x06, 0xee, 0xeb, 0xbf, 0xbd, 0x31, 0x4f, \
0xfa, 0x50, 0xb1, 0xba, 0x49, 0xb3, 0xc4, 0x1d, 0x03, 0xae, 0xb0, 0xdc, \
0xbe, 0x8a, 0xc4, 0x90, 0xa3, 0x28, 0x9b, 0xb6, 0x42, 0x09, 0x1b, 0xd6, \
0x29, 0x9b, 0x19, 0xe9, 0x87, 0x87, 0xd9, 0x9f, 0x35, 0x05, 0xab, 0x91, \
0x8f, 0x6d, 0x7c, 0x91, 0x02, 0x81, 0x81, 0x00, 0x94, 0x57, 0xf0, 0xe0, \
0x28, 0xfd, 0xbd, 0xf3, 0x9c, 0x43, 0x4d, 0x3e, 0xfd, 0x37, 0x4f, 0x23, \
0x52, 0x8d, 0xe1, 0x4c, 0xfe, 0x4c, 0x55, 0x80, 0x82, 0xba, 0x3f, 0xfe, \
0x51, 0xe1, 0x30, 0xd5, 0x3b, 0xd9, 0x73, 0x1d, 0xcb, 0x25, 0xbc, 0xbb, \
0x3f, 0xa5, 0xda, 0x77, 0xa6, 0xb5, 0xfc, 0x1a, 0xaf, 0x79, 0xa1, 0xb2, \
0x14, 0xa2, 0x1f, 0x10, 0x52, 0x1a, 0x05, 0x40, 0x48, 0xb6, 0x4f, 0x34, \
0xd6, 0xc0, 0xc3, 0xa4, 0x36, 0x98, 0x73, 0x88, 0x0b, 0xd3, 0x45, 0xdc, \
0xee, 0x51, 0x6e, 0x04, 0x73, 0x99, 0x93, 0x12, 0x58, 0x96, 0xcb, 0x39, \
0x42, 0xb1, 0xa9, 0xb8, 0xe1, 0x25, 0xf5, 0x9c, 0x14, 0xb7, 0x92, 0x2b, \
0x14, 0xb0, 0x5d, 0x61, 0xa2, 0xaa, 0x34, 0x7c, 0xcd, 0x54, 0x2d, 0x69, \
0x08, 0xf7, 0xdb, 0xfc, 0x9c, 0x87, 0xe8, 0x3a, 0xf6, 0x1d, 0x4c, 0x6a, \
0x83, 0x15, 0x30, 0x01, 0x02, 0x81, 0x81, 0x00, 0x9c, 0x53, 0xa1, 0xb6, \
0x2f, 0xc0, 0x06, 0xf5, 0xdf, 0x5c, 0xd1, 0x4a, 0x4e, 0xc8, 0xbd, 0x6d, \
0x32, 0xf1, 0x5e, 0xe5, 0x3b, 0x70, 0xd0, 0xa8, 0xe5, 0x41, 0x57, 0x6c, \
0x87, 0x53, 0x0f, 0xeb, 0x28, 0xa0, 0x62, 0x8f, 0x43, 0x62, 0xec, 0x2e, \
0x6c, 0x71, 0x55, 0x5b, 0x6a, 0xf4, 0x74, 0x14, 0xea, 0x7a, 0x03, 0xf6, \
0xfc, 0xa4, 0xce, 0xc4, 0xac, 0xda, 0x1d, 0xf0, 0xb5, 0xa9, 0xfd, 0x11, \
0x18, 0x3b, 0x14, 0xa0, 0x90, 0x8d, 0x26, 0xb7, 0x75, 0x73, 0x0a, 0x02, \
0x2c, 0x6f, 0x0f, 0xd8, 0x41, 0x78, 0xc3, 0x73, 0x81, 0xac, 0xaa, 0xaf, \
0xf2, 0xee, 0x32, 0xb5, 0x8d, 0x05, 0xf9, 0x59, 0x5a, 0x9e, 0x3e, 0x65, \
0x9b, 0x74, 0xda, 0xa0, 0x74, 0x95, 0x17, 0x5f, 0x8d, 0x58, 0xfc, 0x8e, \
0x4e, 0x2c, 0x1e, 0xbc, 0x81, 0x02, 0x18, 0xac, 0x12, 0xc6, 0xf9, 0x64, \
0x8b, 0x87, 0xc3, 0x00 \
}
/* END FILE */
/*
*
* Test certificates and keys as C variables
*
*/
/*
* CA
*/
const char mbedtls_test_ca_crt_ec_pem[] = TEST_CA_CRT_EC_PEM;
const char mbedtls_test_ca_key_ec_pem[] = TEST_CA_KEY_EC_PEM;
const char mbedtls_test_ca_pwd_ec_pem[] = TEST_CA_PWD_EC_PEM;
const char mbedtls_test_ca_key_rsa_pem[] = TEST_CA_KEY_RSA_PEM;
const char mbedtls_test_ca_pwd_rsa_pem[] = TEST_CA_PWD_RSA_PEM;
const char mbedtls_test_ca_crt_rsa_sha1_pem[] = TEST_CA_CRT_RSA_SHA1_PEM;
const char mbedtls_test_ca_crt_rsa_sha256_pem[] = TEST_CA_CRT_RSA_SHA256_PEM;
const unsigned char mbedtls_test_ca_crt_ec_der[] = TEST_CA_CRT_EC_DER;
const unsigned char mbedtls_test_ca_key_ec_der[] = TEST_CA_KEY_EC_DER;
const unsigned char mbedtls_test_ca_key_rsa_der[] = TEST_CA_KEY_RSA_DER;
const unsigned char mbedtls_test_ca_crt_rsa_sha1_der[] =
TEST_CA_CRT_RSA_SHA1_DER;
const unsigned char mbedtls_test_ca_crt_rsa_sha256_der[] =
TEST_CA_CRT_RSA_SHA256_DER;
const size_t mbedtls_test_ca_crt_ec_pem_len =
sizeof( mbedtls_test_ca_crt_ec_pem );
const size_t mbedtls_test_ca_key_ec_pem_len =
sizeof( mbedtls_test_ca_key_ec_pem );
const size_t mbedtls_test_ca_pwd_ec_pem_len =
sizeof( mbedtls_test_ca_pwd_ec_pem ) - 1;
const size_t mbedtls_test_ca_key_rsa_pem_len =
sizeof( mbedtls_test_ca_key_rsa_pem );
const size_t mbedtls_test_ca_pwd_rsa_pem_len =
sizeof( mbedtls_test_ca_pwd_rsa_pem ) - 1;
const size_t mbedtls_test_ca_crt_rsa_sha1_pem_len =
sizeof( mbedtls_test_ca_crt_rsa_sha1_pem );
const size_t mbedtls_test_ca_crt_rsa_sha256_pem_len =
sizeof( mbedtls_test_ca_crt_rsa_sha256_pem );
const size_t mbedtls_test_ca_crt_ec_der_len =
sizeof( mbedtls_test_ca_crt_ec_der );
const size_t mbedtls_test_ca_key_ec_der_len =
sizeof( mbedtls_test_ca_key_ec_der );
const size_t mbedtls_test_ca_pwd_ec_der_len = 0;
const size_t mbedtls_test_ca_key_rsa_der_len =
sizeof( mbedtls_test_ca_key_rsa_der );
const size_t mbedtls_test_ca_pwd_rsa_der_len = 0;
const size_t mbedtls_test_ca_crt_rsa_sha1_der_len =
sizeof( mbedtls_test_ca_crt_rsa_sha1_der );
const size_t mbedtls_test_ca_crt_rsa_sha256_der_len =
sizeof( mbedtls_test_ca_crt_rsa_sha256_der );
/*
* Server
*/
const char mbedtls_test_srv_crt_ec_pem[] = TEST_SRV_CRT_EC_PEM;
const char mbedtls_test_srv_key_ec_pem[] = TEST_SRV_KEY_EC_PEM;
const char mbedtls_test_srv_pwd_ec_pem[] = "";
const char mbedtls_test_srv_key_rsa_pem[] = TEST_SRV_KEY_RSA_PEM;
const char mbedtls_test_srv_pwd_rsa_pem[] = "";
const char mbedtls_test_srv_crt_rsa_sha1_pem[] = TEST_SRV_CRT_RSA_SHA1_PEM;
const char mbedtls_test_srv_crt_rsa_sha256_pem[] = TEST_SRV_CRT_RSA_SHA256_PEM;
const unsigned char mbedtls_test_srv_crt_ec_der[] = TEST_SRV_CRT_EC_DER;
const unsigned char mbedtls_test_srv_key_ec_der[] = TEST_SRV_KEY_EC_DER;
const unsigned char mbedtls_test_srv_key_rsa_der[] = TEST_SRV_KEY_RSA_DER;
const unsigned char mbedtls_test_srv_crt_rsa_sha1_der[] =
TEST_SRV_CRT_RSA_SHA1_DER;
const unsigned char mbedtls_test_srv_crt_rsa_sha256_der[] =
TEST_SRV_CRT_RSA_SHA256_DER;
const size_t mbedtls_test_srv_crt_ec_pem_len =
sizeof( mbedtls_test_srv_crt_ec_pem );
const size_t mbedtls_test_srv_key_ec_pem_len =
sizeof( mbedtls_test_srv_key_ec_pem );
const size_t mbedtls_test_srv_pwd_ec_pem_len =
sizeof( mbedtls_test_srv_pwd_ec_pem ) - 1;
const size_t mbedtls_test_srv_key_rsa_pem_len =
sizeof( mbedtls_test_srv_key_rsa_pem );
const size_t mbedtls_test_srv_pwd_rsa_pem_len =
sizeof( mbedtls_test_srv_pwd_rsa_pem ) - 1;
const size_t mbedtls_test_srv_crt_rsa_sha1_pem_len =
sizeof( mbedtls_test_srv_crt_rsa_sha1_pem );
const size_t mbedtls_test_srv_crt_rsa_sha256_pem_len =
sizeof( mbedtls_test_srv_crt_rsa_sha256_pem );
const size_t mbedtls_test_srv_crt_ec_der_len =
sizeof( mbedtls_test_srv_crt_ec_der );
const size_t mbedtls_test_srv_key_ec_der_len =
sizeof( mbedtls_test_srv_key_ec_der );
const size_t mbedtls_test_srv_pwd_ec_der_len = 0;
const size_t mbedtls_test_srv_key_rsa_der_len =
sizeof( mbedtls_test_srv_key_rsa_der );
const size_t mbedtls_test_srv_pwd_rsa_der_len = 0;
const size_t mbedtls_test_srv_crt_rsa_sha1_der_len =
sizeof( mbedtls_test_srv_crt_rsa_sha1_der );
const size_t mbedtls_test_srv_crt_rsa_sha256_der_len =
sizeof( mbedtls_test_srv_crt_rsa_sha256_der );
/*
* Client
*/
const char mbedtls_test_cli_crt_ec_pem[] = TEST_CLI_CRT_EC_PEM;
const char mbedtls_test_cli_key_ec_pem[] = TEST_CLI_KEY_EC_PEM;
const char mbedtls_test_cli_pwd_ec_pem[] = "";
const char mbedtls_test_cli_key_rsa_pem[] = TEST_CLI_KEY_RSA_PEM;
const char mbedtls_test_cli_pwd_rsa_pem[] = "";
const char mbedtls_test_cli_crt_rsa_pem[] = TEST_CLI_CRT_RSA_PEM;
const unsigned char mbedtls_test_cli_crt_ec_der[] = TEST_CLI_CRT_EC_DER;
const unsigned char mbedtls_test_cli_key_ec_der[] = TEST_CLI_KEY_EC_DER;
const unsigned char mbedtls_test_cli_key_rsa_der[] = TEST_CLI_KEY_RSA_DER;
const unsigned char mbedtls_test_cli_crt_rsa_der[] = TEST_CLI_CRT_RSA_DER;
const size_t mbedtls_test_cli_crt_ec_pem_len =
sizeof( mbedtls_test_cli_crt_ec_pem );
const size_t mbedtls_test_cli_key_ec_pem_len =
sizeof( mbedtls_test_cli_key_ec_pem );
const size_t mbedtls_test_cli_pwd_ec_pem_len =
sizeof( mbedtls_test_cli_pwd_ec_pem ) - 1;
const size_t mbedtls_test_cli_key_rsa_pem_len =
sizeof( mbedtls_test_cli_key_rsa_pem );
const size_t mbedtls_test_cli_pwd_rsa_pem_len =
sizeof( mbedtls_test_cli_pwd_rsa_pem ) - 1;
const size_t mbedtls_test_cli_crt_rsa_pem_len =
sizeof( mbedtls_test_cli_crt_rsa_pem );
const size_t mbedtls_test_cli_crt_ec_der_len =
sizeof( mbedtls_test_cli_crt_ec_der );
const size_t mbedtls_test_cli_key_ec_der_len =
sizeof( mbedtls_test_cli_key_ec_der );
const size_t mbedtls_test_cli_key_rsa_der_len =
sizeof( mbedtls_test_cli_key_rsa_der );
const size_t mbedtls_test_cli_crt_rsa_der_len =
sizeof( mbedtls_test_cli_crt_rsa_der );
/*
*
* Definitions of test CRTs without specification of all parameters, choosing
* them automatically according to the config. For example, mbedtls_test_ca_crt
* is one of mbedtls_test_ca_crt_{rsa|ec}_{sha1|sha256}_{pem|der}.
*
*/
/*
* Dispatch between PEM and DER according to config
*/
#if defined(MBEDTLS_PEM_PARSE_C)
/* PEM encoded test CA certificates and keys */
#define TEST_CA_KEY_RSA TEST_CA_KEY_RSA_PEM
#define TEST_CA_PWD_RSA TEST_CA_PWD_RSA_PEM
#define TEST_CA_CRT_RSA_SHA256 TEST_CA_CRT_RSA_SHA256_PEM
#define TEST_CA_CRT_RSA_SHA1 TEST_CA_CRT_RSA_SHA1_PEM
#define TEST_CA_KEY_EC TEST_CA_KEY_EC_PEM
#define TEST_CA_PWD_EC TEST_CA_PWD_EC_PEM
#define TEST_CA_CRT_EC TEST_CA_CRT_EC_PEM
/* PEM encoded test server certificates and keys */
#define TEST_SRV_KEY_RSA TEST_SRV_KEY_RSA_PEM
#define TEST_SRV_PWD_RSA ""
#define TEST_SRV_CRT_RSA_SHA256 TEST_SRV_CRT_RSA_SHA256_PEM
#define TEST_SRV_CRT_RSA_SHA1 TEST_SRV_CRT_RSA_SHA1_PEM
#define TEST_SRV_KEY_EC TEST_SRV_KEY_EC_PEM
#define TEST_SRV_PWD_EC ""
#define TEST_SRV_CRT_EC TEST_SRV_CRT_EC_PEM
/* PEM encoded test client certificates and keys */
#define TEST_CLI_KEY_RSA TEST_CLI_KEY_RSA_PEM
#define TEST_CLI_PWD_RSA ""
#define TEST_CLI_CRT_RSA TEST_CLI_CRT_RSA_PEM
#define TEST_CLI_KEY_EC TEST_CLI_KEY_EC_PEM
#define TEST_CLI_PWD_EC ""
#define TEST_CLI_CRT_EC TEST_CLI_CRT_EC_PEM
#else /* MBEDTLS_PEM_PARSE_C */
/* DER encoded test CA certificates and keys */
#define TEST_CA_KEY_RSA TEST_CA_KEY_RSA_DER
#define TEST_CA_PWD_RSA ""
#define TEST_CA_CRT_RSA_SHA256 TEST_CA_CRT_RSA_SHA256_DER
#define TEST_CA_CRT_RSA_SHA1 TEST_CA_CRT_RSA_SHA1_DER
#define TEST_CA_KEY_EC TEST_CA_KEY_EC_DER
#define TEST_CA_PWD_EC ""
#define TEST_CA_CRT_EC TEST_CA_CRT_EC_DER
/* DER encoded test server certificates and keys */
#define TEST_SRV_KEY_RSA TEST_SRV_KEY_RSA_DER
#define TEST_SRV_PWD_RSA ""
#define TEST_SRV_CRT_RSA_SHA256 TEST_SRV_CRT_RSA_SHA256_DER
#define TEST_SRV_CRT_RSA_SHA1 TEST_SRV_CRT_RSA_SHA1_DER
#define TEST_SRV_KEY_EC TEST_SRV_KEY_EC_DER
#define TEST_SRV_PWD_EC ""
#define TEST_SRV_CRT_EC TEST_SRV_CRT_EC_DER
/* DER encoded test client certificates and keys */
#define TEST_CLI_KEY_RSA TEST_CLI_KEY_RSA_DER
#define TEST_CLI_PWD_RSA ""
#define TEST_CLI_CRT_RSA TEST_CLI_CRT_RSA_DER
#define TEST_CLI_KEY_EC TEST_CLI_KEY_EC_DER
#define TEST_CLI_PWD_EC ""
#define TEST_CLI_CRT_EC TEST_CLI_CRT_EC_DER
#endif /* MBEDTLS_PEM_PARSE_C */
const char mbedtls_test_ca_key_rsa[] = TEST_CA_KEY_RSA;
const char mbedtls_test_ca_pwd_rsa[] = TEST_CA_PWD_RSA;
const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256;
const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;
const char mbedtls_test_ca_key_ec[] = TEST_CA_KEY_EC;
const char mbedtls_test_ca_pwd_ec[] = TEST_CA_PWD_EC;
const char mbedtls_test_ca_crt_ec[] = TEST_CA_CRT_EC;
const char mbedtls_test_srv_key_rsa[] = TEST_SRV_KEY_RSA;
const char mbedtls_test_srv_pwd_rsa[] = TEST_SRV_PWD_RSA;
const char mbedtls_test_srv_crt_rsa_sha256[] = TEST_SRV_CRT_RSA_SHA256;
const char mbedtls_test_srv_crt_rsa_sha1[] = TEST_SRV_CRT_RSA_SHA1;
const char mbedtls_test_srv_key_ec[] = TEST_SRV_KEY_EC;
const char mbedtls_test_srv_pwd_ec[] = TEST_SRV_PWD_EC;
const char mbedtls_test_srv_crt_ec[] = TEST_SRV_CRT_EC;
const char mbedtls_test_cli_key_rsa[] = TEST_CLI_KEY_RSA;
const char mbedtls_test_cli_pwd_rsa[] = TEST_CLI_PWD_RSA;
const char mbedtls_test_cli_crt_rsa[] = TEST_CLI_CRT_RSA;
const char mbedtls_test_cli_key_ec[] = TEST_CLI_KEY_EC;
const char mbedtls_test_cli_pwd_ec[] = TEST_CLI_PWD_EC;
const char mbedtls_test_cli_crt_ec[] = TEST_CLI_CRT_EC;
const size_t mbedtls_test_ca_key_rsa_len =
sizeof( mbedtls_test_ca_key_rsa );
const size_t mbedtls_test_ca_pwd_rsa_len =
sizeof( mbedtls_test_ca_pwd_rsa ) - 1;
const size_t mbedtls_test_ca_crt_rsa_sha256_len =
sizeof( mbedtls_test_ca_crt_rsa_sha256 );
const size_t mbedtls_test_ca_crt_rsa_sha1_len =
sizeof( mbedtls_test_ca_crt_rsa_sha1 );
const size_t mbedtls_test_ca_key_ec_len =
sizeof( mbedtls_test_ca_key_ec );
const size_t mbedtls_test_ca_pwd_ec_len =
sizeof( mbedtls_test_ca_pwd_ec ) - 1;
const size_t mbedtls_test_ca_crt_ec_len =
sizeof( mbedtls_test_ca_crt_ec );
const size_t mbedtls_test_srv_key_rsa_len =
sizeof( mbedtls_test_srv_key_rsa );
const size_t mbedtls_test_srv_pwd_rsa_len =
sizeof( mbedtls_test_srv_pwd_rsa ) -1;
const size_t mbedtls_test_srv_crt_rsa_sha256_len =
sizeof( mbedtls_test_srv_crt_rsa_sha256 );
const size_t mbedtls_test_srv_crt_rsa_sha1_len =
sizeof( mbedtls_test_srv_crt_rsa_sha1 );
const size_t mbedtls_test_srv_key_ec_len =
sizeof( mbedtls_test_srv_key_ec );
const size_t mbedtls_test_srv_pwd_ec_len =
sizeof( mbedtls_test_srv_pwd_ec ) - 1;
const size_t mbedtls_test_srv_crt_ec_len =
sizeof( mbedtls_test_srv_crt_ec );
const size_t mbedtls_test_cli_key_rsa_len =
sizeof( mbedtls_test_cli_key_rsa );
const size_t mbedtls_test_cli_pwd_rsa_len =
sizeof( mbedtls_test_cli_pwd_rsa ) - 1;
const size_t mbedtls_test_cli_crt_rsa_len =
sizeof( mbedtls_test_cli_crt_rsa );
const size_t mbedtls_test_cli_key_ec_len =
sizeof( mbedtls_test_cli_key_ec );
const size_t mbedtls_test_cli_pwd_ec_len =
sizeof( mbedtls_test_cli_pwd_ec ) - 1;
const size_t mbedtls_test_cli_crt_ec_len =
sizeof( mbedtls_test_cli_crt_ec );
/*
* Dispatch between SHA-1 and SHA-256
*/
#if defined(MBEDTLS_SHA256_C)
#define TEST_CA_CRT_RSA TEST_CA_CRT_RSA_SHA256
#define TEST_SRV_CRT_RSA TEST_SRV_CRT_RSA_SHA256
#else
#define TEST_CA_CRT_RSA TEST_CA_CRT_RSA_SHA1
#define TEST_SRV_CRT_RSA TEST_SRV_CRT_RSA_SHA1
#endif /* MBEDTLS_SHA256_C */
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA;
const char mbedtls_test_srv_crt_rsa[] = TEST_SRV_CRT_RSA;
const size_t mbedtls_test_ca_crt_rsa_len =
sizeof( mbedtls_test_ca_crt_rsa );
const size_t mbedtls_test_srv_crt_rsa_len =
sizeof( mbedtls_test_srv_crt_rsa );
/*
* Dispatch between RSA and EC
*/
#if defined(MBEDTLS_RSA_C)
#define TEST_CA_KEY TEST_CA_KEY_RSA
#define TEST_CA_PWD TEST_CA_PWD_RSA
#define TEST_CA_CRT TEST_CA_CRT_RSA
#define TEST_SRV_KEY TEST_SRV_KEY_RSA
#define TEST_SRV_PWD TEST_SRV_PWD_RSA
#define TEST_SRV_CRT TEST_SRV_CRT_RSA
#define TEST_CLI_KEY TEST_CLI_KEY_RSA
#define TEST_CLI_PWD TEST_CLI_PWD_RSA
#define TEST_CLI_CRT TEST_CLI_CRT_RSA
#else /* no RSA, so assume ECDSA */
#define TEST_CA_KEY TEST_CA_KEY_EC
#define TEST_CA_PWD TEST_CA_PWD_EC
#define TEST_CA_CRT TEST_CA_CRT_EC
#define TEST_SRV_KEY TEST_SRV_KEY_EC
#define TEST_SRV_PWD TEST_SRV_PWD_EC
#define TEST_SRV_CRT TEST_SRV_CRT_EC
#define TEST_CLI_KEY TEST_CLI_KEY_EC
#define TEST_CLI_PWD TEST_CLI_PWD_EC
#define TEST_CLI_CRT TEST_CLI_CRT_EC
#endif /* MBEDTLS_RSA_C */
/* API stability forces us to declare
* mbedtls_test_{ca|srv|cli}_{key|pwd|crt}
* as pointers. */
static const char test_ca_key[] = TEST_CA_KEY;
static const char test_ca_pwd[] = TEST_CA_PWD;
static const char test_ca_crt[] = TEST_CA_CRT;
static const char test_srv_key[] = TEST_SRV_KEY;
static const char test_srv_pwd[] = TEST_SRV_PWD;
static const char test_srv_crt[] = TEST_SRV_CRT;
static const char test_cli_key[] = TEST_CLI_KEY;
static const char test_cli_pwd[] = TEST_CLI_PWD;
static const char test_cli_crt[] = TEST_CLI_CRT;
const char *mbedtls_test_ca_key = test_ca_key;
const char *mbedtls_test_ca_pwd = test_ca_pwd;
const char *mbedtls_test_ca_crt = test_ca_crt;
const char *mbedtls_test_srv_key = test_srv_key;
const char *mbedtls_test_srv_pwd = test_srv_pwd;
const char *mbedtls_test_srv_crt = test_srv_crt;
const char *mbedtls_test_cli_key = test_cli_key;
const char *mbedtls_test_cli_pwd = test_cli_pwd;
const char *mbedtls_test_cli_crt = test_cli_crt;
const size_t mbedtls_test_ca_key_len =
sizeof( test_ca_key );
const size_t mbedtls_test_ca_pwd_len =
sizeof( test_ca_pwd ) - 1;
const size_t mbedtls_test_ca_crt_len =
sizeof( test_ca_crt );
const size_t mbedtls_test_srv_key_len =
sizeof( test_srv_key );
const size_t mbedtls_test_srv_pwd_len =
sizeof( test_srv_pwd ) - 1;
const size_t mbedtls_test_srv_crt_len =
sizeof( test_srv_crt );
const size_t mbedtls_test_cli_key_len =
sizeof( test_cli_key );
const size_t mbedtls_test_cli_pwd_len =
sizeof( test_cli_pwd ) - 1;
const size_t mbedtls_test_cli_crt_len =
sizeof( test_cli_crt );
/*
*
* Lists of certificates
*
*/
/* List of CAs in PEM or DER, depending on config */
const char * mbedtls_test_cas[] = {
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA1_C)
mbedtls_test_ca_crt_rsa_sha1,
#endif
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C)
mbedtls_test_ca_crt_rsa_sha256,
#endif
#if defined(MBEDTLS_ECDSA_C)
mbedtls_test_ca_crt_ec,
#endif
NULL
};
const size_t mbedtls_test_cas_len[] = {
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA1_C)
sizeof( mbedtls_test_ca_crt_rsa_sha1 ),
#endif
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C)
sizeof( mbedtls_test_ca_crt_rsa_sha256 ),
#endif
#if defined(MBEDTLS_ECDSA_C)
sizeof( mbedtls_test_ca_crt_ec ),
#endif
0
};
/* List of all available CA certificates in DER format */
const unsigned char * mbedtls_test_cas_der[] = {
#if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_SHA256_C)
mbedtls_test_ca_crt_rsa_sha256_der,
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA1_C)
mbedtls_test_ca_crt_rsa_sha1_der,
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
mbedtls_test_ca_crt_ec_der,
#endif /* MBEDTLS_ECDSA_C */
NULL
};
const size_t mbedtls_test_cas_der_len[] = {
#if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_SHA256_C)
sizeof( mbedtls_test_ca_crt_rsa_sha256_der ),
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA1_C)
sizeof( mbedtls_test_ca_crt_rsa_sha1_der ),
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
sizeof( mbedtls_test_ca_crt_ec_der ),
#endif /* MBEDTLS_ECDSA_C */
0
};
/* Concatenation of all available CA certificates in PEM format */
#if defined(MBEDTLS_PEM_PARSE_C)
const char mbedtls_test_cas_pem[] =
#if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_SHA256_C)
TEST_CA_CRT_RSA_SHA256_PEM
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA1_C)
TEST_CA_CRT_RSA_SHA1_PEM
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
TEST_CA_CRT_EC_PEM
#endif /* MBEDTLS_ECDSA_C */
"";
const size_t mbedtls_test_cas_pem_len = sizeof( mbedtls_test_cas_pem );
#endif /* MBEDTLS_PEM_PARSE_C */
#endif /* MBEDTLS_CERTS_C */
|
900049.c | /**
*!
* \file mcu_mm32spin2x_it.c
* \version v0.0.1
* \date 2020/03/25
* \author Bean([email protected])
*******************************************************************************
* @attention
*
* Copyright (c) 2020 Bean
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SUARTL 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.
*******************************************************************************
*/
/*Includes ----------------------------------------------*/
#include "b_config.h"
#include "hal/inc/b_hal_it.h"
#if (MCU_PLATFORM == 3001)
void bMcuIntEnable()
{
;
}
void bMcuIntDisable()
{
;
}
#endif
/************************ Copyright (c) 2020 Bean *****END OF FILE****/
|
273609.c | #include <sys/types.h> /* for 'open' */
#include <sys/stat.h> /* for 'open' */
#include <fcntl.h> /* for 'open' */
#include <stdlib.h> /* for 'malloc' */
#include <stdio.h> /* for 'printf' */
#include <unistd.h> /* for 'read' */
#include <errno.h> /* for 'sterror' */
#include <sys/time.h> /* for 'gettimeofday' */
#include "uthash.h"
#undef uthash_noexpand_fyi
#define uthash_noexpand_fyi(t) die()
#define UNALIGNED_KEYS 0
void die() {
fprintf(stderr,"expansion inhibited\n");
exit(-1);
}
/* Windows doesn't have gettimeofday. While Cygwin and some
* versions of MinGW supply one, it is very coarse. This substitute
* gives much more accurate elapsed times under Windows. */
#if (( defined __CYGWIN__ ) || ( defined __MINGW32__ ))
#include <windows.h>
void win_gettimeofday(struct timeval* p, void* tz /* IGNORED */) {
LARGE_INTEGER q;
static long long freq;
static long long cyg_timer;
QueryPerformanceFrequency(&q);
freq = q.QuadPart;
QueryPerformanceCounter(&q);
cyg_timer = q.QuadPart;
p->tv_sec = (long)(cyg_timer / freq);
p->tv_usec = (long)(((cyg_timer % freq) * 1000000) / freq);
}
#define gettimeofday win_gettimeofday
#define MODE (O_RDONLY|O_BINARY)
#else
#define MODE (O_RDONLY)
#endif
#ifndef timersub
#define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
#endif
typedef struct stat_key {
char *key;
unsigned len;
UT_hash_handle hh, hh2;
} stat_key;
#define CHAIN_0 0
#define CHAIN_5 1
#define CHAIN_10 2
#define CHAIN_20 3
#define CHAIN_100 4
#define CHAIN_MAX 5
void hash_chain_len_histogram(UT_hash_table *tbl) {
unsigned i, bkt_hist[CHAIN_MAX+1];
double pct = 100.0/tbl->num_buckets;
memset(bkt_hist,0,sizeof(bkt_hist));
for(i=0; i < tbl->num_buckets; i++) {
unsigned count = tbl->buckets[i].count;
if (count == 0) bkt_hist[CHAIN_0]++;
else if (count < 5) bkt_hist[CHAIN_5]++;
else if (count < 10) bkt_hist[CHAIN_10]++;
else if (count < 20) bkt_hist[CHAIN_20]++;
else if (count < 100) bkt_hist[CHAIN_100]++;
else bkt_hist[CHAIN_MAX]++;
}
fprintf(stderr, "Buckets with 0 items: %.1f%%\n", bkt_hist[CHAIN_0 ]*pct);
fprintf(stderr, "Buckets with < 5 items: %.1f%%\n", bkt_hist[CHAIN_5 ]*pct);
fprintf(stderr, "Buckets with < 10 items: %.1f%%\n", bkt_hist[CHAIN_10]*pct);
fprintf(stderr, "Buckets with < 20 items: %.1f%%\n", bkt_hist[CHAIN_20]*pct);
fprintf(stderr, "Buckets with < 100 items: %.1f%%\n", bkt_hist[CHAIN_100]*pct);
fprintf(stderr, "Buckets with > 100 items: %.1f%%\n", bkt_hist[CHAIN_MAX]*pct);
}
int main(int argc, char *argv[]) {
int dups=0, rc, fd, done=0, err=0, want, i=0, padding=0, v=1, percent=100;
unsigned keylen, max_keylen=0, verbose=0;
const char *filename = "/dev/stdin";
char *dst;
stat_key *keyt, *keytmp, *keys=NULL, *keys2=NULL;
struct timeval start_tm, end_tm, elapsed_tm, elapsed_tm2, elapsed_tm3;
if ((argc >= 3) && !strcmp(argv[1],"-p")) {percent = atoi(argv[2]); v = 3;}
if ((argc >= v) && !strcmp(argv[v],"-v")) {verbose=1; v++;}
if (argc >= v) filename=argv[v];
fd=open(filename,MODE);
if ( fd == -1 ) {
fprintf(stderr,"open failed %s: %s\n", filename, strerror(errno));
return -1;
}
for(i=0; !done; i++) {
want = sizeof(int);
dst = (char*)&keylen;
readmore1:
rc = read(fd,dst,want);
if (rc != want) {
if (rc == 0) done=1;
else if (rc == -1) {
fprintf(stderr,"read failed: %s\n", strerror(errno));
err=1;
}
else if (rc > 0) { want -= rc; dst += rc; goto readmore1; }
}
if (done || err) break;
if (keylen > max_keylen) max_keylen=keylen;
if ( (keyt = (stat_key*)malloc(sizeof(stat_key))) == NULL) {
fprintf(stderr,"out of memory\n");
exit(-1);
}
/* read key */
#ifdef UNALIGNED_KEYS
padding = i%8;
#endif
if ( (keyt->key = (char*)malloc(padding+keylen)) == NULL) {
fprintf(stderr,"out of memory\n");
exit(-1);
}
keyt->key += padding; /* forcibly alter the alignment of key */
keyt->len = keylen;
want = keylen;
dst = keyt->key;
readmore2:
rc = read(fd,dst,want);
if (rc != want) {
if (rc == -1) {
fprintf(stderr,"read failed: %s\n", strerror(errno));
err=1;
} else if (rc == 0) {
fprintf(stderr,"incomplete file\n");
err=1;
} else if (rc >= 0) { want -= rc; dst += rc; goto readmore2; }
}
if (err) break;
/* if percent was set to something less than 100%, skip some keys*/
if (((rand()*1.0) / RAND_MAX) > ((percent*1.0)/100)) {
free(keyt->key-padding);
free(keyt);
continue;
}
/* eliminate dups */
HASH_FIND(hh,keys,keyt->key,keylen,keytmp);
if (keytmp) {
dups++;
free(keyt->key - padding);
free(keyt);
} else {
HASH_ADD_KEYPTR(hh,keys,keyt->key,keylen,keyt);
}
}
if (verbose) {
unsigned key_count = HASH_COUNT(keys);
fprintf(stderr,"max key length: %u\n", max_keylen);
fprintf(stderr,"number unique keys: %u\n", key_count);
fprintf(stderr,"keystats memory: %u\n",
(unsigned)((sizeof(stat_key)+max_keylen)*key_count));
hash_chain_len_histogram(keys->hh.tbl);
}
/* add all keys to a new hash, so we can measure add time w/o malloc */
gettimeofday(&start_tm,NULL);
for(keyt = keys; keyt != NULL; keyt=(stat_key*)keyt->hh.next) {
HASH_ADD_KEYPTR(hh2,keys2,keyt->key,keyt->len,keyt);
}
gettimeofday(&end_tm,NULL);
timersub(&end_tm, &start_tm, &elapsed_tm);
/* now look up all keys in the new hash, again measuring elapsed time */
gettimeofday(&start_tm,NULL);
for(keyt = keys; keyt != NULL; keyt=(stat_key*)keyt->hh.next) {
HASH_FIND(hh2,keys2,keyt->key,keyt->len,keytmp);
if (!keytmp) fprintf(stderr,"internal error, key not found\n");
}
gettimeofday(&end_tm,NULL);
timersub(&end_tm, &start_tm, &elapsed_tm2);
/* now delete all items in the new hash, measuring elapsed time */
gettimeofday(&start_tm,NULL);
while (keys2) {
keytmp = keys2;
HASH_DELETE(hh2,keys2,keytmp);
}
gettimeofday(&end_tm,NULL);
timersub(&end_tm, &start_tm, &elapsed_tm3);
if (!err) {
printf("%.3f,%d,%d,%d,%s,%ld,%ld,%ld\n",
1-(1.0*keys->hh.tbl->nonideal_items/keys->hh.tbl->num_items),
keys->hh.tbl->num_items,
keys->hh.tbl->num_buckets,
dups,
(keys->hh.tbl->noexpand ? "nx" : "ok"),
(elapsed_tm.tv_sec * 1000000) + elapsed_tm.tv_usec,
(elapsed_tm2.tv_sec * 1000000) + elapsed_tm2.tv_usec,
(elapsed_tm3.tv_sec * 1000000) + elapsed_tm3.tv_usec );
}
return 0;
}
|
612463.c | /****************************************************************************
* net/local/local_sendpacket.c
*
* Copyright (C) 2015 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_LOCAL)
#include <sys/types.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <debug.h>
#include "local/local.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define LOCAL_PREAMBLE_SIZE 8
/****************************************************************************
* Private Data
****************************************************************************/
static const uint8_t g_preamble[LOCAL_PREAMBLE_SIZE] =
{
LOCAL_SYNC_BYTE, LOCAL_SYNC_BYTE, LOCAL_SYNC_BYTE, LOCAL_SYNC_BYTE,
LOCAL_SYNC_BYTE, LOCAL_SYNC_BYTE, LOCAL_SYNC_BYTE, LOCAL_END_BYTE
};
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: local_fifo_write
*
* Description:
* Write a data on the write-only FIFO.
*
* Parameters:
* fd File descriptor of write-only FIFO.
* buf Data to send
* len Length of data to send
*
* Return:
* Zero is returned on success; a negated errno value is returned on any
* failure.
*
****************************************************************************/
static int local_fifo_write(int fd, FAR const uint8_t *buf, size_t len)
{
ssize_t nwritten;
while (len > 0)
{
nwritten = write(fd, buf, len);
if (nwritten < 0)
{
int errcode = get_errno();
DEBUGASSERT(errcode > 0);
if (errcode != EINTR)
{
nerr("ERROR: Write failed: %d\n", errcode);
return -errcode;
}
ninfo("Ignoring signal\n");
}
else
{
DEBUGASSERT(nwritten > 0 && nwritten <= len);
len -= nwritten;
buf += nwritten;
}
}
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: local_send_packet
*
* Description:
* Send a packet on the write-only FIFO.
*
* Parameters:
* fd File descriptor of write-only FIFO.
* buf Data to send
* len Length of data to send
*
* Return:
* Zero is returned on success; a negated errno value is returned on any
* failure.
*
****************************************************************************/
int local_send_packet(int fd, FAR const uint8_t *buf, size_t len)
{
uint16_t len16;
int ret;
/* Send the packet preamble */
ret = local_fifo_write(fd, g_preamble, LOCAL_PREAMBLE_SIZE);
if (ret == OK)
{
/* Send the packet length */
len16 = len;
ret = local_fifo_write(fd, (FAR const uint8_t *)&len16, sizeof(uint16_t));
if (ret == OK)
{
/* Send the packet data */
ret = local_fifo_write(fd, buf, len);
}
}
return ret;
}
#endif /* CONFIG_NET && CONFIG_NET_LOCAL */
|
926487.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "motivate.h" // NOLINT
int main(){
srand((unsigned) time(0));
FILE* quotes=fopen(quotes_path,"rb"); // NOLINT
FILE* map=fopen(quotes_map_path,"rb"); // NOLINT
if(quotes==NULL || map==NULL){
printf("Error! Files are missing. Consider reinstalling.");
return -1;
}
fseek(map,0,SEEK_END);
int number_of_quotes=ftell(map)/(2*sizeof(unsigned int));
int random=rand()%number_of_quotes;
unsigned int linePosition=0;
fseek(map,2*random*sizeof(linePosition),SEEK_SET);
fread(&linePosition, sizeof(linePosition), 1, map);
char quote[1000];
fseek(quotes, linePosition, SEEK_CUR);
fgets(quote,1000,quotes);
printf("%s",quote);
fgets(quote,1000,quotes);
printf("%s",quote);
return 0;
}
|
635325.c | #include "sbgEComBinaryLogImu.h"
//----------------------------------------------------------------------//
//- Getter / helpers -//
//----------------------------------------------------------------------//
/*!
* Return from an IMU Short log, the X, Y or Z delta angle value in rad.s^-1
* \param[in] pImuShort Input IMU short message instance.
* \param[in] idx The component to return from 0 to 2.
* \return The delta angle value converted in rad.s^-1.
*/
float sbgLogImuShortGetDeltaAngle(const SbgLogImuShort *pImuShort, size_t idx)
{
assert(pImuShort);
assert(idx < 3);
return pImuShort->deltaAngle[idx] / 67108864.0f;
}
/*!
* Return from an IMU Short log, the X, Y or Z delta velocity value in m.s^-2
* \param[in] pImuShort Input IMU short message instance.
* \param[in] idx The component to return from 0 to 2.
* \return The delta velocity value converted in m.s^-2.
*/
float sbgLogImuShortGetDeltaVelocity(const SbgLogImuShort *pImuShort, size_t idx)
{
assert(pImuShort);
assert(idx < 3);
return pImuShort->deltaVelocity[idx] / 1048576.0f;
}
/*!
* Return from an IMU Short log, the temperature in °C
* \param[in] pImuShort Input IMU short message instance.
* \return The converted temperature in °C
*/
float sbgLogImuShortGetTemperature(const SbgLogImuShort *pImuShort)
{
assert(pImuShort);
return pImuShort->temperature / 256.0f;
}
//----------------------------------------------------------------------//
//- Operations -//
//----------------------------------------------------------------------//
/*!
* Parse data for the SBG_ECOM_LOG_IMU_DATA message and fill the corresponding structure.
* \param[in] pInputStream Input stream buffer to read the payload from.
* \param[out] pOutputData Pointer on the output structure that stores parsed data.
* \return SBG_NO_ERROR if the payload has been parsed.
*/
SbgErrorCode sbgEComBinaryLogParseImuData(SbgStreamBuffer *pInputStream, SbgLogImuData *pOutputData)
{
assert(pInputStream);
assert(pOutputData);
//
// Read the frame payload
//
pOutputData->timeStamp = sbgStreamBufferReadUint32LE(pInputStream);
pOutputData->status = sbgStreamBufferReadUint16LE(pInputStream);
pOutputData->accelerometers[0] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->accelerometers[1] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->accelerometers[2] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->gyroscopes[0] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->gyroscopes[1] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->gyroscopes[2] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->temperature = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaVelocity[0] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaVelocity[1] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaVelocity[2] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaAngle[0] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaAngle[1] = sbgStreamBufferReadFloatLE(pInputStream);
pOutputData->deltaAngle[2] = sbgStreamBufferReadFloatLE(pInputStream);
//
// Return if any error has occurred while parsing the frame
//
return sbgStreamBufferGetLastError(pInputStream);
}
/*!
* Write data for the SBG_ECOM_LOG_IMU_DATA message to the output stream buffer from the provided structure.
* \param[out] pOutputStream Output stream buffer to write the payload to.
* \param[in] pInputData Pointer on the input structure that stores data to write.
* \return SBG_NO_ERROR if the message has been generated in the provided buffer.
*/
SbgErrorCode sbgEComBinaryLogWriteImuData(SbgStreamBuffer *pOutputStream, const SbgLogImuData *pInputData)
{
assert(pOutputStream);
assert(pInputData);
//
// Write the frame payload
//
sbgStreamBufferWriteUint32LE(pOutputStream, pInputData->timeStamp);
sbgStreamBufferWriteUint16LE(pOutputStream, pInputData->status);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->accelerometers[0]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->accelerometers[1]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->accelerometers[2]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->gyroscopes[0]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->gyroscopes[1]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->gyroscopes[2]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->temperature);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaVelocity[0]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaVelocity[1]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaVelocity[2]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaAngle[0]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaAngle[1]);
sbgStreamBufferWriteFloatLE(pOutputStream, pInputData->deltaAngle[2]);
//
// Return if any error has occurred while writing the frame
//
return sbgStreamBufferGetLastError(pOutputStream);
}
/*!
* Parse data for the SBG_ECOM_LOG_IMU_SHORT message and fill the corresponding structure.
* \param[in] pInputStream Input stream buffer to read the payload from.
* \param[out] pOutputData Pointer on the output structure that stores parsed data.
* \return SBG_NO_ERROR if the payload has been parsed.
*/
SbgErrorCode sbgEComBinaryLogParseImuShort(SbgStreamBuffer *pInputStream, SbgLogImuShort *pOutputData)
{
assert(pInputStream);
assert(pOutputData);
//
// Read the frame payload
//
pOutputData->timeStamp = sbgStreamBufferReadUint32LE(pInputStream);
pOutputData->status = sbgStreamBufferReadUint16LE(pInputStream);
pOutputData->deltaVelocity[0] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->deltaVelocity[1] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->deltaVelocity[2] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->deltaAngle[0] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->deltaAngle[1] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->deltaAngle[2] = sbgStreamBufferReadInt32LE(pInputStream);
pOutputData->temperature = sbgStreamBufferReadInt16LE(pInputStream);
//
// Return if any error has occurred while parsing the frame
//
return sbgStreamBufferGetLastError(pInputStream);
}
/*!
* Write data for the SBG_ECOM_LOG_IMU_SHORT message to the output stream buffer from the provided structure.
* \param[out] pOutputStream Output stream buffer to write the payload to.
* \param[in] pInputData Pointer on the input structure that stores data to write.
* \return SBG_NO_ERROR if the message has been generated in the provided buffer.
*/
SbgErrorCode sbgEComBinaryLogWriteImuShort(SbgStreamBuffer *pOutputStream, const SbgLogImuShort *pInputData)
{
assert(pOutputStream);
assert(pInputData);
//
// Write the frame payload
//
sbgStreamBufferWriteUint32LE(pOutputStream, pInputData->timeStamp);
sbgStreamBufferWriteUint16LE(pOutputStream, pInputData->status);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaVelocity[0]);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaVelocity[1]);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaVelocity[2]);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaAngle[0]);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaAngle[1]);
sbgStreamBufferWriteInt32LE(pOutputStream, pInputData->deltaAngle[2]);
sbgStreamBufferWriteInt16LE(pOutputStream, pInputData->temperature);
//
// Return if any error has occurred while writing the frame
//
return sbgStreamBufferGetLastError(pOutputStream);
}
/*!
* Parse data for the SBG_ECOM_LOG_FAST_IMU_DATA message and fill the corresponding structure.
* \param[in] pInputStream Input stream buffer to read the payload from.
* \param[out] pOutputData Pointer on the output structure that stores parsed data.
* \return SBG_NO_ERROR if the payload has been parsed.
*/
SbgErrorCode sbgEComBinaryLogParseFastImuData(SbgStreamBuffer *pInputStream, SbgLogFastImuData *pOutputData)
{
assert(pInputStream);
assert(pOutputData);
//
// Read the frame payload
//
pOutputData->timeStamp = sbgStreamBufferReadUint32LE(pInputStream);
pOutputData->status = sbgStreamBufferReadUint16LE(pInputStream);
pOutputData->accelerometers[0] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.01f;
pOutputData->accelerometers[1] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.01f;
pOutputData->accelerometers[2] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.01f;
pOutputData->gyroscopes[0] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.001f;
pOutputData->gyroscopes[1] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.001f;
pOutputData->gyroscopes[2] = (float)sbgStreamBufferReadInt16LE(pInputStream) * 0.001f;
//
// Return if any error has occurred while parsing the frame
//
return sbgStreamBufferGetLastError(pInputStream);
}
/*!
* Write data for the SBG_ECOM_LOG_FAST_IMU_DATA message to the output stream buffer from the provided structure.
* \param[out] pOutputStream Output stream buffer to write the payload to.
* \param[in] pInputData Pointer on the input structure that stores data to write.
* \return SBG_NO_ERROR if the message has been generated in the provided buffer.
*/
SbgErrorCode sbgEComBinaryLogWriteFastImuData(SbgStreamBuffer *pOutputStream, const SbgLogFastImuData *pInputData)
{
assert(pOutputStream);
assert(pInputData);
//
// Write the frame payload
//
sbgStreamBufferWriteUint32LE(pOutputStream, pInputData->timeStamp);
sbgStreamBufferWriteUint16LE(pOutputStream, pInputData->status);
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->accelerometers[0] * 100.0f));
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->accelerometers[1] * 100.0f));
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->accelerometers[2] * 100.0f));
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->gyroscopes[0] * 1000.0f));
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->gyroscopes[1] * 1000.0f));
sbgStreamBufferWriteInt16LE(pOutputStream, (int16_t)(pInputData->gyroscopes[2] * 1000.0f));
//
// Return if any error has occurred while writing the frame
//
return sbgStreamBufferGetLastError(pOutputStream);
}
|
475177.c | #include <stdio.h>
#define kMaxDVDs 4
#define kMaxTitleLength 256
void PrintDVDTitle(int dvdNum, char title[][kMaxTitleLength]);
int main(int argc, const char * argv[]) {
char title[kMaxDVDs][kMaxTitleLength];
short dvdNum;
printf("The title array takes up %ld bytes of memory.\n\n", sizeof(title));
for(dvdNum = 0; dvdNum < kMaxDVDs; dvdNum++) {
printf("Title of DVD #%d: ", dvdNum + 1);
fgets(title[dvdNum], kMaxTitleLength, stdin);
}
printf("----\n");
for(dvdNum = 0; dvdNum < kMaxDVDs; dvdNum++) {
PrintDVDTitle(dvdNum, title);
}
return 0;
}
void PrintDVDTitle(int dvdNum, char title[][kMaxTitleLength]) {
printf("Title of DVD #%d: %s\n", dvdNum + 1, title[dvdNum]);
}
|
452631.c | // global.c - Secure memory manager globals.
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
#include <intrin.h>
#include "config.h"
#include "hashing.h"
#include "random.h"
static void* _0 = 0; // Pointer to the root of all things.
/*
static bool random_global_initialized__ = false; // Global random state initialization flag.
static random_state random_global_state__ = { { 0 }, 0 }; // Global random state.
// Initializes the global random number generator.
void random_global_initialize(uint64_t seed)
{
if (random_global_initialized__) return;
if (seed == 0) seed = random_generate_seed();
random_initialize(&random_global_state__, seed);
}
// Gets the next random uint64_t value from the global random number generator.
uint64_t random_next_integer(void)
{
return random_integer(&random_global_state__);
}
// Gets the next random byte value from the global random number generator.
uint8_t random_next_byte(void)
{
return random_byte(&random_global_state__);
}
*/
|
497962.c | /*
* tkScale.c --
*
* This module implements a scale widgets for the Tk toolkit. A scale
* displays a slider that can be adjusted to change a value; it also
* displays numeric labels and a textual label, if desired.
*
* The modifications to use floating-point values are based on an
* implementation by Paul Mackerras. The -variable option is due to
* Henning Schulzrinne. All of these are used with permission.
*
* Copyright (c) 1990-1994 The Regents of the University of California.
* Copyright (c) 1994-1997 Sun Microsystems, Inc.
* Copyright (c) 1998-2000 by Scriptics Corporation.
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "default.h"
#include "tkInt.h"
#include "tkScale.h"
#if defined(_WIN32)
#define snprintf _snprintf
#endif
/*
* The following table defines the legal values for the -orient option. It is
* used together with the "enum orient" declaration in tkScale.h.
*/
static const char *const orientStrings[] = {
"horizontal", "vertical", NULL
};
/*
* The following table defines the legal values for the -state option. It is
* used together with the "enum state" declaration in tkScale.h.
*/
static const char *const stateStrings[] = {
"active", "disabled", "normal", NULL
};
static const Tk_OptionSpec optionSpecs[] = {
{TK_OPTION_BORDER, "-activebackground", "activeBackground", "Foreground",
DEF_SCALE_ACTIVE_BG_COLOR, -1, Tk_Offset(TkScale, activeBorder),
0, DEF_SCALE_ACTIVE_BG_MONO, 0},
{TK_OPTION_BORDER, "-background", "background", "Background",
DEF_SCALE_BG_COLOR, -1, Tk_Offset(TkScale, bgBorder),
0, DEF_SCALE_BG_MONO, 0},
{TK_OPTION_DOUBLE, "-bigincrement", "bigIncrement", "BigIncrement",
DEF_SCALE_BIG_INCREMENT, -1, Tk_Offset(TkScale, bigIncrement),
0, 0, 0},
{TK_OPTION_SYNONYM, "-bd", NULL, NULL,
NULL, 0, -1, 0, "-borderwidth", 0},
{TK_OPTION_SYNONYM, "-bg", NULL, NULL,
NULL, 0, -1, 0, "-background", 0},
{TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
DEF_SCALE_BORDER_WIDTH, -1, Tk_Offset(TkScale, borderWidth),
0, 0, 0},
{TK_OPTION_STRING, "-command", "command", "Command",
DEF_SCALE_COMMAND, -1, Tk_Offset(TkScale, command),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor",
DEF_SCALE_CURSOR, -1, Tk_Offset(TkScale, cursor),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_INT, "-digits", "digits", "Digits",
DEF_SCALE_DIGITS, -1, Tk_Offset(TkScale, digits),
0, 0, 0},
{TK_OPTION_SYNONYM, "-fg", "foreground", NULL,
NULL, 0, -1, 0, "-foreground", 0},
{TK_OPTION_FONT, "-font", "font", "Font",
DEF_SCALE_FONT, -1, Tk_Offset(TkScale, tkfont), 0, 0, 0},
{TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
DEF_SCALE_FG_COLOR, -1, Tk_Offset(TkScale, textColorPtr), 0,
(ClientData) DEF_SCALE_FG_MONO, 0},
{TK_OPTION_DOUBLE, "-from", "from", "From", DEF_SCALE_FROM, -1,
Tk_Offset(TkScale, fromValue), 0, 0, 0},
{TK_OPTION_BORDER, "-highlightbackground", "highlightBackground",
"HighlightBackground", DEF_SCALE_HIGHLIGHT_BG_COLOR,
-1, Tk_Offset(TkScale, highlightBorder),
0, DEF_SCALE_HIGHLIGHT_BG_MONO, 0},
{TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
DEF_SCALE_HIGHLIGHT, -1, Tk_Offset(TkScale, highlightColorPtr),
0, 0, 0},
{TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness",
"HighlightThickness", DEF_SCALE_HIGHLIGHT_WIDTH, -1,
Tk_Offset(TkScale, highlightWidth), 0, 0, 0},
{TK_OPTION_STRING, "-label", "label", "Label",
DEF_SCALE_LABEL, -1, Tk_Offset(TkScale, label),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_PIXELS, "-length", "length", "Length",
DEF_SCALE_LENGTH, -1, Tk_Offset(TkScale, length), 0, 0, 0},
{TK_OPTION_STRING_TABLE, "-orient", "orient", "Orient",
DEF_SCALE_ORIENT, -1, Tk_Offset(TkScale, orient),
0, orientStrings, 0},
{TK_OPTION_RELIEF, "-relief", "relief", "Relief",
DEF_SCALE_RELIEF, -1, Tk_Offset(TkScale, relief), 0, 0, 0},
{TK_OPTION_INT, "-repeatdelay", "repeatDelay", "RepeatDelay",
DEF_SCALE_REPEAT_DELAY, -1, Tk_Offset(TkScale, repeatDelay),
0, 0, 0},
{TK_OPTION_INT, "-repeatinterval", "repeatInterval", "RepeatInterval",
DEF_SCALE_REPEAT_INTERVAL, -1, Tk_Offset(TkScale, repeatInterval),
0, 0, 0},
{TK_OPTION_DOUBLE, "-resolution", "resolution", "Resolution",
DEF_SCALE_RESOLUTION, -1, Tk_Offset(TkScale, resolution),
0, 0, 0},
{TK_OPTION_BOOLEAN, "-showvalue", "showValue", "ShowValue",
DEF_SCALE_SHOW_VALUE, -1, Tk_Offset(TkScale, showValue),
0, 0, 0},
{TK_OPTION_PIXELS, "-sliderlength", "sliderLength", "SliderLength",
DEF_SCALE_SLIDER_LENGTH, -1, Tk_Offset(TkScale, sliderLength),
0, 0, 0},
{TK_OPTION_RELIEF, "-sliderrelief", "sliderRelief", "SliderRelief",
DEF_SCALE_SLIDER_RELIEF, -1, Tk_Offset(TkScale, sliderRelief),
0, 0, 0},
{TK_OPTION_STRING_TABLE, "-state", "state", "State",
DEF_SCALE_STATE, -1, Tk_Offset(TkScale, state),
0, stateStrings, 0},
{TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
DEF_SCALE_TAKE_FOCUS, Tk_Offset(TkScale, takeFocusPtr), -1,
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_DOUBLE, "-tickinterval", "tickInterval", "TickInterval",
DEF_SCALE_TICK_INTERVAL, -1, Tk_Offset(TkScale, tickInterval),
0, 0, 0},
{TK_OPTION_DOUBLE, "-to", "to", "To",
DEF_SCALE_TO, -1, Tk_Offset(TkScale, toValue), 0, 0, 0},
{TK_OPTION_COLOR, "-troughcolor", "troughColor", "Background",
DEF_SCALE_TROUGH_COLOR, -1, Tk_Offset(TkScale, troughColorPtr),
0, DEF_SCALE_TROUGH_MONO, 0},
{TK_OPTION_STRING, "-variable", "variable", "Variable",
DEF_SCALE_VARIABLE, Tk_Offset(TkScale, varNamePtr), -1,
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_PIXELS, "-width", "width", "Width",
DEF_SCALE_WIDTH, -1, Tk_Offset(TkScale, width), 0, 0, 0},
{TK_OPTION_END, NULL, NULL, NULL, NULL, 0, -1, 0, 0, 0}
};
/*
* The following tables define the scale widget commands and map the indexes
* into the string tables into a single enumerated type used to dispatch the
* scale widget command.
*/
static const char *const commandNames[] = {
"cget", "configure", "coords", "get", "identify", "set", NULL
};
enum command {
COMMAND_CGET, COMMAND_CONFIGURE, COMMAND_COORDS, COMMAND_GET,
COMMAND_IDENTIFY, COMMAND_SET
};
/*
* Forward declarations for procedures defined later in this file:
*/
static void ComputeFormat(TkScale *scalePtr, int forTicks);
static void ComputeScaleGeometry(TkScale *scalePtr);
static int ConfigureScale(Tcl_Interp *interp, TkScale *scalePtr,
int objc, Tcl_Obj *const objv[]);
static void DestroyScale(char *memPtr);
static double MaxTickRoundingError(TkScale *scalePtr,
double tickResolution);
static void ScaleCmdDeletedProc(ClientData clientData);
static void ScaleEventProc(ClientData clientData,
XEvent *eventPtr);
static char * ScaleVarProc(ClientData clientData,
Tcl_Interp *interp, const char *name1,
const char *name2, int flags);
static int ScaleWidgetObjCmd(ClientData clientData,
Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]);
static void ScaleWorldChanged(ClientData instanceData);
static void ScaleSetVariable(TkScale *scalePtr);
/*
* The structure below defines scale class behavior by means of procedures
* that can be invoked from generic window code.
*/
static const Tk_ClassProcs scaleClass = {
sizeof(Tk_ClassProcs), /* size */
ScaleWorldChanged, /* worldChangedProc */
NULL, /* createProc */
NULL /* modalProc */
};
/*
*--------------------------------------------------------------
*
* ScaleDigit, ScaleMax, ScaleMin, ScaleRound --
*
* Simple math helper functions, designed to be automatically inlined by
* the compiler most of the time.
*
*--------------------------------------------------------------
*/
static inline int
ScaleDigit(
double value)
{
return (int) floor(log10(fabs(value)));
}
static inline double
ScaleMax(
double a,
double b)
{
return (a > b) ? a : b;
}
static inline double
ScaleMin(
double a,
double b)
{
return (a < b) ? a : b;
}
static inline int
ScaleRound(
double value)
{
return (int) floor(value + 0.5);
}
/*
*--------------------------------------------------------------
*
* Tk_ScaleObjCmd --
*
* This procedure is invoked to process the "scale" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
int
Tk_ScaleObjCmd(
ClientData clientData, /* NULL. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument values. */
{
TkScale *scalePtr;
Tk_OptionTable optionTable;
Tk_Window tkwin;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "pathName ?-option value ...?");
return TCL_ERROR;
}
tkwin = Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp),
Tcl_GetString(objv[1]), NULL);
if (tkwin == NULL) {
return TCL_ERROR;
}
/*
* Create the option table for this widget class. If it has already been
* created, the cached pointer will be returned.
*/
optionTable = Tk_CreateOptionTable(interp, optionSpecs);
Tk_SetClass(tkwin, "Scale");
scalePtr = TkpCreateScale(tkwin);
/*
* Initialize fields that won't be initialized by ConfigureScale, or which
* ConfigureScale expects to have reasonable values (e.g. resource
* pointers).
*/
scalePtr->tkwin = tkwin;
scalePtr->display = Tk_Display(tkwin);
scalePtr->interp = interp;
scalePtr->widgetCmd = Tcl_CreateObjCommand(interp,
Tk_PathName(scalePtr->tkwin), ScaleWidgetObjCmd,
scalePtr, ScaleCmdDeletedProc);
scalePtr->optionTable = optionTable;
scalePtr->orient = ORIENT_VERTICAL;
scalePtr->width = 0;
scalePtr->length = 0;
scalePtr->value = 0.0;
scalePtr->varNamePtr = NULL;
scalePtr->fromValue = 0.0;
scalePtr->toValue = 0.0;
scalePtr->tickInterval = 0.0;
scalePtr->resolution = 1.0;
scalePtr->digits = 0;
scalePtr->bigIncrement = 0.0;
scalePtr->command = NULL;
scalePtr->repeatDelay = 0;
scalePtr->repeatInterval = 0;
scalePtr->label = NULL;
scalePtr->labelLength = 0;
scalePtr->state = STATE_NORMAL;
scalePtr->borderWidth = 0;
scalePtr->bgBorder = NULL;
scalePtr->activeBorder = NULL;
scalePtr->sliderRelief = TK_RELIEF_RAISED;
scalePtr->troughColorPtr = NULL;
scalePtr->troughGC = NULL;
scalePtr->copyGC = NULL;
scalePtr->tkfont = NULL;
scalePtr->textColorPtr = NULL;
scalePtr->textGC = NULL;
scalePtr->relief = TK_RELIEF_FLAT;
scalePtr->highlightWidth = 0;
scalePtr->highlightBorder = NULL;
scalePtr->highlightColorPtr = NULL;
scalePtr->inset = 0;
scalePtr->sliderLength = 0;
scalePtr->showValue = 0;
scalePtr->horizLabelY = 0;
scalePtr->horizValueY = 0;
scalePtr->horizTroughY = 0;
scalePtr->horizTickY = 0;
scalePtr->vertTickRightX = 0;
scalePtr->vertValueRightX = 0;
scalePtr->vertTroughX = 0;
scalePtr->vertLabelX = 0;
scalePtr->fontHeight = 0;
scalePtr->cursor = NULL;
scalePtr->takeFocusPtr = NULL;
scalePtr->flags = NEVER_SET;
Tk_SetClassProcs(scalePtr->tkwin, &scaleClass, scalePtr);
Tk_CreateEventHandler(scalePtr->tkwin,
ExposureMask|StructureNotifyMask|FocusChangeMask,
ScaleEventProc, scalePtr);
if ((Tk_InitOptions(interp, (char *) scalePtr, optionTable, tkwin)
!= TCL_OK) ||
(ConfigureScale(interp, scalePtr, objc - 2, objv + 2) != TCL_OK)) {
Tk_DestroyWindow(scalePtr->tkwin);
return TCL_ERROR;
}
/*
* The widget was just created, no command callback must be invoked.
*/
scalePtr->flags &= ~INVOKE_COMMAND;
Tcl_SetObjResult(interp, TkNewWindowObj(scalePtr->tkwin));
return TCL_OK;
}
/*
*--------------------------------------------------------------
*
* ScaleWidgetObjCmd --
*
* This procedure is invoked to process the Tcl command that corresponds
* to a widget managed by this module. See the user documentation for
* details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
static int
ScaleWidgetObjCmd(
ClientData clientData, /* Information about scale widget. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument strings. */
{
TkScale *scalePtr = clientData;
Tcl_Obj *objPtr;
int index, result;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
return TCL_ERROR;
}
result = Tcl_GetIndexFromObjStruct(interp, objv[1], commandNames,
sizeof(char *), "option", 0, &index);
if (result != TCL_OK) {
return result;
}
Tcl_Preserve(scalePtr);
switch (index) {
case COMMAND_CGET:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "cget option");
goto error;
}
objPtr = Tk_GetOptionValue(interp, (char *) scalePtr,
scalePtr->optionTable, objv[2], scalePtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
break;
case COMMAND_CONFIGURE:
if (objc <= 3) {
objPtr = Tk_GetOptionInfo(interp, (char *) scalePtr,
scalePtr->optionTable,
(objc == 3) ? objv[2] : NULL, scalePtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
} else {
result = ConfigureScale(interp, scalePtr, objc-2, objv+2);
}
break;
case COMMAND_COORDS: {
int x, y;
double value;
Tcl_Obj *coords[2];
if ((objc != 2) && (objc != 3)) {
Tcl_WrongNumArgs(interp, 1, objv, "coords ?value?");
goto error;
}
if (objc == 3) {
if (Tcl_GetDoubleFromObj(interp, objv[2], &value) != TCL_OK) {
goto error;
}
} else {
value = scalePtr->value;
}
if (scalePtr->orient == ORIENT_VERTICAL) {
x = scalePtr->vertTroughX + scalePtr->width/2
+ scalePtr->borderWidth;
y = TkScaleValueToPixel(scalePtr, value);
} else {
x = TkScaleValueToPixel(scalePtr, value);
y = scalePtr->horizTroughY + scalePtr->width/2
+ scalePtr->borderWidth;
}
coords[0] = Tcl_NewIntObj(x);
coords[1] = Tcl_NewIntObj(y);
Tcl_SetObjResult(interp, Tcl_NewListObj(2, coords));
break;
}
case COMMAND_GET: {
double value;
int x, y;
if ((objc != 2) && (objc != 4)) {
Tcl_WrongNumArgs(interp, 1, objv, "get ?x y?");
goto error;
}
if (objc == 2) {
value = scalePtr->value;
} else {
if ((Tcl_GetIntFromObj(interp, objv[2], &x) != TCL_OK) ||
(Tcl_GetIntFromObj(interp, objv[3], &y) != TCL_OK)) {
goto error;
}
value = TkScalePixelToValue(scalePtr, x, y);
}
Tcl_SetObjResult(interp, Tcl_ObjPrintf(scalePtr->valueFormat, value));
break;
}
case COMMAND_IDENTIFY: {
int x, y;
const char *zone = "";
if (objc != 4) {
Tcl_WrongNumArgs(interp, 1, objv, "identify x y");
goto error;
}
if ((Tcl_GetIntFromObj(interp, objv[2], &x) != TCL_OK)
|| (Tcl_GetIntFromObj(interp, objv[3], &y) != TCL_OK)) {
goto error;
}
switch (TkpScaleElement(scalePtr, x, y)) {
case TROUGH1: zone = "trough1"; break;
case SLIDER: zone = "slider"; break;
case TROUGH2: zone = "trough2"; break;
}
Tcl_SetObjResult(interp, Tcl_NewStringObj(zone, -1));
break;
}
case COMMAND_SET: {
double value;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "set value");
goto error;
}
if (Tcl_GetDoubleFromObj(interp, objv[2], &value) != TCL_OK) {
goto error;
}
if (scalePtr->state != STATE_DISABLED) {
TkScaleSetValue(scalePtr, value, 1, 1);
}
break;
}
}
Tcl_Release(scalePtr);
return result;
error:
Tcl_Release(scalePtr);
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* DestroyScale --
*
* This procedure is invoked by Tcl_EventuallyFree or Tcl_Release to
* clean up the internal structure of a button at a safe time (when
* no-one is using it anymore).
*
* Results:
* None.
*
* Side effects:
* Everything associated with the scale is freed up.
*
*----------------------------------------------------------------------
*/
static void
DestroyScale(
char *memPtr) /* Info about scale widget. */
{
TkScale *scalePtr = (TkScale *) memPtr;
scalePtr->flags |= SCALE_DELETED;
Tcl_DeleteCommandFromToken(scalePtr->interp, scalePtr->widgetCmd);
if (scalePtr->flags & REDRAW_PENDING) {
Tcl_CancelIdleCall(TkpDisplayScale, scalePtr);
}
/*
* Free up all the stuff that requires special handling, then let
* Tk_FreeOptions handle all the standard option-related stuff.
*/
if (scalePtr->varNamePtr != NULL) {
Tcl_UntraceVar2(scalePtr->interp, Tcl_GetString(scalePtr->varNamePtr),
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
ScaleVarProc, scalePtr);
}
if (scalePtr->troughGC != NULL) {
Tk_FreeGC(scalePtr->display, scalePtr->troughGC);
}
if (scalePtr->copyGC != NULL) {
Tk_FreeGC(scalePtr->display, scalePtr->copyGC);
}
if (scalePtr->textGC != NULL) {
Tk_FreeGC(scalePtr->display, scalePtr->textGC);
}
Tk_FreeConfigOptions((char *) scalePtr, scalePtr->optionTable,
scalePtr->tkwin);
scalePtr->tkwin = NULL;
TkpDestroyScale(scalePtr);
}
/*
*----------------------------------------------------------------------
*
* ConfigureScale --
*
* This procedure is called to process an argv/argc list, plus the Tk
* option database, in order to configure (or reconfigure) a scale
* widget.
*
* Results:
* The return value is a standard Tcl result. If TCL_ERROR is returned,
* then the interp's result contains an error message.
*
* Side effects:
* Configuration information, such as colors, border width, etc. get set
* for scalePtr; old resources get freed, if there were any.
*
*----------------------------------------------------------------------
*/
static int
ConfigureScale(
Tcl_Interp *interp, /* Used for error reporting. */
TkScale *scalePtr, /* Information about widget; may or may not
* already have values for some fields. */
int objc, /* Number of valid entries in objv. */
Tcl_Obj *const objv[]) /* Argument values. */
{
Tk_SavedOptions savedOptions;
Tcl_Obj *errorResult = NULL;
int error;
double varValue;
/*
* Eliminate any existing trace on a variable monitored by the scale.
*/
if (scalePtr->varNamePtr != NULL) {
Tcl_UntraceVar2(interp, Tcl_GetString(scalePtr->varNamePtr),
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
ScaleVarProc, scalePtr);
}
for (error = 0; error <= 1; error++) {
if (!error) {
/*
* First pass: set options to new values.
*/
if (Tk_SetOptions(interp, (char *) scalePtr,
scalePtr->optionTable, objc, objv, scalePtr->tkwin,
&savedOptions, NULL) != TCL_OK) {
continue;
}
} else {
/*
* Second pass: restore options to old values.
*/
errorResult = Tcl_GetObjResult(interp);
Tcl_IncrRefCount(errorResult);
Tk_RestoreSavedOptions(&savedOptions);
}
/*
* If the scale is tied to the value of a variable, then set the
* scale's value from the value of the variable, if it exists and it
* holds a valid double value.
*/
if (scalePtr->varNamePtr != NULL) {
double value;
Tcl_Obj *valuePtr;
valuePtr = Tcl_ObjGetVar2(interp, scalePtr->varNamePtr, NULL,
TCL_GLOBAL_ONLY);
if ((valuePtr != NULL) &&
(Tcl_GetDoubleFromObj(NULL, valuePtr, &value) == TCL_OK)) {
scalePtr->value = TkRoundValueToResolution(scalePtr, value);
}
}
/*
* The fromValue shall not be rounded to the resolution, but the
* toValue and tickInterval do.
*/
scalePtr->toValue = TkRoundValueToResolution(scalePtr, scalePtr->toValue);
scalePtr->tickInterval = TkRoundIntervalToResolution(scalePtr,
scalePtr->tickInterval);
/*
* Make sure that the tick interval has the right sign so that
* addition moves from fromValue to toValue.
*/
if ((scalePtr->tickInterval < 0)
^ ((scalePtr->toValue - scalePtr->fromValue) < 0)) {
scalePtr->tickInterval = -scalePtr->tickInterval;
}
ComputeFormat(scalePtr, 0);
ComputeFormat(scalePtr, 1);
scalePtr->labelLength = scalePtr->label ? (int)strlen(scalePtr->label) : 0;
Tk_SetBackgroundFromBorder(scalePtr->tkwin, scalePtr->bgBorder);
if (scalePtr->highlightWidth < 0) {
scalePtr->highlightWidth = 0;
}
scalePtr->inset = scalePtr->highlightWidth + scalePtr->borderWidth;
break;
}
if (!error) {
Tk_FreeSavedOptions(&savedOptions);
}
/*
* Set the scale value to itself; all this does is to make sure that the
* scale's value is within the new acceptable range for the scale. We
* don't set the var here because we need to make special checks for
* possibly changed varNamePtr.
*/
TkScaleSetValue(scalePtr, scalePtr->value, 0, 1);
/*
* Reestablish the variable trace, if it is needed.
*/
if (scalePtr->varNamePtr != NULL) {
Tcl_Obj *valuePtr;
/*
* Set the associated variable only when the new value differs from
* the current value, or the variable doesn't yet exist.
*/
valuePtr = Tcl_ObjGetVar2(interp, scalePtr->varNamePtr, NULL,
TCL_GLOBAL_ONLY);
if ((valuePtr == NULL) || (Tcl_GetDoubleFromObj(NULL,
valuePtr, &varValue) != TCL_OK)) {
ScaleSetVariable(scalePtr);
} else {
char varString[TCL_DOUBLE_SPACE], scaleString[TCL_DOUBLE_SPACE];
Tcl_PrintDouble(NULL, varValue, varString);
Tcl_PrintDouble(NULL, scalePtr->value, scaleString);
if (strcmp(varString, scaleString)) {
ScaleSetVariable(scalePtr);
}
}
Tcl_TraceVar2(interp, Tcl_GetString(scalePtr->varNamePtr),
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
ScaleVarProc, scalePtr);
}
ScaleWorldChanged(scalePtr);
if (error) {
Tcl_SetObjResult(interp, errorResult);
Tcl_DecrRefCount(errorResult);
return TCL_ERROR;
}
return TCL_OK;
}
/*
*---------------------------------------------------------------------------
*
* ScaleWorldChanged --
*
* This procedure is called when the world has changed in some way and
* the widget needs to recompute all its graphics contexts and determine
* its new geometry.
*
* Results:
* None.
*
* Side effects:
* Scale will be relayed out and redisplayed.
*
*---------------------------------------------------------------------------
*/
static void
ScaleWorldChanged(
ClientData instanceData) /* Information about widget. */
{
XGCValues gcValues;
GC gc;
TkScale *scalePtr = instanceData;
gcValues.foreground = scalePtr->troughColorPtr->pixel;
gc = Tk_GetGC(scalePtr->tkwin, GCForeground, &gcValues);
if (scalePtr->troughGC != NULL) {
Tk_FreeGC(scalePtr->display, scalePtr->troughGC);
}
scalePtr->troughGC = gc;
gcValues.font = Tk_FontId(scalePtr->tkfont);
gcValues.foreground = scalePtr->textColorPtr->pixel;
gc = Tk_GetGC(scalePtr->tkwin, GCForeground | GCFont, &gcValues);
if (scalePtr->textGC != NULL) {
Tk_FreeGC(scalePtr->display, scalePtr->textGC);
}
scalePtr->textGC = gc;
if (scalePtr->copyGC == NULL) {
gcValues.graphics_exposures = False;
scalePtr->copyGC = Tk_GetGC(scalePtr->tkwin, GCGraphicsExposures,
&gcValues);
}
scalePtr->inset = scalePtr->highlightWidth + scalePtr->borderWidth;
/*
* Recompute display-related information, and let the geometry manager
* know how much space is needed now.
*/
ComputeScaleGeometry(scalePtr);
TkEventuallyRedrawScale(scalePtr, REDRAW_ALL);
}
/*
*----------------------------------------------------------------------
*
* MaxTickRoundingError --
*
* Given the separation between values that can be displayed on ticks,
* this calculates the maximum magnitude of error for the displayed
* value. Tries to be clever by working out the increment in error
* between ticks rather than testing all of them, so may overestimate
* error if it is greater than 0.25 x the value separation.
*
* Results:
* Maximum error magnitude of tick numbers.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static double
MaxTickRoundingError(
TkScale *scalePtr, /* Information about scale widget. */
double tickResolution) /* Separation between displayable values. */
{
double tickPosn, firstTickError, lastTickError, intervalError;
int tickCount;
/*
* Compute the error for each tick-related measure.
*/
tickPosn = scalePtr->fromValue / tickResolution;
firstTickError = tickPosn - ScaleRound(tickPosn);
tickPosn = scalePtr->tickInterval / tickResolution;
intervalError = tickPosn - ScaleRound(tickPosn);
tickCount = (int) ((scalePtr->toValue - scalePtr->fromValue) /
scalePtr->tickInterval); /* not including first */
lastTickError = ScaleMin(0.5,
fabs(firstTickError + tickCount * intervalError));
/*
* Compute the maximum cumulative rounding error.
*/
return ScaleMax(fabs(firstTickError), lastTickError) * tickResolution;
}
/*
*----------------------------------------------------------------------
*
* ComputeFormat --
*
* This procedure is invoked to recompute the "valueFormat" or
* "tickFormat" field of a scale's widget record, which determines how
* the value of the scale or one of its ticks is converted to a string.
*
* Results:
* None.
*
* Side effects: The valueFormat or tickFormat field of scalePtr is modified.
*
*----------------------------------------------------------------------
*/
static void
ComputeFormat(
TkScale *scalePtr, /* Information about scale widget. */
int forTicks) /* Do for ticks rather than value */
{
double maxValue, x;
int mostSigDigit, numDigits, leastSigDigit, afterDecimal;
int eDigits, fDigits;
/*
* Compute the displacement from the decimal of the most significant digit
* required for any number in the scale's range.
*/
maxValue = fabs(scalePtr->fromValue);
x = fabs(scalePtr->toValue);
if (x > maxValue) {
maxValue = x;
}
if (maxValue == 0) {
maxValue = 1;
}
mostSigDigit = ScaleDigit(maxValue);
if (forTicks) {
/*
* Display only enough digits to ensure adjacent ticks have different
* values.
*/
if (scalePtr->tickInterval != 0) {
leastSigDigit = ScaleDigit(scalePtr->tickInterval);
/*
* Now add more digits until max error is less than
* TICK_VALUES_DISPLAY_ACCURACY intervals
*/
while (MaxTickRoundingError(scalePtr, pow(10, leastSigDigit))
> fabs(TICK_VALUES_DISPLAY_ACCURACY * scalePtr->tickInterval)) {
--leastSigDigit;
}
numDigits = 1 + mostSigDigit - leastSigDigit;
} else {
numDigits = 1;
}
} else {
/*
* If the number of significant digits wasn't specified explicitly,
* compute it. It's the difference between the most significant digit
* needed to represent any number on the scale and the most
* significant digit of the smallest difference between numbers on the
* scale. In other words, display enough digits so that at least one
* digit will be different between any two adjacent positions of the
* scale.
*/
numDigits = scalePtr->digits;
if (numDigits > TCL_MAX_PREC) {
numDigits = 0;
}
if (numDigits <= 0) {
if (scalePtr->resolution > 0) {
/*
* A resolution was specified for the scale, so just use it.
*/
leastSigDigit = ScaleDigit(scalePtr->resolution);
} else {
/*
* No resolution was specified, so compute the difference in
* value between adjacent pixels and use it for the least
* significant digit.
*/
x = fabs(scalePtr->fromValue - scalePtr->toValue);
if (scalePtr->length > 0) {
x /= scalePtr->length;
}
if (x > 0) {
leastSigDigit = ScaleDigit(x);
} else {
leastSigDigit = 0;
}
}
numDigits = mostSigDigit - leastSigDigit + 1;
if (numDigits < 1) {
numDigits = 1;
}
}
}
/*
* Compute the number of characters required using "e" format and "f"
* format, and then choose whichever one takes fewer characters.
*/
eDigits = numDigits + 4;
if (numDigits > 1) {
eDigits++; /* Decimal point. */
}
afterDecimal = numDigits - mostSigDigit - 1;
if (afterDecimal < 0) {
afterDecimal = 0;
}
fDigits = (mostSigDigit >= 0) ? mostSigDigit + afterDecimal : afterDecimal;
if (afterDecimal > 0) {
fDigits++; /* Decimal point. */
}
if (mostSigDigit < 0) {
fDigits++; /* Zero to left of decimal point. */
}
if (forTicks) {
if (fDigits <= eDigits) {
sprintf(scalePtr->tickFormat, "%%.%df", afterDecimal);
} else {
sprintf(scalePtr->tickFormat, "%%.%de", numDigits - 1);
}
} else {
if (fDigits <= eDigits) {
sprintf(scalePtr->valueFormat, "%%.%df", afterDecimal);
} else {
sprintf(scalePtr->valueFormat, "%%.%de", numDigits - 1);
}
}
}
/*
*----------------------------------------------------------------------
*
* ComputeScaleGeometry --
*
* This procedure is called to compute various geometrical information
* for a scale, such as where various things get displayed. It's called
* when the window is reconfigured.
*
* Results:
* None.
*
* Side effects:
* Display-related numbers get changed in *scalePtr. The geometry manager
* gets told about the window's preferred size.
*
*----------------------------------------------------------------------
*/
static void
ComputeScaleGeometry(
TkScale *scalePtr) /* Information about widget. */
{
char valueString[TCL_DOUBLE_SPACE];
int tmp, valuePixels, tickPixels, x, y, extraSpace;
Tk_FontMetrics fm;
Tk_GetFontMetrics(scalePtr->tkfont, &fm);
scalePtr->fontHeight = fm.linespace + SPACING;
/*
* Horizontal scales are simpler than vertical ones because all sizes are
* the same (the height of a line of text); handle them first and then
* quit.
*/
if (scalePtr->orient == ORIENT_HORIZONTAL) {
y = scalePtr->inset;
extraSpace = 0;
if (scalePtr->labelLength != 0) {
scalePtr->horizLabelY = y + SPACING;
y += scalePtr->fontHeight;
extraSpace = SPACING;
}
if (scalePtr->showValue) {
scalePtr->horizValueY = y + SPACING;
y += scalePtr->fontHeight;
extraSpace = SPACING;
} else {
scalePtr->horizValueY = y;
}
y += extraSpace;
scalePtr->horizTroughY = y;
y += scalePtr->width + 2*scalePtr->borderWidth;
if (scalePtr->tickInterval != 0) {
scalePtr->horizTickY = y + SPACING;
y += scalePtr->fontHeight + SPACING;
}
Tk_GeometryRequest(scalePtr->tkwin,
scalePtr->length + 2*scalePtr->inset, y + scalePtr->inset);
Tk_SetInternalBorder(scalePtr->tkwin, scalePtr->inset);
return;
}
/*
* Vertical scale: compute the amount of space needed to display the
* scales value by formatting strings for the two end points; use
* whichever length is longer.
*/
if (snprintf(valueString, TCL_DOUBLE_SPACE, scalePtr->valueFormat,
scalePtr->fromValue) < 0) {
valueString[TCL_DOUBLE_SPACE - 1] = '\0';
}
valuePixels = Tk_TextWidth(scalePtr->tkfont, valueString, -1);
if (snprintf(valueString, TCL_DOUBLE_SPACE, scalePtr->valueFormat,
scalePtr->toValue) < 0) {
valueString[TCL_DOUBLE_SPACE - 1] = '\0';
}
tmp = Tk_TextWidth(scalePtr->tkfont, valueString, -1);
if (valuePixels < tmp) {
valuePixels = tmp;
}
/*
* Now do the same thing for the tick values
*/
if (snprintf(valueString, TCL_DOUBLE_SPACE, scalePtr->tickFormat,
scalePtr->fromValue) < 0) {
valueString[TCL_DOUBLE_SPACE - 1] = '\0';
}
tickPixels = Tk_TextWidth(scalePtr->tkfont, valueString, -1);
if (snprintf(valueString, TCL_DOUBLE_SPACE, scalePtr->tickFormat,
scalePtr->toValue) < 0) {
valueString[TCL_DOUBLE_SPACE - 1] = '\0';
}
tmp = Tk_TextWidth(scalePtr->tkfont, valueString, -1);
if (tickPixels < tmp) {
tickPixels = tmp;
}
/*
* Assign x-locations to the elements of the scale, working from left to
* right.
*/
x = scalePtr->inset;
if ((scalePtr->tickInterval != 0) && (scalePtr->showValue)) {
scalePtr->vertTickRightX = x + SPACING + tickPixels;
scalePtr->vertValueRightX = scalePtr->vertTickRightX + valuePixels
+ fm.ascent/2;
x = scalePtr->vertValueRightX + SPACING;
} else if (scalePtr->tickInterval != 0) {
scalePtr->vertTickRightX = x + SPACING + tickPixels;
scalePtr->vertValueRightX = scalePtr->vertTickRightX;
x = scalePtr->vertTickRightX + SPACING;
} else if (scalePtr->showValue) {
scalePtr->vertTickRightX = x;
scalePtr->vertValueRightX = x + SPACING + valuePixels;
x = scalePtr->vertValueRightX + SPACING;
} else {
scalePtr->vertTickRightX = x;
scalePtr->vertValueRightX = x;
}
scalePtr->vertTroughX = x;
x += 2*scalePtr->borderWidth + scalePtr->width;
if (scalePtr->labelLength == 0) {
scalePtr->vertLabelX = 0;
} else {
scalePtr->vertLabelX = x + fm.ascent/2;
x = scalePtr->vertLabelX + fm.ascent/2
+ Tk_TextWidth(scalePtr->tkfont, scalePtr->label,
scalePtr->labelLength);
}
Tk_GeometryRequest(scalePtr->tkwin, x + scalePtr->inset,
scalePtr->length + 2*scalePtr->inset);
Tk_SetInternalBorder(scalePtr->tkwin, scalePtr->inset);
}
/*
*--------------------------------------------------------------
*
* ScaleEventProc --
*
* This procedure is invoked by the Tk dispatcher for various events on
* scales.
*
* Results:
* None.
*
* Side effects:
* When the window gets deleted, internal structures get cleaned up.
* When it gets exposed, it is redisplayed.
*
*--------------------------------------------------------------
*/
static void
ScaleEventProc(
ClientData clientData, /* Information about window. */
XEvent *eventPtr) /* Information about event. */
{
TkScale *scalePtr = clientData;
if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) {
TkEventuallyRedrawScale(scalePtr, REDRAW_ALL);
} else if (eventPtr->type == DestroyNotify) {
DestroyScale(clientData);
} else if (eventPtr->type == ConfigureNotify) {
ComputeScaleGeometry(scalePtr);
TkEventuallyRedrawScale(scalePtr, REDRAW_ALL);
} else if (eventPtr->type == FocusIn) {
if (eventPtr->xfocus.detail != NotifyInferior) {
scalePtr->flags |= GOT_FOCUS;
if (scalePtr->highlightWidth > 0) {
TkEventuallyRedrawScale(scalePtr, REDRAW_ALL);
}
}
} else if (eventPtr->type == FocusOut) {
if (eventPtr->xfocus.detail != NotifyInferior) {
scalePtr->flags &= ~GOT_FOCUS;
if (scalePtr->highlightWidth > 0) {
TkEventuallyRedrawScale(scalePtr, REDRAW_ALL);
}
}
}
}
/*
*----------------------------------------------------------------------
*
* ScaleCmdDeletedProc --
*
* This procedure is invoked when a widget command is deleted. If the
* widget isn't already in the process of being destroyed, this command
* destroys it.
*
* Results:
* None.
*
* Side effects:
* The widget is destroyed.
*
*----------------------------------------------------------------------
*/
static void
ScaleCmdDeletedProc(
ClientData clientData) /* Pointer to widget record for widget. */
{
TkScale *scalePtr = clientData;
Tk_Window tkwin = scalePtr->tkwin;
/*
* This procedure could be invoked either because the window was destroyed
* and the command was then deleted (in which case tkwin is NULL) or
* because the command was deleted, and then this procedure destroys the
* widget.
*/
if (!(scalePtr->flags & SCALE_DELETED)) {
scalePtr->flags |= SCALE_DELETED;
Tk_DestroyWindow(tkwin);
}
}
/*
*--------------------------------------------------------------
*
* TkEventuallyRedrawScale --
*
* Arrange for part or all of a scale widget to redrawn at the next
* convenient time in the future.
*
* Results:
* None.
*
* Side effects:
* If "what" is REDRAW_SLIDER then just the slider and the value readout
* will be redrawn; if "what" is REDRAW_ALL then the entire widget will
* be redrawn.
*
*--------------------------------------------------------------
*/
void
TkEventuallyRedrawScale(
TkScale *scalePtr, /* Information about widget. */
int what) /* What to redraw: REDRAW_SLIDER or
* REDRAW_ALL. */
{
if ((what == 0) || (scalePtr->tkwin == NULL)
|| !Tk_IsMapped(scalePtr->tkwin)) {
return;
}
if (!(scalePtr->flags & REDRAW_PENDING)) {
scalePtr->flags |= REDRAW_PENDING;
Tcl_DoWhenIdle(TkpDisplayScale, scalePtr);
}
scalePtr->flags |= what;
}
/*
*--------------------------------------------------------------
*
* TkRoundValueToResolution, TkRoundIntervalToResolution --
*
* Round a given floating-point value to the nearest multiple of the
* scale's resolution.
* TkRoundValueToResolution rounds an absolute value based on the from
* value as a reference.
* TkRoundIntervalToResolution rounds a relative value without
* reference, i.e. it rounds an interval.
*
* Results:
* The return value is the rounded result.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
double
TkRoundValueToResolution(
TkScale *scalePtr, /* Information about scale widget. */
double value) /* Value to round. */
{
return TkRoundIntervalToResolution(scalePtr, value - scalePtr->fromValue)
+ scalePtr->fromValue;
}
double
TkRoundIntervalToResolution(
TkScale *scalePtr, /* Information about scale widget. */
double value) /* Value to round. */
{
double rem, rounded, tick;
if (scalePtr->resolution <= 0) {
return value;
}
tick = floor(value/scalePtr->resolution);
rounded = scalePtr->resolution * tick;
rem = value - rounded;
if (rem < 0) {
if (rem <= -scalePtr->resolution/2) {
rounded = (tick - 1.0) * scalePtr->resolution;
}
} else {
if (rem >= scalePtr->resolution/2) {
rounded = (tick + 1.0) * scalePtr->resolution;
}
}
return rounded;
}
/*
*----------------------------------------------------------------------
*
* ScaleVarProc --
*
* This procedure is invoked by Tcl whenever someone modifies a variable
* associated with a scale widget.
*
* Results:
* NULL is always returned.
*
* Side effects:
* The value displayed in the scale will change to match the variable's
* new value. If the variable has a bogus value then it is reset to the
* value of the scale.
*
*----------------------------------------------------------------------
*/
/* ARGSUSED */
static char *
ScaleVarProc(
ClientData clientData, /* Information about button. */
Tcl_Interp *interp, /* Interpreter containing variable. */
const char *name1, /* Name of variable. */
const char *name2, /* Second part of variable name. */
int flags) /* Information about what happened. */
{
TkScale *scalePtr = clientData;
const char *resultStr;
double value;
Tcl_Obj *valuePtr;
int result;
/*
* If the variable is unset, then immediately recreate it unless the whole
* interpreter is going away.
*/
if (flags & TCL_TRACE_UNSETS) {
if (!Tcl_InterpDeleted(interp) && scalePtr->varNamePtr) {
ClientData probe = NULL;
do {
probe = Tcl_VarTraceInfo(interp,
Tcl_GetString(scalePtr->varNamePtr),
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
ScaleVarProc, probe);
if (probe == (ClientData)scalePtr) {
break;
}
} while (probe);
if (probe) {
/*
* We were able to fetch the unset trace for our
* varNamePtr, which means it is not unset and not
* the cause of this unset trace. Instead some outdated
* former variable must be, and we should ignore it.
*/
return NULL;
}
Tcl_TraceVar2(interp, Tcl_GetString(scalePtr->varNamePtr),
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
ScaleVarProc, clientData);
scalePtr->flags |= NEVER_SET;
TkScaleSetValue(scalePtr, scalePtr->value, 1, 0);
}
return NULL;
}
/*
* If we came here because we updated the variable (in TkScaleSetValue),
* then ignore the trace. Otherwise update the scale with the value of the
* variable.
*/
if (scalePtr->flags & SETTING_VAR) {
return NULL;
}
resultStr = NULL;
valuePtr = Tcl_ObjGetVar2(interp, scalePtr->varNamePtr, NULL,
TCL_GLOBAL_ONLY);
result = Tcl_GetDoubleFromObj(interp, valuePtr, &value);
if (result != TCL_OK) {
resultStr = "can't assign non-numeric value to scale variable";
ScaleSetVariable(scalePtr);
} else {
scalePtr->value = TkRoundValueToResolution(scalePtr, value);
/*
* This code is a bit tricky because it sets the scale's value before
* calling TkScaleSetValue. This way, TkScaleSetValue won't bother to
* set the variable again or to invoke the -command. However, it also
* won't redisplay the scale, so we have to ask for that explicitly.
*/
TkScaleSetValue(scalePtr, scalePtr->value, 1, 0);
}
TkEventuallyRedrawScale(scalePtr, REDRAW_SLIDER);
return (char *) resultStr;
}
/*
*--------------------------------------------------------------
*
* TkScaleSetValue --
*
* This procedure changes the value of a scale and invokes a Tcl command
* to reflect the current position of a scale
*
* Results:
* None.
*
* Side effects:
* A Tcl command is invoked, and an additional error-processing command
* may also be invoked. The scale's slider is redrawn.
*
*--------------------------------------------------------------
*/
void
TkScaleSetValue(
TkScale *scalePtr, /* Info about widget. */
double value, /* New value for scale. Gets adjusted if it's
* off the scale. */
int setVar, /* Non-zero means reflect new value through to
* associated variable, if any. */
int invokeCommand) /* Non-zero means invoked -command option to
* notify of new value, 0 means don't. */
{
value = TkRoundValueToResolution(scalePtr, value);
if ((value < scalePtr->fromValue)
^ (scalePtr->toValue < scalePtr->fromValue)) {
value = scalePtr->fromValue;
}
if ((value > scalePtr->toValue)
^ (scalePtr->toValue < scalePtr->fromValue)) {
value = scalePtr->toValue;
}
if (scalePtr->flags & NEVER_SET) {
scalePtr->flags &= ~NEVER_SET;
} else if (scalePtr->value == value) {
return;
}
scalePtr->value = value;
/*
* Schedule command callback invocation only if there is such a command
* already registered, otherwise the callback would trigger later when
* configuring the widget -command option even if the value did not change.
*/
if ((invokeCommand) && (scalePtr->command != NULL)) {
scalePtr->flags |= INVOKE_COMMAND;
}
TkEventuallyRedrawScale(scalePtr, REDRAW_SLIDER);
if (setVar && scalePtr->varNamePtr) {
ScaleSetVariable(scalePtr);
}
}
/*
*--------------------------------------------------------------
*
* ScaleSetVariable --
*
* This procedure sets the variable associated with a scale, if any.
*
* Results:
* None.
*
* Side effects:
* Other write traces on the variable will trigger.
*
*--------------------------------------------------------------
*/
static void
ScaleSetVariable(
TkScale *scalePtr) /* Info about widget. */
{
if (scalePtr->varNamePtr != NULL) {
char string[TCL_DOUBLE_SPACE];
if (snprintf(string, TCL_DOUBLE_SPACE, scalePtr->valueFormat,
scalePtr->value) < 0) {
string[TCL_DOUBLE_SPACE - 1] = '\0';
}
scalePtr->flags |= SETTING_VAR;
Tcl_ObjSetVar2(scalePtr->interp, scalePtr->varNamePtr, NULL,
Tcl_NewStringObj(string, -1), TCL_GLOBAL_ONLY);
scalePtr->flags &= ~SETTING_VAR;
}
}
/*
*----------------------------------------------------------------------
*
* TkScalePixelToValue --
*
* Given a pixel within a scale window, return the scale reading
* corresponding to that pixel.
*
* Results:
* A double-precision scale reading. If the value is outside the legal
* range for the scale then it's rounded to the nearest end of the scale.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
double
TkScalePixelToValue(
TkScale *scalePtr, /* Information about widget. */
int x, int y) /* Coordinates of point within window. */
{
double value, pixelRange;
if (scalePtr->orient == ORIENT_VERTICAL) {
pixelRange = Tk_Height(scalePtr->tkwin) - scalePtr->sliderLength
- 2*scalePtr->inset - 2*scalePtr->borderWidth;
value = y;
} else {
pixelRange = Tk_Width(scalePtr->tkwin) - scalePtr->sliderLength
- 2*scalePtr->inset - 2*scalePtr->borderWidth;
value = x;
}
if (pixelRange <= 0) {
/*
* Not enough room for the slider to actually slide: just return the
* scale's current value.
*/
return scalePtr->value;
}
value -= scalePtr->sliderLength/2 + scalePtr->inset
+ scalePtr->borderWidth;
value /= pixelRange;
if (value < 0) {
value = 0;
}
if (value > 1) {
value = 1;
}
value = scalePtr->fromValue +
value * (scalePtr->toValue - scalePtr->fromValue);
return TkRoundValueToResolution(scalePtr, value);
}
/*
*----------------------------------------------------------------------
*
* TkScaleValueToPixel --
*
* Given a reading of the scale, return the x-coordinate or y-coordinate
* corresponding to that reading, depending on whether the scale is
* vertical or horizontal, respectively.
*
* Results:
* An integer value giving the pixel location corresponding to reading.
* The value is restricted to lie within the defined range for the scale.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TkScaleValueToPixel(
TkScale *scalePtr, /* Information about widget. */
double value) /* Reading of the widget. */
{
int y, pixelRange;
double valueRange;
valueRange = scalePtr->toValue - scalePtr->fromValue;
pixelRange = ((scalePtr->orient == ORIENT_VERTICAL)
? Tk_Height(scalePtr->tkwin) : Tk_Width(scalePtr->tkwin))
- scalePtr->sliderLength - 2*scalePtr->inset - 2*scalePtr->borderWidth;
if (valueRange == 0) {
y = 0;
} else {
y = ScaleRound((value - scalePtr->fromValue) * pixelRange
/ valueRange);
if (y < 0) {
y = 0;
} else if (y > pixelRange) {
y = pixelRange;
}
}
y += scalePtr->sliderLength/2 + scalePtr->inset + scalePtr->borderWidth;
return y;
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* fill-column: 78
* End:
*/
|
438120.c | /* ISC license. */
#include <skabus/rpc.h>
#include "skabus-rpc-internal.h"
uint64_t skabus_rpc_sendpm_withfds (skabus_rpc_t *a, char const *cname, char const *s, size_t len, int const *fds, unsigned int nfds, unsigned char const *bits, tain_t const *limit, tain_t const *deadline, tain_t *stamp)
{
return skabus_rpc_sendq_withfds(a, "\xff", 1, cname, s, len, fds, nfds, bits, limit, deadline, stamp) ;
}
|
177479.c | /*
Mantis PCI bridge driver
Copyright (C) Manu Abraham ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/signal.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <media/dmxdev.h>
#include <media/dvbdev.h>
#include <media/dvb_demux.h>
#include <media/dvb_frontend.h>
#include <media/dvb_net.h>
#include "mantis_common.h"
#include "mantis_link.h"
#include "mantis_hif.h"
#include "mantis_reg.h"
#include "mantis_ca.h"
static int mantis_ca_read_attr_mem(struct dvb_ca_en50221 *en50221, int slot, int addr)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Request Attribute Mem Read", slot);
if (slot != 0)
return -EINVAL;
return mantis_hif_read_mem(ca, addr);
}
static int mantis_ca_write_attr_mem(struct dvb_ca_en50221 *en50221, int slot, int addr, u8 data)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Request Attribute Mem Write", slot);
if (slot != 0)
return -EINVAL;
return mantis_hif_write_mem(ca, addr, data);
}
static int mantis_ca_read_cam_ctl(struct dvb_ca_en50221 *en50221, int slot, u8 addr)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Request CAM control Read", slot);
if (slot != 0)
return -EINVAL;
return mantis_hif_read_iom(ca, addr);
}
static int mantis_ca_write_cam_ctl(struct dvb_ca_en50221 *en50221, int slot, u8 addr, u8 data)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Request CAM control Write", slot);
if (slot != 0)
return -EINVAL;
return mantis_hif_write_iom(ca, addr, data);
}
static int mantis_ca_slot_reset(struct dvb_ca_en50221 *en50221, int slot)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Slot RESET", slot);
udelay(500); /* Wait.. */
mmwrite(0xda, MANTIS_PCMCIA_RESET); /* Leading edge assert */
udelay(500);
mmwrite(0x00, MANTIS_PCMCIA_RESET); /* Trailing edge deassert */
msleep(1000);
dvb_ca_en50221_camready_irq(&ca->en50221, 0);
return 0;
}
static int mantis_ca_slot_shutdown(struct dvb_ca_en50221 *en50221, int slot)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Slot shutdown", slot);
return 0;
}
static int mantis_ts_control(struct dvb_ca_en50221 *en50221, int slot)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): TS control", slot);
/* mantis_set_direction(mantis, 1); */ /* Enable TS through CAM */
return 0;
}
static int mantis_slot_status(struct dvb_ca_en50221 *en50221, int slot, int open)
{
struct mantis_ca *ca = en50221->data;
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Slot(%d): Poll Slot status", slot);
if (ca->slot_state == MODULE_INSERTED) {
dprintk(MANTIS_DEBUG, 1, "CA Module present and ready");
return DVB_CA_EN50221_POLL_CAM_PRESENT | DVB_CA_EN50221_POLL_CAM_READY;
} else {
dprintk(MANTIS_DEBUG, 1, "CA Module not present or not ready");
}
return 0;
}
int mantis_ca_init(struct mantis_pci *mantis)
{
struct dvb_adapter *dvb_adapter = &mantis->dvb_adapter;
struct mantis_ca *ca;
int ca_flags = 0, result;
dprintk(MANTIS_DEBUG, 1, "Initializing Mantis CA");
ca = kzalloc(sizeof(struct mantis_ca), GFP_KERNEL);
if (!ca) {
dprintk(MANTIS_ERROR, 1, "Out of memory!, exiting ..");
result = -ENOMEM;
goto err;
}
ca->ca_priv = mantis;
mantis->mantis_ca = ca;
ca_flags = DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE;
/* register CA interface */
ca->en50221.owner = THIS_MODULE;
ca->en50221.read_attribute_mem = mantis_ca_read_attr_mem;
ca->en50221.write_attribute_mem = mantis_ca_write_attr_mem;
ca->en50221.read_cam_control = mantis_ca_read_cam_ctl;
ca->en50221.write_cam_control = mantis_ca_write_cam_ctl;
ca->en50221.slot_reset = mantis_ca_slot_reset;
ca->en50221.slot_shutdown = mantis_ca_slot_shutdown;
ca->en50221.slot_ts_enable = mantis_ts_control;
ca->en50221.poll_slot_status = mantis_slot_status;
ca->en50221.data = ca;
mutex_init(&ca->ca_lock);
init_waitqueue_head(&ca->hif_data_wq);
init_waitqueue_head(&ca->hif_opdone_wq);
init_waitqueue_head(&ca->hif_write_wq);
dprintk(MANTIS_ERROR, 1, "Registering EN50221 device");
result = dvb_ca_en50221_init(dvb_adapter, &ca->en50221, ca_flags, 1);
if (result != 0) {
dprintk(MANTIS_ERROR, 1, "EN50221: Initialization failed <%d>", result);
goto err;
}
dprintk(MANTIS_ERROR, 1, "Registered EN50221 device");
mantis_evmgr_init(ca);
return 0;
err:
kfree(ca);
return result;
}
EXPORT_SYMBOL_GPL(mantis_ca_init);
void mantis_ca_exit(struct mantis_pci *mantis)
{
struct mantis_ca *ca = mantis->mantis_ca;
dprintk(MANTIS_DEBUG, 1, "Mantis CA exit");
if (!ca)
return;
mantis_evmgr_exit(ca);
dprintk(MANTIS_ERROR, 1, "Unregistering EN50221 device");
dvb_ca_en50221_release(&ca->en50221);
kfree(ca);
}
EXPORT_SYMBOL_GPL(mantis_ca_exit);
|
678372.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "EUTRA-RRC-Definitions"
* found in "/home/lixh/enb_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14`
*/
#include "LTE_WLANConnectionStatusReport-v1430-IEs.h"
static const ber_tlv_tag_t asn_DEF_LTE_nonCriticalExtension_tags_3[] = {
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_SEQUENCE_specifics_t asn_SPC_LTE_nonCriticalExtension_specs_3 = {
sizeof(struct LTE_WLANConnectionStatusReport_v1430_IEs__nonCriticalExtension),
offsetof(struct LTE_WLANConnectionStatusReport_v1430_IEs__nonCriticalExtension, _asn_ctx),
0, /* No top level tags */
0, /* No tags in the map */
0, 0, 0, /* Optional elements (not needed) */
-1, /* First extension addition */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_LTE_nonCriticalExtension_3 = {
"nonCriticalExtension",
"nonCriticalExtension",
&asn_OP_SEQUENCE,
asn_DEF_LTE_nonCriticalExtension_tags_3,
sizeof(asn_DEF_LTE_nonCriticalExtension_tags_3)
/sizeof(asn_DEF_LTE_nonCriticalExtension_tags_3[0]) - 1, /* 1 */
asn_DEF_LTE_nonCriticalExtension_tags_3, /* Same as above */
sizeof(asn_DEF_LTE_nonCriticalExtension_tags_3)
/sizeof(asn_DEF_LTE_nonCriticalExtension_tags_3[0]), /* 2 */
{ 0, 0, SEQUENCE_constraint },
0, 0, /* No members */
&asn_SPC_LTE_nonCriticalExtension_specs_3 /* Additional specs */
};
asn_TYPE_member_t asn_MBR_LTE_WLANConnectionStatusReport_v1430_IEs_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct LTE_WLANConnectionStatusReport_v1430_IEs, wlan_Status_v1430),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_LTE_WLAN_Status_v1430,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"wlan-Status-v1430"
},
{ ATF_POINTER, 1, offsetof(struct LTE_WLANConnectionStatusReport_v1430_IEs, nonCriticalExtension),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
0,
&asn_DEF_LTE_nonCriticalExtension_3,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"nonCriticalExtension"
},
};
static const int asn_MAP_LTE_WLANConnectionStatusReport_v1430_IEs_oms_1[] = { 1 };
static const ber_tlv_tag_t asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_LTE_WLANConnectionStatusReport_v1430_IEs_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* wlan-Status-v1430 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* nonCriticalExtension */
};
asn_SEQUENCE_specifics_t asn_SPC_LTE_WLANConnectionStatusReport_v1430_IEs_specs_1 = {
sizeof(struct LTE_WLANConnectionStatusReport_v1430_IEs),
offsetof(struct LTE_WLANConnectionStatusReport_v1430_IEs, _asn_ctx),
asn_MAP_LTE_WLANConnectionStatusReport_v1430_IEs_tag2el_1,
2, /* Count of tags in the map */
asn_MAP_LTE_WLANConnectionStatusReport_v1430_IEs_oms_1, /* Optional members */
1, 0, /* Root/Additions */
-1, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs = {
"WLANConnectionStatusReport-v1430-IEs",
"WLANConnectionStatusReport-v1430-IEs",
&asn_OP_SEQUENCE,
asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1,
sizeof(asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1)
/sizeof(asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1[0]), /* 1 */
asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1, /* Same as above */
sizeof(asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1)
/sizeof(asn_DEF_LTE_WLANConnectionStatusReport_v1430_IEs_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_LTE_WLANConnectionStatusReport_v1430_IEs_1,
2, /* Elements count */
&asn_SPC_LTE_WLANConnectionStatusReport_v1430_IEs_specs_1 /* Additional specs */
};
|
756441.c | /***************************************************************************//**
* @file
* @brief Splits long messages into smaller fragments for transmission and
* reassembles received fragments into full messages.
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#include "app/framework/include/af.h"
#include "app/framework/util/util.h"
#include "fragmentation.h"
#ifdef UC_BUILD
#if (EMBER_AF_PLUGIN_FRAGMENTATION_FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK == 1)
#define FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK
#endif
#else // !UC_BUILD
#ifdef EMBER_AF_PLUGIN_FRAGMENTATION_FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK
#define FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK
#endif
#endif // UC_BUILD
//------------------------------------------------------------------------------
// Globals
#ifndef UC_BUILD
EmberEventControl emAfFragmentationEvents[10];
#endif // UC_BUILD
#if defined(FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK)
#define FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK_BOOLEAN true
#else
#define FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK_BOOLEAN false
#endif
static const bool freeOutgoingMessagePriorToFinalAck = FREE_OUTGOING_MESSAGE_PRIOR_TO_FINAL_ACK_BOOLEAN;
#define UNUSED_TX_PACKET_ENTRY 0xFF
//------------------------------------------------------------------------------
// Forward Declarations
static EmberStatus sendNextFragments(txFragmentedPacket* txPacket);
static void abortTransmission(txFragmentedPacket *txPacket, EmberStatus status);
static txFragmentedPacket* getFreeTxPacketEntry(void);
static txFragmentedPacket* txPacketLookUp(EmberApsFrame *apsFrame);
static void updateCurrentAppTasksForFragmentationState(void);
// We separate the outgoing buffer from the txPacket entry to allow us to keep around
// data about previous fragmented messages that have sent their last packet
// but not yet been acknowledged. This saves space by not replicating the entire
// buffer required to store the outgoing message. However, in that case we do not
// pass the complete message to the message sent handler.
static txFragmentedPacket txPackets[EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS];
static uint8_t txMessageBuffers[EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS]
[EMBER_AF_PLUGIN_FRAGMENTATION_BUFFER_SIZE];
static txFragmentedPacket txPacketAwaitingFinalAck = {
.messageType = UNUSED_TX_PACKET_ENTRY
};
#if defined(EMBER_TEST)
#define NO_BLOCK_TO_DROP 0xFF
uint8_t emAfPluginFragmentationArtificiallyDropBlockNumber = NO_BLOCK_TO_DROP;
#define artificiallyDropBlock(block) (block == emAfPluginFragmentationArtificiallyDropBlockNumber)
#define clearArtificiallyDropBlock() emAfPluginFragmentationArtificiallyDropBlockNumber = NO_BLOCK_TO_DROP;
#define artificiallyDropBlockPrintln(format, arg) emberAfCorePrintln((format), (arg))
#else
#define artificiallyDropBlock(block) false
#define clearArtificiallyDropBlock()
#define artificiallyDropBlockPrintln(format, arg)
#endif
#define messageTag(txPacket) ((txPacket)->sequence)
//------------------------------------------------------------------------------
// Functions
EmberStatus emAfFragmentationSendUnicast(EmberOutgoingMessageType type,
uint16_t indexOrDestination,
EmberApsFrame *apsFrame,
uint8_t *buffer,
uint16_t bufLen,
uint16_t *messageTag)
{
EmberStatus status;
uint16_t fragments;
txFragmentedPacket* txPacket;
if (emberFragmentWindowSize == 0) {
return EMBER_INVALID_CALL;
}
if (bufLen > EMBER_AF_PLUGIN_FRAGMENTATION_BUFFER_SIZE) {
return EMBER_MESSAGE_TOO_LONG;
}
txPacket = getFreeTxPacketEntry();
if (txPacket == NULL) {
return EMBER_MAX_MESSAGE_LIMIT_REACHED;
}
txPacket->messageType = type;
txPacket->indexOrDestination = indexOrDestination;
MEMMOVE(&txPacket->apsFrame, apsFrame, sizeof(EmberApsFrame));
txPacket->apsFrame.options |=
(EMBER_APS_OPTION_FRAGMENT | EMBER_APS_OPTION_RETRY);
emAfPluginFragmentationHandleSourceRoute(txPacket,
indexOrDestination);
MEMMOVE(txPacket->bufferPtr, buffer, bufLen);
txPacket->bufLen = bufLen;
txPacket->fragmentLen = emberAfMaximumApsPayloadLength(type,
indexOrDestination,
&txPacket->apsFrame);
fragments = ((bufLen + txPacket->fragmentLen - 1) / txPacket->fragmentLen);
if (fragments > MAX_INT8U_VALUE) {
return EMBER_MESSAGE_TOO_LONG;
}
txPacket->fragmentCount = (uint8_t)fragments;
txPacket->fragmentBase = 0;
txPacket->fragmentsInTransit = 0;
status = sendNextFragments(txPacket);
if (status == EMBER_SUCCESS) {
// Set the APS sequence number in the passed apsFrame.
apsFrame->sequence = txPacket->sequence;
emberAfAddToCurrentAppTasks(EMBER_AF_FRAGMENTATION_IN_PROGRESS);
} else {
txPacket->messageType = UNUSED_TX_PACKET_ENTRY;
}
*messageTag = messageTag(txPacket);
return status;
}
bool emAfFragmentationMessageSent(EmberApsFrame *apsFrame,
EmberStatus status)
{
if (apsFrame->options & EMBER_APS_OPTION_FRAGMENT) {
// If the outgoing APS frame is fragmented, we should always have a
// a corresponding record in the txFragmentedPacket array.
txFragmentedPacket *txPacket = txPacketLookUp(apsFrame);
if (txPacket == NULL) {
return true;
}
if (status == EMBER_SUCCESS) {
txPacket->fragmentsInTransit--;
if (txPacket->fragmentsInTransit == 0) {
txPacket->fragmentBase += emberFragmentWindowSize;
abortTransmission(txPacket, sendNextFragments(txPacket));
}
} else {
abortTransmission(txPacket, status);
}
updateCurrentAppTasksForFragmentationState();
return true;
} else {
return false;
}
}
static EmberStatus sendNextFragments(txFragmentedPacket* txPacket)
{
uint8_t i;
uint16_t offset;
emberAfCorePrintln("Sending fragment %d of %d",
txPacket->fragmentBase,
txPacket->fragmentCount);
offset = txPacket->fragmentBase * txPacket->fragmentLen;
// Send fragments until the window is full.
for (i = txPacket->fragmentBase;
i < txPacket->fragmentBase + emberFragmentWindowSize
&& i < txPacket->fragmentCount;
i++) {
EmberStatus status;
// For a message requiring n fragments, the length of each of the first
// n - 1 fragments is the maximum fragment size. The length of the last
// fragment is whatever is leftover.
uint8_t fragmentLen = (offset + txPacket->fragmentLen < txPacket->bufLen
? txPacket->fragmentLen
: txPacket->bufLen - offset);
txPacket->apsFrame.groupId = HIGH_LOW_TO_INT(txPacket->fragmentCount, i);
status = emAfPluginFragmentationSend(txPacket,
i,
fragmentLen,
offset);
if (status != EMBER_SUCCESS) {
return status;
}
txPacket->fragmentsInTransit++;
offset += fragmentLen;
} // close inner for
if (txPacket->fragmentsInTransit == 0) {
emAfFragmentationMessageSentHandler(txPacket->messageType,
txPacket->indexOrDestination,
&txPacket->apsFrame,
txPacket->bufferPtr,
txPacket->bufLen,
EMBER_SUCCESS,
messageTag(txPacket));
txPacket->messageType = UNUSED_TX_PACKET_ENTRY;
} else if (freeOutgoingMessagePriorToFinalAck
&& txPacket->bufferPtr != NULL
&& offset >= txPacket->bufLen
&& emberFragmentWindowSize == 1
&& txPacketAwaitingFinalAck.messageType == UNUSED_TX_PACKET_ENTRY) {
// Awaiting final fragment
MEMMOVE(&txPacketAwaitingFinalAck, txPacket, sizeof(txFragmentedPacket));
txPacketAwaitingFinalAck.bufferPtr = NULL;
txPacketAwaitingFinalAck.bufLen = 0;
txPacket->messageType = UNUSED_TX_PACKET_ENTRY;
}
return EMBER_SUCCESS;
}
static void abortTransmission(txFragmentedPacket *txPacket,
EmberStatus status)
{
if (status != EMBER_SUCCESS && txPacket->messageType != UNUSED_TX_PACKET_ENTRY) {
emAfFragmentationMessageSentHandler(txPacket->messageType,
txPacket->indexOrDestination,
&txPacket->apsFrame,
txPacket->bufferPtr,
txPacket->bufLen,
status,
messageTag(txPacket));
txPacket->messageType = UNUSED_TX_PACKET_ENTRY;
}
}
static txFragmentedPacket* getFreeTxPacketEntry(void)
{
uint8_t i;
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS; i++) {
txFragmentedPacket *txPacket = &(txPackets[i]);
if (txPacket->messageType == UNUSED_TX_PACKET_ENTRY) {
txPacket->bufferPtr = txMessageBuffers[i];
return txPacket;
}
}
return NULL;
}
static txFragmentedPacket* txPacketLookUp(EmberApsFrame *apsFrame)
{
uint8_t i;
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS; i++) {
txFragmentedPacket *txPacket = &(txPackets[i]);
if (txPacket->messageType == UNUSED_TX_PACKET_ENTRY) {
continue;
}
// Each node has a single source APS counter.
if (apsFrame->sequence == txPacket->apsFrame.sequence) {
return txPacket;
}
}
if (txPacketAwaitingFinalAck.messageType != UNUSED_TX_PACKET_ENTRY
&& apsFrame->sequence == txPacketAwaitingFinalAck.apsFrame.sequence) {
return &txPacketAwaitingFinalAck;
}
return NULL;
}
//------------------------------------------------------------------------------
// Receiving.
#define lowBitMask(n) ((1u << (n)) - 1)
static void setFragmentMask(rxFragmentedPacket *rxPacket);
static bool storeRxFragment(rxFragmentedPacket *rxPacket,
uint8_t fragment,
uint8_t *buffer,
uint16_t bufLen);
static void moveRxWindow(rxFragmentedPacket *rxPacket);
static rxFragmentedPacket* getFreeRxPacketEntry(void);
static rxFragmentedPacket* rxPacketLookUp(EmberApsFrame *apsFrame,
EmberNodeId sender);
static rxFragmentedPacket rxPackets[EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS];
static void ageAllAckedRxPackets(void)
{
uint8_t i;
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
if (rxPackets[i].status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_ACKED) {
rxPackets[i].ackedPacketAge++;
}
}
}
static uint16_t retryTimeoutMs(EmberNodeId nodeId)
{
EmberEUI64 eui64;
uint16_t retryTimeoutMs = emberApsAckTimeoutMs;
if (EMBER_SLEEPY_END_DEVICE <= emAfCurrentZigbeeProNetwork->nodeType) {
retryTimeoutMs += emberMacIndirectTimeout;
}
if (emberLookupEui64ByNodeId(nodeId, eui64) == EMBER_SUCCESS
&& emberGetExtendedTimeout(eui64)) {
retryTimeoutMs += emberMacIndirectTimeout;
}
return retryTimeoutMs;
}
bool emAfFragmentationIncomingMessage(EmberIncomingMessageType type,
EmberApsFrame *apsFrame,
EmberNodeId sender,
uint8_t **buffer,
uint16_t *bufLen)
{
static bool rxWindowMoved = false;
bool newFragment;
uint8_t fragment;
uint8_t mask;
rxFragmentedPacket *rxPacket;
EmberAfClusterCommand cmd;
if (!(apsFrame->options & EMBER_APS_OPTION_FRAGMENT)) {
return false;
}
assert(*bufLen <= MAX_INT8U_VALUE);
rxPacket = rxPacketLookUp(apsFrame, sender);
fragment = LOW_BYTE(apsFrame->groupId);
if (artificiallyDropBlock(fragment)) {
artificiallyDropBlockPrintln("Artificially dropping block %d", fragment);
clearArtificiallyDropBlock();
return true;
}
// First fragment for this packet, we need to set up a new entry.
if (rxPacket == NULL) {
rxPacket = getFreeRxPacketEntry();
if (rxPacket == NULL || fragment >= emberFragmentWindowSize) {
return true;
}
rxPacket->status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_IN_USE;
rxPacket->fragmentSource = sender;
rxPacket->fragmentSequenceNumber = apsFrame->sequence;
rxPacket->fragmentBase = 0;
rxPacket->windowFinger = 0;
rxPacket->fragmentsReceived = 0;
rxPacket->fragmentsExpected = 0xFF;
rxPacket->fragmentLen = (uint8_t)(*bufLen);
setFragmentMask(rxPacket);
#ifdef UC_BUILD
slxu_zigbee_event_set_delay_ms(&(rxPacket->fragmentEventControl),
(retryTimeoutMs(sender)
* ZIGBEE_APSC_MAX_TRANSMIT_RETRIES));
#else // !UC_BUILD
emberEventControlSetDelayMS(*(rxPacket->fragmentEventControl),
(retryTimeoutMs(sender)
* ZIGBEE_APSC_MAX_TRANSMIT_RETRIES));
#endif // UC_BUILD
emberAfAddToCurrentAppTasks(EMBER_AF_FRAGMENTATION_IN_PROGRESS);
}
// All fragments inside the rx window have been received and the incoming
// fragment is outside the receiving window: let's move the rx window.
if (rxPacket->fragmentMask == 0xFF
&& rxPacket->fragmentBase + emberFragmentWindowSize <= fragment) {
moveRxWindow(rxPacket);
setFragmentMask(rxPacket);
rxWindowMoved = true;
#ifdef UC_BUILD
slxu_zigbee_event_set_delay_ms(&(rxPacket->fragmentEventControl),
(retryTimeoutMs(sender)
* ZIGBEE_APSC_MAX_TRANSMIT_RETRIES));
#else // !UC_BUILD
emberEventControlSetDelayMS(*(rxPacket->fragmentEventControl),
(retryTimeoutMs(sender)
* ZIGBEE_APSC_MAX_TRANSMIT_RETRIES));
#endif // UC_BUILD
}
// Fragment outside the rx window.
if (fragment < rxPacket->fragmentBase
|| fragment >= rxPacket->fragmentBase + emberFragmentWindowSize) {
return true;
} else { // Fragment inside the rx window.
if (rxWindowMoved) {
// We assume that the fragment length for the new rx window is the length
// of the first fragment received inside the window. However, if the first
// fragment received is the last fragment of the packet, we do not
// consider it for setting the fragment length.
if (fragment < rxPacket->fragmentsExpected - 1) {
rxPacket->fragmentLen = (uint8_t)(*bufLen);
rxWindowMoved = false;
}
} else {
// We enforce that all the subsequent fragments (except for the last
// fragment) inside the rx window have the same length as the first one.
if (fragment < rxPacket->fragmentsExpected - 1
&& rxPacket->fragmentLen != (uint8_t)(*bufLen)) {
goto kickout;
}
}
}
mask = 1 << (fragment % emberFragmentWindowSize);
newFragment = !(mask & rxPacket->fragmentMask);
// First fragment, setting the total number of expected fragments.
if (fragment == 0) {
rxPacket->fragmentsExpected = HIGH_BYTE(apsFrame->groupId);
if (rxPacket->fragmentsExpected < emberFragmentWindowSize) {
setFragmentMask(rxPacket);
}
}
emberAfCorePrintln("Receiving fragment %d of %d", fragment, rxPacket->fragmentsExpected);
// If it's a new fragment, try to buffer it
// If the payload is too long, we wait to hear all fragments (and ack each
// one) and then respond with an INSUFFICIENT_SPACE
rxPacket->fragmentMask |= mask;
if (newFragment) {
rxPacket->fragmentsReceived++;
if (!storeRxFragment(rxPacket, fragment, *buffer, *bufLen)
&& (EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_PAYLOAD_TOO_LARGE != rxPacket->status)) {
goto kickout;
}
}
if (fragment == rxPacket->fragmentsExpected - 1
|| (rxPacket->fragmentMask
| lowBitMask(fragment % emberFragmentWindowSize)) == 0xFF) {
emAfPluginFragmentationSendReply(sender,
apsFrame,
rxPacket);
}
// Received all the expected fragments.
if (rxPacket->fragmentsReceived == rxPacket->fragmentsExpected) {
uint8_t fragmentsInLastWindow =
rxPacket->fragmentsExpected % emberFragmentWindowSize;
if (fragmentsInLastWindow == 0) {
fragmentsInLastWindow = emberFragmentWindowSize;
}
// Pass the reassembled packet only once to the application.
if (rxPacket->status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_IN_USE) {
//Age all acked packets first
ageAllAckedRxPackets();
// Mark the packet entry as acked.
rxPacket->status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_ACKED;
// Set the age of the new acked packet as the youngest one.
rxPacket->ackedPacketAge = 0;
// This library sends replies for all fragments, so, before passing on the
// reassembled message, clear the retry bit to prevent the application
// from sending a duplicate reply.
apsFrame->options &= ~EMBER_APS_OPTION_RETRY;
// The total size is the window finger + (n-1) full fragments + the last
// fragment.
*bufLen = rxPacket->windowFinger + rxPacket->lastfragmentLen
+ (fragmentsInLastWindow - 1) * rxPacket->fragmentLen;
*buffer = rxPacket->buffer;
updateCurrentAppTasksForFragmentationState();
return false;
} else if (rxPacket->status
== EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_PAYLOAD_TOO_LARGE) {
// Send a default response with INSUFFICIENT_SPACE
*bufLen = rxPacket->windowFinger + rxPacket->lastfragmentLen
+ (fragmentsInLastWindow - 1) * rxPacket->fragmentLen;
*buffer = rxPacket->buffer;
emberAfProcessMessageIntoZclCmd(apsFrame,
type,
*buffer,
*bufLen,
sender,
NULL, // inter-PAN fragments don't reach here
&cmd);
emberAfSendDefaultResponse(&cmd, EMBER_ZCL_STATUS_INSUFFICIENT_SPACE);
// Finally, free the buffer
#ifdef UC_BUILD
emAfFragmentationAbortReception(&(rxPacket->fragmentEventControl));
#else // !UC_BUILD
emAfFragmentationAbortReception(rxPacket->fragmentEventControl);
#endif // UC_BUILD
}
}
return true;
kickout:
#ifdef UC_BUILD
emAfFragmentationAbortReception(&(rxPacket->fragmentEventControl));
#else // !UC_BUILD
emAfFragmentationAbortReception(rxPacket->fragmentEventControl);
#endif // UC_BUILD
return true;
}
#ifdef UC_BUILD
void emAfFragmentationAbortReception(sl_zigbee_event_t* control)
#else // !UC_BUILD
void emAfFragmentationAbortReception(EmberEventControl* control)
#endif // UC_BUILD
{
uint8_t i;
#ifdef UC_BUILD
slxu_zigbee_event_set_inactive(control);
#else // !UC_BUILD
emberEventControlSetInactive(*control);
#endif // UC_BUILD
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
rxFragmentedPacket *rxPacket = &(rxPackets[i]);
#ifdef UC_BUILD
if (&(rxPacket->fragmentEventControl) == control) {
#else // !UC_BUILD
if (rxPacket->fragmentEventControl == control) {
#endif // UC_BUILD
rxPacket->status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_AVAILABLE;
}
}
updateCurrentAppTasksForFragmentationState();
}
static void setFragmentMask(rxFragmentedPacket *rxPacket)
{
// Unused bits must be 1.
uint8_t highestZeroBit = emberFragmentWindowSize;
// If we are in the final window, there may be additional unused bits.
if (rxPacket->fragmentsExpected
< rxPacket->fragmentBase + emberFragmentWindowSize) {
highestZeroBit = (rxPacket->fragmentsExpected % emberFragmentWindowSize);
}
rxPacket->fragmentMask = ~lowBitMask(highestZeroBit);
}
static bool storeRxFragment(rxFragmentedPacket *rxPacket,
uint8_t fragment,
uint8_t *buffer,
uint16_t bufLen)
{
uint16_t index = rxPacket->windowFinger;
if (index + bufLen > EMBER_AF_PLUGIN_FRAGMENTATION_BUFFER_SIZE) {
rxPacket->status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_PAYLOAD_TOO_LARGE;
return false;
}
index += (fragment - rxPacket->fragmentBase) * rxPacket->fragmentLen;
MEMMOVE(rxPacket->buffer + index, buffer, bufLen);
// If this is the last fragment of the packet, store its length.
if (fragment == rxPacket->fragmentsExpected - 1) {
rxPacket->lastfragmentLen = (uint8_t)bufLen;
}
return true;
}
static void moveRxWindow(rxFragmentedPacket *rxPacket)
{
rxPacket->fragmentBase += emberFragmentWindowSize;
rxPacket->windowFinger += emberFragmentWindowSize * rxPacket->fragmentLen;
}
static rxFragmentedPacket* getFreeRxPacketEntry(void)
{
uint8_t i;
rxFragmentedPacket* ackedPacket = NULL;
// Available entries first.
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
rxFragmentedPacket *rxPacket = &(rxPackets[i]);
if (rxPacket->status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_AVAILABLE) {
return rxPacket;
}
}
// Acked packets: Look for the oldest one.
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
rxFragmentedPacket *rxPacket = &(rxPackets[i]);
if (rxPacket->status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_ACKED) {
if (ackedPacket == NULL
|| ackedPacket->ackedPacketAge < rxPacket->ackedPacketAge) {
ackedPacket = rxPacket;
}
}
}
return ackedPacket;
}
static rxFragmentedPacket* rxPacketLookUp(EmberApsFrame *apsFrame,
EmberNodeId sender)
{
uint8_t i;
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
rxFragmentedPacket *rxPacket = &(rxPackets[i]);
if (rxPacket->status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_AVAILABLE) {
continue;
}
// Each packet is univocally identified by the pair (node id, seq. number).
if (apsFrame->sequence == rxPacket->fragmentSequenceNumber
&& sender == rxPacket->fragmentSource) {
return rxPacket;
}
}
return NULL;
}
//------------------------------------------------------------------------------
// Initialization
#ifdef UC_BUILD
void emberAfPluginFragmentationInitCallback(uint8_t init_level)
{
switch (init_level) {
case SL_ZIGBEE_INIT_LEVEL_EVENT:
{
uint8_t i;
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
slxu_zigbee_event_init(&(rxPackets[i].fragmentEventControl),
emAfFragmentationAbortReception);
rxPackets[i].status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_AVAILABLE;
}
break;
}
case SL_ZIGBEE_INIT_LEVEL_LOCAL_DATA:
{
uint8_t i;
emAfPluginFragmentationPlatformInitCallback();
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS; i++) {
txPackets[i].messageType = 0xFF;
}
break;
}
}
}
#else // !UC_BUILD
void emberAfPluginFragmentationInitCallback(void)
{
uint8_t i;
emAfPluginFragmentationPlatformInitCallback();
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
slxu_zigbee_event_init(&(rxPackets[i].fragmentEventControl),
emAfFragmentationAbortReception);
rxPackets[i].status = EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_AVAILABLE;
rxPackets[i].fragmentEventControl = &(emAfFragmentationEvents[i]);
}
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS; i++) {
txPackets[i].messageType = 0xFF;
}
}
#endif // UC_BUILD
//------------------------------------------------------------------------------
// Utility
// Clear app task frag bit only if neither tx nor rx frag is in progress.
static void updateCurrentAppTasksForFragmentationState(void)
{
uint8_t i;
bool fragmenting;
fragmenting = false;
if (txPacketAwaitingFinalAck.messageType != UNUSED_TX_PACKET_ENTRY) {
fragmenting = true;
}
if (!fragmenting) {
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_OUTGOING_PACKETS; i++) {
if (txPackets[i].messageType != UNUSED_TX_PACKET_ENTRY) {
fragmenting = true;
break;
}
}
}
if (!fragmenting) {
for (i = 0; i < EMBER_AF_PLUGIN_FRAGMENTATION_MAX_INCOMING_PACKETS; i++) {
if (rxPackets[i].status == EMBER_AF_PLUGIN_FRAGMENTATION_RX_PACKET_IN_USE) {
fragmenting = true;
break;
}
}
}
if (!fragmenting) {
emberAfRemoveFromCurrentAppTasks(EMBER_AF_FRAGMENTATION_IN_PROGRESS);
}
}
|
771307.c | /*
MIT License
Copyright (c) 2021 Ben Buhrow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
A demo program utilizing ycalc library.
If no arguments on command line, enter an interactive session.
If string arguments on the command line, run calc on them and return.
If redirect or pipe is detected, ignore any command line arguments, run
calc on the lines in the file, and return;
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "calc.h"
#if defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <io.h>
#else
#include <unistd.h> //isatty
#endif
#if defined(__unix__)
#include <termios.h>
#define CMDHIST_SIZE 16
static char** CMDHIST;
static int CMDHIST_HEAD = 0;
static int CMDHIST_TAIL = 0;
#endif
int exp_is_open(char* line, int firstline);
char* get_input(char* input_exp, uint32_t* insize);
char* process_batchline(int* code);
// gcc -O2 calc.h calc.c demo.c -o demo -lgmp -lm
int main(int argc, char** argv)
{
int have_redirect = 0;
#if defined(__MINGW32__)
// I'm not sure how to detect at runtime if this is an msys shell.
// So unfortunately if we compile with mingw we basically have to remove
// the ability to process from pipes or redirects. should be able to use
// batchfiles via command line switch still.
if (0)
{
#elif defined(WIN32)
if (_isatty(_fileno(stdin)) == 0)
{
fseek(stdin, -1, SEEK_END);
if (ftell(stdin) >= 0)
{
rewind(stdin);
#else
if (isatty(fileno(stdin)) == 0)
{
#endif
// ok, we have incoming data in a pipe or redirect
have_redirect = 1;
}
#if defined(WIN32) && !defined(__MINGW32__) // not complete, but ok for now
}
#endif
calc_init();
if ((argc == 1) && (have_redirect == 0))
{
// with no arguments to the program, enter an interactive loop
// to process commands
uint32_t insize = GSTR_MAXSIZE;
char* input_exp, * indup, * input_line;
str_t input_str;
int firstline = 1;
//the input expression
input_exp = (char*)malloc(GSTR_MAXSIZE * sizeof(char));
indup = (char*)malloc(GSTR_MAXSIZE * sizeof(char));
input_line = (char*)malloc(GSTR_MAXSIZE * sizeof(char));
sInit(&input_str);
strcpy(input_exp, "");
strcpy(input_line, "");
printf(">> ");
#if defined(__unix__)
int i;
static struct termios oldtio, newtio;
tcgetattr(0, &oldtio);
newtio = oldtio;
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK);
CMDHIST = (char**)malloc(CMDHIST_SIZE * sizeof(char*));
for (i = 0; i < CMDHIST_SIZE; i++)
{
CMDHIST[i] = (char*)malloc(GSTR_MAXSIZE * sizeof(char));
}
#endif
while (1)
{
{
#if defined(__unix__)
tcsetattr(0, TCSANOW, &newtio);
#endif
input_line = get_input(input_line, &insize);
#if defined(__unix__)
tcsetattr(0, TCSANOW, &oldtio);
#endif
}
// exit, or execute the current expression...
if ((strcmp(input_line, "quit") == 0) || (strcmp(input_line, "exit") == 0))
{
break;
}
else
{
sAppend(input_line, &input_str);
if (exp_is_open(input_line, firstline))
{
if (strlen(input_line) > 0)
sAppend(",", &input_str);
firstline = 0;
continue;
}
firstline = 1;
process_expression(input_str.s, NULL, 0, 1);
sClear(&input_str);
}
#if defined(WIN32) && !defined(__MINGW32__)
fflush(stdin); //important! otherwise scanf will process printf's output
#else
fflush(stdin); //important! otherwise scanf will process printf's output
fflush(stdout);
#endif
// re-display the command prompt
printf(">> ");
fflush(stdout);
}
free(input_exp);
free(input_line);
free(indup);
sFree(&input_str);
#if defined(__unix__)
for (i = 0; i < CMDHIST_SIZE; i++)
{
free(CMDHIST[i]);
}
free(CMDHIST);
#endif
}
else if (have_redirect)
{
uint32_t insize = GSTR_MAXSIZE;
char *input_line;
str_t input_str;
int firstline = 1;
//the input expression
sInit(&input_str);
while (1)
{
int code;
input_line = process_batchline(&code);
if (code == 1)
{
break;
}
else if (code == 2)
{
continue;
}
// exit, or execute the current expression...
if ((strcmp(input_line, "quit") == 0) || (strcmp(input_line, "exit") == 0))
{
free(input_line);
break;
}
else
{
sAppend(input_line, &input_str);
if (exp_is_open(input_line, firstline))
{
if (strlen(input_line) > 0)
sAppend(",", &input_str);
firstline = 0;
free(input_line);
continue;
}
free(input_line);
firstline = 1;
process_expression(input_str.s, NULL, 0, 1);
sClear(&input_str);
}
}
sFree(&input_str);
}
else
{
// else we expect expressions on the command line to process
int i;
for (i = 1; i < argc; i++)
{
process_expression(argv[i], NULL, 0, 1);
}
}
calc_finalize();
return 0;
}
int exp_is_open(char* line, int firstline)
{
int i;
static int openp, closedp, openb, closedb;
if (firstline)
{
openp = openb = closedp = closedb = 0;
}
for (i = 0; i < strlen(line); i++)
{
if (line[i] == '(') openp++;
if (line[i] == ')') closedp++;
if (line[i] == '{') openb++;
if (line[i] == '}') closedb++;
}
if ((openp == closedp) && (openb == closedb))
{
return 0;
}
else
{
return 1;
}
}
char* get_input(char* input_exp, uint32_t* insize)
{
#if !defined(__unix__)
// get command from user
fgets(input_exp, GSTR_MAXSIZE, stdin);
while (1)
{
if (input_exp[strlen(input_exp) - 1] == 13 || input_exp[strlen(input_exp) - 1] == 10)
{
// replace with a null char and continue
printf("\n");
fflush(stdout);
input_exp[strlen(input_exp) - 1] = '\0';
break;
}
else
{
// last char is not a carriage return means
// the input is longer than allocated.
// reallocate and get another chunk
*insize += GSTR_MAXSIZE;
input_exp = (char*)realloc(input_exp, *insize * sizeof(char));
if (input_exp == NULL)
{
printf("couldn't reallocate string when parsing\n");
exit(-1);
}
fgets(input_exp + strlen(input_exp), GSTR_MAXSIZE, stdin);
}
}
#else
int n = 0;
int p = CMDHIST_HEAD;
strcpy(CMDHIST[p], "");
while (1)
{
int c = getc(stdin);
// is this an escape sequence?
if (c == 27) {
// "throw away" next two characters which specify escape sequence
int c1 = getc(stdin);
int c2 = getc(stdin);
int i;
if ((c1 == 91) && (c2 == 65))
{
// clear the current screen contents
for (i = 0; i < n; i++)
printf("\b");
for (i = 0; i < n; i++)
printf(" ");
for (i = 0; i < n; i++)
printf("\b");
// save whatever is currently entered
if (p == CMDHIST_HEAD)
{
input_exp[n] = '\0';
memcpy(CMDHIST[CMDHIST_HEAD], input_exp, GSTR_MAXSIZE * sizeof(char));
}
// uparrow
if (CMDHIST_HEAD >= CMDHIST_TAIL)
{
p--;
// wrap
if (p < 0)
{
// but not past tail
p = 0;
}
}
else
{
p--;
// wrap
if (p < 0)
{
p = CMDHIST_SIZE - 1;
}
}
// and print the previous one
printf("%s", CMDHIST[p]);
strcpy(input_exp, CMDHIST[p]);
n = strlen(input_exp);
}
else if ((c1 == 91) && (c2 == 66))
{
// downarrow
// clear the current screen contents
for (i = 0; i < strlen(CMDHIST[p]); i++)
printf("\b");
for (i = 0; i < strlen(CMDHIST[p]); i++)
printf(" ");
for (i = 0; i < strlen(CMDHIST[p]); i++)
printf("\b");
if (p != CMDHIST_HEAD)
{
p++;
// wrap
if (p == CMDHIST_SIZE)
{
p = 0;
}
}
// and print the next one
printf("%s", CMDHIST[p]);
strcpy(input_exp, CMDHIST[p]);
n = strlen(input_exp);
}
else if ((c1 == 91) && (c2 == 67))
{
// rightarrow
}
else if ((c1 == 91) && (c2 == 68))
{
// leftarrow
}
else
{
printf("unknown escape sequence %d %d\n", c1, c2);
}
continue;
}
// if backspace
if (c == 0x7f)
{
//fprintf(stderr,"saw a backspace\n"); fflush(stderr);
if (n > 0)
{
// go one char left
printf("\b");
// overwrite the char with whitespace
printf(" ");
// go back to "now removed char position"
printf("\b");
n--;
}
continue;
}
if (c == EOF)
{
printf("\n");
exit(0);
}
if ((c == 13) || (c == 10))
{
input_exp[n++] = '\0';
break;
}
putc(c, stdout);
input_exp[n++] = (char)c;
if (n >= *insize)
{
*insize += GSTR_MAXSIZE;
input_exp = (char*)realloc(input_exp, *insize * sizeof(char));
if (input_exp == NULL)
{
printf("couldn't reallocate string when parsing\n");
exit(-1);
}
}
}
printf("\n");
fflush(stdout);
if (strlen(input_exp) > 0)
{
memcpy(CMDHIST[CMDHIST_HEAD++], input_exp, GSTR_MAXSIZE * sizeof(char));
if (CMDHIST_TAIL > 0)
{
CMDHIST_TAIL++;
if (CMDHIST_TAIL == CMDHIST_SIZE)
CMDHIST_TAIL = 0;
}
if (CMDHIST_HEAD == CMDHIST_SIZE)
{
CMDHIST_HEAD = 0;
if (CMDHIST_TAIL == 0)
CMDHIST_TAIL = 1;
}
}
#endif
return input_exp;
}
char* process_batchline(int* code)
{
int nChars, j;
char* line, tmpline[GSTR_MAXSIZE], * ptr;
FILE* batchfile;
batchfile = stdin;
// load the next line of the batch file and get the expression
// ready for processing
line = (char*)malloc(GSTR_MAXSIZE * sizeof(char));
strcpy(line, "");
// read a line - skipping blank lines
do
{
while (1)
{
ptr = fgets(tmpline, GSTR_MAXSIZE, batchfile);
strcpy(line + strlen(line), tmpline);
// stop if we didn't read anything
if (feof(batchfile))
{
//printf("eof; done processing batchfile\n");
fclose(batchfile);
*code = 1;
free(line);
return NULL;
}
if (ptr == NULL)
{
printf("fgets returned null; done processing batchfile\n");
fclose(batchfile);
*code = 1;
free(line);
return NULL;
}
// if we got the end of the line, stop reading
if ((line[strlen(line) - 1] == 0xa) ||
(line[strlen(line) - 1] == 0xd))
break;
// else reallocate the buffer and get some more
line = (char*)realloc(line, (strlen(line) + GSTR_MAXSIZE) * sizeof(char));
}
// remove LF an CRs from line
nChars = 0;
for (j = 0; j < strlen(line); j++)
{
switch (line[j])
{
case 13:
case 10:
break;
default:
line[nChars++] = line[j];
break;
}
}
line[nChars++] = '\0';
} while (strlen(line) == 0);
//ignore blank lines
if (strlen(line) == 0)
{
*code = 2;
free(line);
return NULL;
}
//ignore comment lines
if (((line[0] == '/') && (line[1] == '/')) || (line[0] == '%'))
{
*code = 2;
free(line);
return NULL;
}
*code = 0;
return line;
}
|
46125.c | #include <stdio.h>
#include <math.h>
#define macro(y, x) ((y) = 1 / (pow(x, 2) + 1))
int main(int argc, char *argv[])
{
double a = 0, b = 1;
double h = 0.1;
double x = a, y;
for(; x <= b; x += h)
{
macro(y, x);
printf("x = %f, y = %f\n", x, y);
}
return 0;
}
|
531155.c | /**
******************************************************************************
* @file stm32l4xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
*
* COPYRIGHT(c) 2017 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx_hal.h"
#include "stm32l4xx.h"
#include "stm32l4xx_it.h"
#include "cmsis_os.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern PCD_HandleTypeDef hpcd_USB_OTG_FS;
extern UART_HandleTypeDef huart3;
/******************************************************************************/
/* Cortex-M4 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN HardFault_IRQn 1 */
/* USER CODE END HardFault_IRQn 1 */
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN MemoryManagement_IRQn 1 */
/* USER CODE END MemoryManagement_IRQn 1 */
}
/**
* @brief This function handles Prefetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN BusFault_IRQn 1 */
/* USER CODE END BusFault_IRQn 1 */
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN UsageFault_IRQn 1 */
/* USER CODE END UsageFault_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
osSystickHandler();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32L4xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32l4xx.s). */
/******************************************************************************/
/**
* @brief This function handles USART3 global interrupt.
*/
void USART3_IRQHandler(void)
{
/* enable if uart flags need to be cleared */
#if 0
/* USER CODE END USART3_IRQn 0 */
HAL_UART_IRQHandler(&huart3);
/* USER CODE BEGIN USART3_IRQn 1 */
#endif
}
/**
* @brief This function handles USB OTG FS global interrupt.
*/
void OTG_FS_IRQHandler(void)
{
/* USER CODE BEGIN OTG_FS_IRQn 0 */
/* USER CODE END OTG_FS_IRQn 0 */
HAL_PCD_IRQHandler(&hpcd_USB_OTG_FS);
/* USER CODE BEGIN OTG_FS_IRQn 1 */
/* USER CODE END OTG_FS_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
219118.c | /**
* @file
* Management Information Base II (RFC1213) IP objects and functions.
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Dirk Ziegelmeier <[email protected]>
* Christiaan Simons <[email protected]>
*/
#include "lwip/snmp.h"
#include "lwip/apps/snmp.h"
#include "lwip/apps/snmp_core.h"
#include "lwip/apps/snmp_mib2.h"
#include "lwip/apps/snmp_table.h"
#include "lwip/apps/snmp_scalar.h"
#include "lwip/stats.h"
#include "lwip/netif.h"
#include "lwip/ip.h"
#include "lwip/etharp.h"
#if LWIP_SNMP && SNMP_LWIP_MIB2
#if SNMP_USE_NETCONN
#define SYNC_NODE_NAME(node_name) node_name ## _synced
#define CREATE_LWIP_SYNC_NODE(oid, node_name) \
static const struct snmp_threadsync_node node_name ## _synced = SNMP_CREATE_THREAD_SYNC_NODE(oid, &node_name.node, &snmp_mib2_lwip_locks);
#else
#define SYNC_NODE_NAME(node_name) node_name
#define CREATE_LWIP_SYNC_NODE(oid, node_name)
#endif
#if LWIP_IPV4
/* --- ip .1.3.6.1.2.1.4 ----------------------------------------------------- */
static s16_t
ip_get_value(struct snmp_node_instance* instance, void* value)
{
s32_t* sint_ptr = (s32_t*)value;
u32_t* uint_ptr = (u32_t*)value;
switch (instance->node->oid) {
case 1: /* ipForwarding */
#if IP_FORWARD
/* forwarding */
*sint_ptr = 1;
#else
/* not-forwarding */
*sint_ptr = 2;
#endif
return sizeof(*sint_ptr);
case 2: /* ipDefaultTTL */
*sint_ptr = IP_DEFAULT_TTL;
return sizeof(*sint_ptr);
case 3: /* ipInReceives */
*uint_ptr = STATS_GET(mib2.ipinreceives);
return sizeof(*uint_ptr);
case 4: /* ipInHdrErrors */
*uint_ptr = STATS_GET(mib2.ipinhdrerrors);
return sizeof(*uint_ptr);
case 5: /* ipInAddrErrors */
*uint_ptr = STATS_GET(mib2.ipinaddrerrors);
return sizeof(*uint_ptr);
case 6: /* ipForwDatagrams */
*uint_ptr = STATS_GET(mib2.ipforwdatagrams);
return sizeof(*uint_ptr);
case 7: /* ipInUnknownProtos */
*uint_ptr = STATS_GET(mib2.ipinunknownprotos);
return sizeof(*uint_ptr);
case 8: /* ipInDiscards */
*uint_ptr = STATS_GET(mib2.ipindiscards);
return sizeof(*uint_ptr);
case 9: /* ipInDelivers */
*uint_ptr = STATS_GET(mib2.ipindelivers);
return sizeof(*uint_ptr);
case 10: /* ipOutRequests */
*uint_ptr = STATS_GET(mib2.ipoutrequests);
return sizeof(*uint_ptr);
case 11: /* ipOutDiscards */
*uint_ptr = STATS_GET(mib2.ipoutdiscards);
return sizeof(*uint_ptr);
case 12: /* ipOutNoRoutes */
*uint_ptr = STATS_GET(mib2.ipoutnoroutes);
return sizeof(*uint_ptr);
case 13: /* ipReasmTimeout */
#if IP_REASSEMBLY
*sint_ptr = IP_REASS_MAXAGE;
#else
*sint_ptr = 0;
#endif
return sizeof(*sint_ptr);
case 14: /* ipReasmReqds */
*uint_ptr = STATS_GET(mib2.ipreasmreqds);
return sizeof(*uint_ptr);
case 15: /* ipReasmOKs */
*uint_ptr = STATS_GET(mib2.ipreasmoks);
return sizeof(*uint_ptr);
case 16: /* ipReasmFails */
*uint_ptr = STATS_GET(mib2.ipreasmfails);
return sizeof(*uint_ptr);
case 17: /* ipFragOKs */
*uint_ptr = STATS_GET(mib2.ipfragoks);
return sizeof(*uint_ptr);
case 18: /* ipFragFails */
*uint_ptr = STATS_GET(mib2.ipfragfails);
return sizeof(*uint_ptr);
case 19: /* ipFragCreates */
*uint_ptr = STATS_GET(mib2.ipfragcreates);
return sizeof(*uint_ptr);
case 23: /* ipRoutingDiscards: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_value(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return 0;
}
/**
* Test ip object value before setting.
*
* @param instance node instance
* @param len return value space (in bytes)
* @param value points to (varbind) space to copy value from.
*
* @note we allow set if the value matches the hardwired value,
* otherwise return badvalue.
*/
static snmp_err_t
ip_set_test(struct snmp_node_instance* instance, u16_t len, void *value)
{
snmp_err_t ret = SNMP_ERR_WRONGVALUE;
s32_t *sint_ptr = (s32_t*)value;
LWIP_UNUSED_ARG(len);
switch (instance->node->oid) {
case 1: /* ipForwarding */
#if IP_FORWARD
/* forwarding */
if (*sint_ptr == 1)
#else
/* not-forwarding */
if (*sint_ptr == 2)
#endif
{
ret = SNMP_ERR_NOERROR;
}
break;
case 2: /* ipDefaultTTL */
if (*sint_ptr == IP_DEFAULT_TTL) {
ret = SNMP_ERR_NOERROR;
}
break;
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_set_test(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return ret;
}
static snmp_err_t
ip_set_value(struct snmp_node_instance* instance, u16_t len, void *value)
{
LWIP_UNUSED_ARG(instance);
LWIP_UNUSED_ARG(len);
LWIP_UNUSED_ARG(value);
/* nothing to do here because in set_test we only accept values being the same as our own stored value -> no need to store anything */
return SNMP_ERR_NOERROR;
}
/* --- ipAddrTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_AddrTable_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff } /* IP D */
};
static snmp_err_t
ip_AddrTable_get_cell_value_core(struct netif *netif, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
LWIP_UNUSED_ARG(value_len);
switch (*column) {
case 1: /* ipAdEntAddr */
value->u32 = netif_ip4_addr(netif)->addr;
break;
case 2: /* ipAdEntIfIndex */
value->u32 = netif_to_num(netif);
break;
case 3: /* ipAdEntNetMask */
value->u32 = netif_ip4_netmask(netif)->addr;
break;
case 4: /* ipAdEntBcastAddr */
/* lwIP oddity, there's no broadcast
address in the netif we can rely on */
value->u32 = IPADDR_BROADCAST & 1;
break;
case 5: /* ipAdEntReasmMaxSize */
#if IP_REASSEMBLY
/* @todo The theoretical maximum is IP_REASS_MAX_PBUFS * size of the pbufs,
* but only if receiving one fragmented packet at a time.
* The current solution is to calculate for 2 simultaneous packets...
*/
value->u32 = (IP_HLEN + ((IP_REASS_MAX_PBUFS/2) *
(PBUF_POOL_BUFSIZE - PBUF_LINK_ENCAPSULATION_HLEN - PBUF_LINK_HLEN - IP_HLEN)));
#else
/** @todo returning MTU would be a bad thing and
returning a wild guess like '576' isn't good either */
value->u32 = 0;
#endif
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_AddrTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t ip;
struct netif *netif;
/* check if incoming OID length and if values are in plausible range */
if (!snmp_oid_in_range(row_oid, row_oid_len, ip_AddrTable_oid_ranges, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &ip); /* we know it succeeds because of oid_in_range check above */
/* find netif with requested ip */
netif = netif_list;
while (netif != NULL) {
if (ip4_addr_cmp(&ip, netif_ip4_addr(netif))) {
/* fill in object properties */
return ip_AddrTable_get_cell_value_core(netif, column, value, value_len);
}
netif = netif->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_AddrTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct netif *netif;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges));
/* iterate over all possible OIDs to find the next one */
netif = netif_list;
while (netif != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges)];
snmp_ip4_to_oid(netif_ip4_addr(netif), &test_oid[0]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges), netif);
netif = netif->next;
}
/* did we find a next one? */
if (state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_AddrTable_get_cell_value_core((struct netif*)state.reference, column, value, value_len);
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
/* --- ipRouteTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_RouteTable_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff }, /* IP D */
};
static snmp_err_t
ip_RouteTable_get_cell_value_core(struct netif *netif, u8_t default_route, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
switch (*column) {
case 1: /* ipRouteDest */
if (default_route) {
/* default rte has 0.0.0.0 dest */
value->u32 = IP4_ADDR_ANY4->addr;
} else {
/* netifs have netaddress dest */
ip4_addr_t tmp;
ip4_addr_get_network(&tmp, netif_ip4_addr(netif), netif_ip4_netmask(netif));
value->u32 = tmp.addr;
}
break;
case 2: /* ipRouteIfIndex */
value->u32 = netif_to_num(netif);
break;
case 3: /* ipRouteMetric1 */
if (default_route) {
value->s32 = 1; /* default */
} else {
value->s32 = 0; /* normal */
}
break;
case 4: /* ipRouteMetric2 */
case 5: /* ipRouteMetric3 */
case 6: /* ipRouteMetric4 */
value->s32 = -1; /* none */
break;
case 7: /* ipRouteNextHop */
if (default_route) {
/* default rte: gateway */
value->u32 = netif_ip4_gw(netif)->addr;
} else {
/* other rtes: netif ip_addr */
value->u32 = netif_ip4_addr(netif)->addr;
}
break;
case 8: /* ipRouteType */
if (default_route) {
/* default rte is indirect */
value->u32 = 4; /* indirect */
} else {
/* other rtes are direct */
value->u32 = 3; /* direct */
}
break;
case 9: /* ipRouteProto */
/* locally defined routes */
value->u32 = 2; /* local */
break;
case 10: /* ipRouteAge */
/* @todo (sysuptime - timestamp last change) / 100 */
value->u32 = 0;
break;
case 11: /* ipRouteMask */
if (default_route) {
/* default rte use 0.0.0.0 mask */
value->u32 = IP4_ADDR_ANY4->addr;
} else {
/* other rtes use netmask */
value->u32 = netif_ip4_netmask(netif)->addr;
}
break;
case 12: /* ipRouteMetric5 */
value->s32 = -1; /* none */
break;
case 13: /* ipRouteInfo */
value->const_ptr = snmp_zero_dot_zero.id;
*value_len = snmp_zero_dot_zero.len * sizeof(u32_t);
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_RouteTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t test_ip;
struct netif *netif;
/* check if incoming OID length and if values are in plausible range */
if (!snmp_oid_in_range(row_oid, row_oid_len, ip_RouteTable_oid_ranges, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP and port from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &test_ip); /* we know it succeeds because of oid_in_range check above */
/* default route is on default netif */
if (ip4_addr_isany_val(test_ip) && (netif_default != NULL)) {
/* fill in object properties */
return ip_RouteTable_get_cell_value_core(netif_default, 1, column, value, value_len);
}
/* find netif with requested route */
netif = netif_list;
while (netif != NULL) {
ip4_addr_t dst;
ip4_addr_get_network(&dst, netif_ip4_addr(netif), netif_ip4_netmask(netif));
if (ip4_addr_cmp(&dst, &test_ip)) {
/* fill in object properties */
return ip_RouteTable_get_cell_value_core(netif, 0, column, value, value_len);
}
netif = netif->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_RouteTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct netif *netif;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges)];
u32_t test_oid[LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges));
/* check default route */
if (netif_default != NULL) {
snmp_ip4_to_oid(IP4_ADDR_ANY4, &test_oid[0]);
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges), netif_default);
}
/* iterate over all possible OIDs to find the next one */
netif = netif_list;
while (netif != NULL) {
ip4_addr_t dst;
ip4_addr_get_network(&dst, netif_ip4_addr(netif), netif_ip4_netmask(netif));
/* check generated OID: is it a candidate for the next one? */
if (!ip4_addr_isany_val(dst)) {
snmp_ip4_to_oid(&dst, &test_oid[0]);
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges), netif);
}
netif = netif->next;
}
/* did we find a next one? */
if (state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
ip4_addr_t dst;
snmp_oid_to_ip4(&result_temp[0], &dst);
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_RouteTable_get_cell_value_core((struct netif*)state.reference, ip4_addr_isany_val(dst), column, value, value_len);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
#if LWIP_ARP && LWIP_IPV4
/* --- ipNetToMediaTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_NetToMediaTable_oid_ranges[] = {
{ 1, 0xff }, /* IfIndex */
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff } /* IP D */
};
static snmp_err_t
ip_NetToMediaTable_get_cell_value_core(u8_t arp_table_index, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
etharp_get_entry(arp_table_index, &ip, &netif, ðaddr);
/* value */
switch (*column) {
case 1: /* atIfIndex / ipNetToMediaIfIndex */
value->u32 = netif_to_num(netif);
break;
case 2: /* atPhysAddress / ipNetToMediaPhysAddress */
value->ptr = ethaddr;
*value_len = sizeof(*ethaddr);
break;
case 3: /* atNetAddress / ipNetToMediaNetAddress */
value->u32 = ip->addr;
break;
case 4: /* ipNetToMediaType */
value->u32 = 3; /* dynamic*/
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_NetToMediaTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t ip_in;
u8_t netif_index;
u8_t i;
/* check if incoming OID length and if values are in plausible range */
if (!snmp_oid_in_range(row_oid, row_oid_len, ip_NetToMediaTable_oid_ranges, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP from incoming OID */
netif_index = (u8_t)row_oid[0];
snmp_oid_to_ip4(&row_oid[1], &ip_in); /* we know it succeeds because of oid_in_range check above */
/* find requested entry */
for (i=0; i<ARP_TABLE_SIZE; i++) {
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
if (etharp_get_entry(i, &ip, &netif, ðaddr)) {
if ((netif_index == netif_to_num(netif)) && ip4_addr_cmp(&ip_in, ip)) {
/* fill in object properties */
return ip_NetToMediaTable_get_cell_value_core(i, column, value, value_len);
}
}
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_NetToMediaTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
u8_t i;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges));
/* iterate over all possible OIDs to find the next one */
for (i=0; i<ARP_TABLE_SIZE; i++) {
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
if (etharp_get_entry(i, &ip, &netif, ðaddr)) {
u32_t test_oid[LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges)];
test_oid[0] = netif_to_num(netif);
snmp_ip4_to_oid(ip, &test_oid[1]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges), (void*)(size_t)i);
}
}
/* did we find a next one? */
if (state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_NetToMediaTable_get_cell_value_core((u8_t)(size_t)state.reference, column, value, value_len);
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
#endif /* LWIP_ARP && LWIP_IPV4 */
static const struct snmp_scalar_node ip_Forwarding = SNMP_SCALAR_CREATE_NODE(1, SNMP_NODE_INSTANCE_READ_WRITE, SNMP_ASN1_TYPE_INTEGER, ip_get_value, ip_set_test, ip_set_value);
static const struct snmp_scalar_node ip_DefaultTTL = SNMP_SCALAR_CREATE_NODE(2, SNMP_NODE_INSTANCE_READ_WRITE, SNMP_ASN1_TYPE_INTEGER, ip_get_value, ip_set_test, ip_set_value);
static const struct snmp_scalar_node ip_InReceives = SNMP_SCALAR_CREATE_NODE_READONLY(3, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InHdrErrors = SNMP_SCALAR_CREATE_NODE_READONLY(4, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InAddrErrors = SNMP_SCALAR_CREATE_NODE_READONLY(5, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ForwDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(6, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InUnknownProtos = SNMP_SCALAR_CREATE_NODE_READONLY(7, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(8, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InDelivers = SNMP_SCALAR_CREATE_NODE_READONLY(9, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutRequests = SNMP_SCALAR_CREATE_NODE_READONLY(10, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(11, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutNoRoutes = SNMP_SCALAR_CREATE_NODE_READONLY(12, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmTimeout = SNMP_SCALAR_CREATE_NODE_READONLY(13, SNMP_ASN1_TYPE_INTEGER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmReqds = SNMP_SCALAR_CREATE_NODE_READONLY(14, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmOKs = SNMP_SCALAR_CREATE_NODE_READONLY(15, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmFails = SNMP_SCALAR_CREATE_NODE_READONLY(16, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragOKs = SNMP_SCALAR_CREATE_NODE_READONLY(17, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragFails = SNMP_SCALAR_CREATE_NODE_READONLY(18, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragCreates = SNMP_SCALAR_CREATE_NODE_READONLY(19, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_RoutingDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(23, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_table_simple_col_def ip_AddrTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntAddr */
{ 2, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntIfIndex */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntNetMask */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntBcastAddr */
{ 5, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* ipAdEntReasmMaxSize */
};
static const struct snmp_table_simple_node ip_AddrTable = SNMP_TABLE_CREATE_SIMPLE(20, ip_AddrTable_columns, ip_AddrTable_get_cell_value, ip_AddrTable_get_next_cell_instance_and_value);
static const struct snmp_table_simple_col_def ip_RouteTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteDest */
{ 2, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteIfIndex */
{ 3, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric1 */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric2 */
{ 5, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric3 */
{ 6, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric4 */
{ 7, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteNextHop */
{ 8, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteType */
{ 9, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteProto */
{ 10, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteAge */
{ 11, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteMask */
{ 12, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric5 */
{ 13, SNMP_ASN1_TYPE_OBJECT_ID, SNMP_VARIANT_VALUE_TYPE_PTR } /* ipRouteInfo */
};
static const struct snmp_table_simple_node ip_RouteTable = SNMP_TABLE_CREATE_SIMPLE(21, ip_RouteTable_columns, ip_RouteTable_get_cell_value, ip_RouteTable_get_next_cell_instance_and_value);
#endif /* LWIP_IPV4 */
#if LWIP_ARP && LWIP_IPV4
static const struct snmp_table_simple_col_def ip_NetToMediaTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipNetToMediaIfIndex */
{ 2, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_VARIANT_VALUE_TYPE_PTR }, /* ipNetToMediaPhysAddress */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipNetToMediaNetAddress */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* ipNetToMediaType */
};
static const struct snmp_table_simple_node ip_NetToMediaTable = SNMP_TABLE_CREATE_SIMPLE(22, ip_NetToMediaTable_columns, ip_NetToMediaTable_get_cell_value, ip_NetToMediaTable_get_next_cell_instance_and_value);
#endif /* LWIP_ARP && LWIP_IPV4 */
#if LWIP_IPV4
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE( 1, ip_Forwarding)
CREATE_LWIP_SYNC_NODE( 2, ip_DefaultTTL)
CREATE_LWIP_SYNC_NODE( 3, ip_InReceives)
CREATE_LWIP_SYNC_NODE( 4, ip_InHdrErrors)
CREATE_LWIP_SYNC_NODE( 5, ip_InAddrErrors)
CREATE_LWIP_SYNC_NODE( 6, ip_ForwDatagrams)
CREATE_LWIP_SYNC_NODE( 7, ip_InUnknownProtos)
CREATE_LWIP_SYNC_NODE( 8, ip_InDiscards)
CREATE_LWIP_SYNC_NODE( 9, ip_InDelivers)
CREATE_LWIP_SYNC_NODE(10, ip_OutRequests)
CREATE_LWIP_SYNC_NODE(11, ip_OutDiscards)
CREATE_LWIP_SYNC_NODE(12, ip_OutNoRoutes)
CREATE_LWIP_SYNC_NODE(13, ip_ReasmTimeout)
CREATE_LWIP_SYNC_NODE(14, ip_ReasmReqds)
CREATE_LWIP_SYNC_NODE(15, ip_ReasmOKs)
CREATE_LWIP_SYNC_NODE(15, ip_ReasmFails)
CREATE_LWIP_SYNC_NODE(17, ip_FragOKs)
CREATE_LWIP_SYNC_NODE(18, ip_FragFails)
CREATE_LWIP_SYNC_NODE(19, ip_FragCreates)
CREATE_LWIP_SYNC_NODE(20, ip_AddrTable)
CREATE_LWIP_SYNC_NODE(21, ip_RouteTable)
#if LWIP_ARP
CREATE_LWIP_SYNC_NODE(22, ip_NetToMediaTable)
#endif /* LWIP_ARP */
CREATE_LWIP_SYNC_NODE(23, ip_RoutingDiscards)
static const struct snmp_node* const ip_nodes[] = {
&SYNC_NODE_NAME(ip_Forwarding).node.node,
&SYNC_NODE_NAME(ip_DefaultTTL).node.node,
&SYNC_NODE_NAME(ip_InReceives).node.node,
&SYNC_NODE_NAME(ip_InHdrErrors).node.node,
&SYNC_NODE_NAME(ip_InAddrErrors).node.node,
&SYNC_NODE_NAME(ip_ForwDatagrams).node.node,
&SYNC_NODE_NAME(ip_InUnknownProtos).node.node,
&SYNC_NODE_NAME(ip_InDiscards).node.node,
&SYNC_NODE_NAME(ip_InDelivers).node.node,
&SYNC_NODE_NAME(ip_OutRequests).node.node,
&SYNC_NODE_NAME(ip_OutDiscards).node.node,
&SYNC_NODE_NAME(ip_OutNoRoutes).node.node,
&SYNC_NODE_NAME(ip_ReasmTimeout).node.node,
&SYNC_NODE_NAME(ip_ReasmReqds).node.node,
&SYNC_NODE_NAME(ip_ReasmOKs).node.node,
&SYNC_NODE_NAME(ip_ReasmFails).node.node,
&SYNC_NODE_NAME(ip_FragOKs).node.node,
&SYNC_NODE_NAME(ip_FragFails).node.node,
&SYNC_NODE_NAME(ip_FragCreates).node.node,
&SYNC_NODE_NAME(ip_AddrTable).node.node,
&SYNC_NODE_NAME(ip_RouteTable).node.node,
#if LWIP_ARP
&SYNC_NODE_NAME(ip_NetToMediaTable).node.node,
#endif /* LWIP_ARP */
&SYNC_NODE_NAME(ip_RoutingDiscards).node.node
};
const struct snmp_tree_node snmp_mib2_ip_root = SNMP_CREATE_TREE_NODE(4, ip_nodes);
#endif /* LWIP_IPV4 */
/* --- at .1.3.6.1.2.1.3 ----------------------------------------------------- */
#if LWIP_ARP && LWIP_IPV4
/* at node table is a subset of ip_nettomedia table (same rows but less columns) */
static const struct snmp_table_simple_col_def at_Table_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* atIfIndex */
{ 2, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_VARIANT_VALUE_TYPE_PTR }, /* atPhysAddress */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 } /* atNetAddress */
};
static const struct snmp_table_simple_node at_Table = SNMP_TABLE_CREATE_SIMPLE(1, at_Table_columns, ip_NetToMediaTable_get_cell_value, ip_NetToMediaTable_get_next_cell_instance_and_value);
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE(1, at_Table)
static const struct snmp_node* const at_nodes[] = {
&SYNC_NODE_NAME(at_Table).node.node
};
const struct snmp_tree_node snmp_mib2_at_root = SNMP_CREATE_TREE_NODE(3, at_nodes);
#endif /* LWIP_ARP && LWIP_IPV4 */
#endif /* LWIP_SNMP && SNMP_LWIP_MIB2 */
|
516613.c | /*-
* Copyright (c) 2009-2012 Microsoft Corp.
* Copyright (c) 2010-2012 Citrix Inc.
* Copyright (c) 2012 NetApp Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD: releng/10.2/sys/dev/hyperv/netvsc/hv_net_vsc.c 285236 2015-07-07 04:15:22Z whu $
*/
/**
* HyperV vmbus network VSC (virtual services client) module
*
*/
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/lock.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <machine/bus.h>
#include <machine/atomic.h>
#include <dev/hyperv/include/hyperv.h>
#include "hv_net_vsc.h"
#include "hv_rndis.h"
#include "hv_rndis_filter.h"
MALLOC_DEFINE(M_NETVSC, "netvsc", "Hyper-V netvsc driver");
/*
* Forward declarations
*/
static void hv_nv_on_channel_callback(void *context);
static int hv_nv_init_send_buffer_with_net_vsp(struct hv_device *device);
static int hv_nv_init_rx_buffer_with_net_vsp(struct hv_device *device);
static int hv_nv_destroy_send_buffer(netvsc_dev *net_dev);
static int hv_nv_destroy_rx_buffer(netvsc_dev *net_dev);
static int hv_nv_connect_to_vsp(struct hv_device *device);
static void hv_nv_on_send_completion(netvsc_dev *net_dev,
struct hv_device *device, hv_vm_packet_descriptor *pkt);
static void hv_nv_on_receive(netvsc_dev *net_dev,
struct hv_device *device, hv_vm_packet_descriptor *pkt);
/*
*
*/
static inline netvsc_dev *
hv_nv_alloc_net_device(struct hv_device *device)
{
netvsc_dev *net_dev;
hn_softc_t *sc = device_get_softc(device->device);
net_dev = malloc(sizeof(netvsc_dev), M_NETVSC, M_NOWAIT | M_ZERO);
if (net_dev == NULL) {
return (NULL);
}
net_dev->dev = device;
net_dev->destroy = FALSE;
sc->net_dev = net_dev;
return (net_dev);
}
/*
*
*/
static inline netvsc_dev *
hv_nv_get_outbound_net_device(struct hv_device *device)
{
hn_softc_t *sc = device_get_softc(device->device);
netvsc_dev *net_dev = sc->net_dev;;
if ((net_dev != NULL) && net_dev->destroy) {
return (NULL);
}
return (net_dev);
}
/*
*
*/
static inline netvsc_dev *
hv_nv_get_inbound_net_device(struct hv_device *device)
{
hn_softc_t *sc = device_get_softc(device->device);
netvsc_dev *net_dev = sc->net_dev;;
if (net_dev == NULL) {
return (net_dev);
}
/*
* When the device is being destroyed; we only
* permit incoming packets if and only if there
* are outstanding sends.
*/
if (net_dev->destroy && net_dev->num_outstanding_sends == 0) {
return (NULL);
}
return (net_dev);
}
int
hv_nv_get_next_send_section(netvsc_dev *net_dev)
{
unsigned long bitsmap_words = net_dev->bitsmap_words;
unsigned long *bitsmap = net_dev->send_section_bitsmap;
unsigned long idx;
int ret = NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX;
int i;
for (i = 0; i < bitsmap_words; i++) {
idx = ffs(~bitsmap[i]);
if (0 == idx)
continue;
idx--;
if (i * BITS_PER_LONG + idx >= net_dev->send_section_count)
return (ret);
if (synch_test_and_set_bit(idx, &bitsmap[i]))
continue;
ret = i * BITS_PER_LONG + idx;
break;
}
return (ret);
}
/*
* Net VSC initialize receive buffer with net VSP
*
* Net VSP: Network virtual services client, also known as the
* Hyper-V extensible switch and the synthetic data path.
*/
static int
hv_nv_init_rx_buffer_with_net_vsp(struct hv_device *device)
{
netvsc_dev *net_dev;
nvsp_msg *init_pkt;
int ret = 0;
net_dev = hv_nv_get_outbound_net_device(device);
if (!net_dev) {
return (ENODEV);
}
net_dev->rx_buf = contigmalloc(net_dev->rx_buf_size, M_NETVSC,
M_ZERO, 0UL, BUS_SPACE_MAXADDR, PAGE_SIZE, 0);
/*
* Establish the GPADL handle for this buffer on this channel.
* Note: This call uses the vmbus connection rather than the
* channel to establish the gpadl handle.
* GPADL: Guest physical address descriptor list.
*/
ret = hv_vmbus_channel_establish_gpadl(
device->channel, net_dev->rx_buf,
net_dev->rx_buf_size, &net_dev->rx_buf_gpadl_handle);
if (ret != 0) {
goto cleanup;
}
/* sema_wait(&ext->channel_init_sema); KYS CHECK */
/* Notify the NetVsp of the gpadl handle */
init_pkt = &net_dev->channel_init_packet;
memset(init_pkt, 0, sizeof(nvsp_msg));
init_pkt->hdr.msg_type = nvsp_msg_1_type_send_rx_buf;
init_pkt->msgs.vers_1_msgs.send_rx_buf.gpadl_handle =
net_dev->rx_buf_gpadl_handle;
init_pkt->msgs.vers_1_msgs.send_rx_buf.id =
NETVSC_RECEIVE_BUFFER_ID;
/* Send the gpadl notification request */
ret = hv_vmbus_channel_send_packet(device->channel, init_pkt,
sizeof(nvsp_msg), (uint64_t)(uintptr_t)init_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
if (ret != 0) {
goto cleanup;
}
sema_wait(&net_dev->channel_init_sema);
/* Check the response */
if (init_pkt->msgs.vers_1_msgs.send_rx_buf_complete.status
!= nvsp_status_success) {
ret = EINVAL;
goto cleanup;
}
net_dev->rx_section_count =
init_pkt->msgs.vers_1_msgs.send_rx_buf_complete.num_sections;
net_dev->rx_sections = malloc(net_dev->rx_section_count *
sizeof(nvsp_1_rx_buf_section), M_NETVSC, M_NOWAIT);
if (net_dev->rx_sections == NULL) {
ret = EINVAL;
goto cleanup;
}
memcpy(net_dev->rx_sections,
init_pkt->msgs.vers_1_msgs.send_rx_buf_complete.sections,
net_dev->rx_section_count * sizeof(nvsp_1_rx_buf_section));
/*
* For first release, there should only be 1 section that represents
* the entire receive buffer
*/
if (net_dev->rx_section_count != 1
|| net_dev->rx_sections->offset != 0) {
ret = EINVAL;
goto cleanup;
}
goto exit;
cleanup:
hv_nv_destroy_rx_buffer(net_dev);
exit:
return (ret);
}
/*
* Net VSC initialize send buffer with net VSP
*/
static int
hv_nv_init_send_buffer_with_net_vsp(struct hv_device *device)
{
netvsc_dev *net_dev;
nvsp_msg *init_pkt;
int ret = 0;
net_dev = hv_nv_get_outbound_net_device(device);
if (!net_dev) {
return (ENODEV);
}
net_dev->send_buf = contigmalloc(net_dev->send_buf_size, M_NETVSC,
M_ZERO, 0UL, BUS_SPACE_MAXADDR, PAGE_SIZE, 0);
if (net_dev->send_buf == NULL) {
ret = ENOMEM;
goto cleanup;
}
/*
* Establish the gpadl handle for this buffer on this channel.
* Note: This call uses the vmbus connection rather than the
* channel to establish the gpadl handle.
*/
ret = hv_vmbus_channel_establish_gpadl(device->channel,
net_dev->send_buf, net_dev->send_buf_size,
&net_dev->send_buf_gpadl_handle);
if (ret != 0) {
goto cleanup;
}
/* Notify the NetVsp of the gpadl handle */
init_pkt = &net_dev->channel_init_packet;
memset(init_pkt, 0, sizeof(nvsp_msg));
init_pkt->hdr.msg_type = nvsp_msg_1_type_send_send_buf;
init_pkt->msgs.vers_1_msgs.send_rx_buf.gpadl_handle =
net_dev->send_buf_gpadl_handle;
init_pkt->msgs.vers_1_msgs.send_rx_buf.id =
NETVSC_SEND_BUFFER_ID;
/* Send the gpadl notification request */
ret = hv_vmbus_channel_send_packet(device->channel, init_pkt,
sizeof(nvsp_msg), (uint64_t)init_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
if (ret != 0) {
goto cleanup;
}
sema_wait(&net_dev->channel_init_sema);
/* Check the response */
if (init_pkt->msgs.vers_1_msgs.send_send_buf_complete.status
!= nvsp_status_success) {
ret = EINVAL;
goto cleanup;
}
net_dev->send_section_size =
init_pkt->msgs.vers_1_msgs.send_send_buf_complete.section_size;
net_dev->send_section_count =
net_dev->send_buf_size / net_dev->send_section_size;
net_dev->bitsmap_words = howmany(net_dev->send_section_count,
BITS_PER_LONG);
net_dev->send_section_bitsmap =
malloc(net_dev->bitsmap_words * sizeof(long), M_NETVSC,
M_NOWAIT | M_ZERO);
if (NULL == net_dev->send_section_bitsmap) {
ret = ENOMEM;
goto cleanup;
}
goto exit;
cleanup:
hv_nv_destroy_send_buffer(net_dev);
exit:
return (ret);
}
/*
* Net VSC destroy receive buffer
*/
static int
hv_nv_destroy_rx_buffer(netvsc_dev *net_dev)
{
nvsp_msg *revoke_pkt;
int ret = 0;
/*
* If we got a section count, it means we received a
* send_rx_buf_complete msg
* (ie sent nvsp_msg_1_type_send_rx_buf msg) therefore,
* we need to send a revoke msg here
*/
if (net_dev->rx_section_count) {
/* Send the revoke receive buffer */
revoke_pkt = &net_dev->revoke_packet;
memset(revoke_pkt, 0, sizeof(nvsp_msg));
revoke_pkt->hdr.msg_type = nvsp_msg_1_type_revoke_rx_buf;
revoke_pkt->msgs.vers_1_msgs.revoke_rx_buf.id =
NETVSC_RECEIVE_BUFFER_ID;
ret = hv_vmbus_channel_send_packet(net_dev->dev->channel,
revoke_pkt, sizeof(nvsp_msg),
(uint64_t)(uintptr_t)revoke_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND, 0);
/*
* If we failed here, we might as well return and have a leak
* rather than continue and a bugchk
*/
if (ret != 0) {
return (ret);
}
}
/* Tear down the gpadl on the vsp end */
if (net_dev->rx_buf_gpadl_handle) {
ret = hv_vmbus_channel_teardown_gpdal(net_dev->dev->channel,
net_dev->rx_buf_gpadl_handle);
/*
* If we failed here, we might as well return and have a leak
* rather than continue and a bugchk
*/
if (ret != 0) {
return (ret);
}
net_dev->rx_buf_gpadl_handle = 0;
}
if (net_dev->rx_buf) {
/* Free up the receive buffer */
contigfree(net_dev->rx_buf, net_dev->rx_buf_size, M_NETVSC);
net_dev->rx_buf = NULL;
}
if (net_dev->rx_sections) {
free(net_dev->rx_sections, M_NETVSC);
net_dev->rx_sections = NULL;
net_dev->rx_section_count = 0;
}
return (ret);
}
/*
* Net VSC destroy send buffer
*/
static int
hv_nv_destroy_send_buffer(netvsc_dev *net_dev)
{
nvsp_msg *revoke_pkt;
int ret = 0;
/*
* If we got a section count, it means we received a
* send_rx_buf_complete msg
* (ie sent nvsp_msg_1_type_send_rx_buf msg) therefore,
* we need to send a revoke msg here
*/
if (net_dev->send_section_size) {
/* Send the revoke send buffer */
revoke_pkt = &net_dev->revoke_packet;
memset(revoke_pkt, 0, sizeof(nvsp_msg));
revoke_pkt->hdr.msg_type =
nvsp_msg_1_type_revoke_send_buf;
revoke_pkt->msgs.vers_1_msgs.revoke_send_buf.id =
NETVSC_SEND_BUFFER_ID;
ret = hv_vmbus_channel_send_packet(net_dev->dev->channel,
revoke_pkt, sizeof(nvsp_msg),
(uint64_t)(uintptr_t)revoke_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND, 0);
/*
* If we failed here, we might as well return and have a leak
* rather than continue and a bugchk
*/
if (ret != 0) {
return (ret);
}
}
/* Tear down the gpadl on the vsp end */
if (net_dev->send_buf_gpadl_handle) {
ret = hv_vmbus_channel_teardown_gpdal(net_dev->dev->channel,
net_dev->send_buf_gpadl_handle);
/*
* If we failed here, we might as well return and have a leak
* rather than continue and a bugchk
*/
if (ret != 0) {
return (ret);
}
net_dev->send_buf_gpadl_handle = 0;
}
if (net_dev->send_buf) {
/* Free up the receive buffer */
contigfree(net_dev->send_buf, net_dev->send_buf_size, M_NETVSC);
net_dev->send_buf = NULL;
}
if (net_dev->send_section_bitsmap) {
free(net_dev->send_section_bitsmap, M_NETVSC);
}
return (ret);
}
/*
* Attempt to negotiate the caller-specified NVSP version
*
* For NVSP v2, Server 2008 R2 does not set
* init_pkt->msgs.init_msgs.init_compl.negotiated_prot_vers
* to the negotiated version, so we cannot rely on that.
*/
static int
hv_nv_negotiate_nvsp_protocol(struct hv_device *device, netvsc_dev *net_dev,
uint32_t nvsp_ver)
{
nvsp_msg *init_pkt;
int ret;
init_pkt = &net_dev->channel_init_packet;
memset(init_pkt, 0, sizeof(nvsp_msg));
init_pkt->hdr.msg_type = nvsp_msg_type_init;
/*
* Specify parameter as the only acceptable protocol version
*/
init_pkt->msgs.init_msgs.init.p1.protocol_version = nvsp_ver;
init_pkt->msgs.init_msgs.init.protocol_version_2 = nvsp_ver;
/* Send the init request */
ret = hv_vmbus_channel_send_packet(device->channel, init_pkt,
sizeof(nvsp_msg), (uint64_t)(uintptr_t)init_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
if (ret != 0)
return (-1);
sema_wait(&net_dev->channel_init_sema);
if (init_pkt->msgs.init_msgs.init_compl.status != nvsp_status_success)
return (EINVAL);
return (0);
}
/*
* Send NDIS version 2 config packet containing MTU.
*
* Not valid for NDIS version 1.
*/
static int
hv_nv_send_ndis_config(struct hv_device *device, uint32_t mtu)
{
netvsc_dev *net_dev;
nvsp_msg *init_pkt;
int ret;
net_dev = hv_nv_get_outbound_net_device(device);
if (!net_dev)
return (-ENODEV);
/*
* Set up configuration packet, write MTU
* Indicate we are capable of handling VLAN tags
*/
init_pkt = &net_dev->channel_init_packet;
memset(init_pkt, 0, sizeof(nvsp_msg));
init_pkt->hdr.msg_type = nvsp_msg_2_type_send_ndis_config;
init_pkt->msgs.vers_2_msgs.send_ndis_config.mtu = mtu;
init_pkt->
msgs.vers_2_msgs.send_ndis_config.capabilities.u1.u2.ieee8021q
= 1;
/* Send the configuration packet */
ret = hv_vmbus_channel_send_packet(device->channel, init_pkt,
sizeof(nvsp_msg), (uint64_t)(uintptr_t)init_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND, 0);
if (ret != 0)
return (-EINVAL);
return (0);
}
/*
* Net VSC connect to VSP
*/
static int
hv_nv_connect_to_vsp(struct hv_device *device)
{
netvsc_dev *net_dev;
nvsp_msg *init_pkt;
uint32_t ndis_version;
uint32_t protocol_list[] = { NVSP_PROTOCOL_VERSION_1,
NVSP_PROTOCOL_VERSION_2,
NVSP_PROTOCOL_VERSION_4,
NVSP_PROTOCOL_VERSION_5 };
int i;
int protocol_number = nitems(protocol_list);
int ret = 0;
device_t dev = device->device;
hn_softc_t *sc = device_get_softc(dev);
struct ifnet *ifp = sc->arpcom.ac_ifp;
net_dev = hv_nv_get_outbound_net_device(device);
if (!net_dev) {
return (ENODEV);
}
/*
* Negotiate the NVSP version. Try the latest NVSP first.
*/
for (i = protocol_number - 1; i >= 0; i--) {
if (hv_nv_negotiate_nvsp_protocol(device, net_dev,
protocol_list[i]) == 0) {
net_dev->nvsp_version = protocol_list[i];
if (bootverbose)
device_printf(dev, "Netvsc: got version 0x%x\n",
net_dev->nvsp_version);
break;
}
}
if (i < 0) {
if (bootverbose)
device_printf(dev, "failed to negotiate a valid "
"protocol.\n");
return (EPROTO);
}
/*
* Set the MTU if supported by this NVSP protocol version
* This needs to be right after the NVSP init message per Haiyang
*/
if (net_dev->nvsp_version >= NVSP_PROTOCOL_VERSION_2)
ret = hv_nv_send_ndis_config(device, ifp->if_mtu);
/*
* Send the NDIS version
*/
init_pkt = &net_dev->channel_init_packet;
memset(init_pkt, 0, sizeof(nvsp_msg));
if (net_dev->nvsp_version <= NVSP_PROTOCOL_VERSION_4) {
ndis_version = NDIS_VERSION_6_1;
} else {
ndis_version = NDIS_VERSION_6_30;
}
init_pkt->hdr.msg_type = nvsp_msg_1_type_send_ndis_vers;
init_pkt->msgs.vers_1_msgs.send_ndis_vers.ndis_major_vers =
(ndis_version & 0xFFFF0000) >> 16;
init_pkt->msgs.vers_1_msgs.send_ndis_vers.ndis_minor_vers =
ndis_version & 0xFFFF;
/* Send the init request */
ret = hv_vmbus_channel_send_packet(device->channel, init_pkt,
sizeof(nvsp_msg), (uint64_t)(uintptr_t)init_pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND, 0);
if (ret != 0) {
goto cleanup;
}
/*
* TODO: BUGBUG - We have to wait for the above msg since the netvsp
* uses KMCL which acknowledges packet (completion packet)
* since our Vmbus always set the
* HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED flag
*/
/* sema_wait(&NetVscChannel->channel_init_sema); */
/* Post the big receive buffer to NetVSP */
ret = hv_nv_init_rx_buffer_with_net_vsp(device);
if (ret == 0)
ret = hv_nv_init_send_buffer_with_net_vsp(device);
cleanup:
return (ret);
}
/*
* Net VSC disconnect from VSP
*/
static void
hv_nv_disconnect_from_vsp(netvsc_dev *net_dev)
{
hv_nv_destroy_rx_buffer(net_dev);
hv_nv_destroy_send_buffer(net_dev);
}
/*
* Net VSC on device add
*
* Callback when the device belonging to this driver is added
*/
netvsc_dev *
hv_nv_on_device_add(struct hv_device *device, void *additional_info)
{
netvsc_dev *net_dev;
int ret = 0;
net_dev = hv_nv_alloc_net_device(device);
if (!net_dev)
goto cleanup;
/* Initialize the NetVSC channel extension */
net_dev->rx_buf_size = NETVSC_RECEIVE_BUFFER_SIZE;
net_dev->send_buf_size = NETVSC_SEND_BUFFER_SIZE;
sema_init(&net_dev->channel_init_sema, 0, "netdev_sema");
/*
* Open the channel
*/
ret = hv_vmbus_channel_open(device->channel,
NETVSC_DEVICE_RING_BUFFER_SIZE, NETVSC_DEVICE_RING_BUFFER_SIZE,
NULL, 0, hv_nv_on_channel_callback, device);
if (ret != 0)
goto cleanup;
/*
* Connect with the NetVsp
*/
ret = hv_nv_connect_to_vsp(device);
if (ret != 0)
goto close;
return (net_dev);
close:
/* Now, we can close the channel safely */
hv_vmbus_channel_close(device->channel);
cleanup:
/*
* Free the packet buffers on the netvsc device packet queue.
* Release other resources.
*/
if (net_dev) {
sema_destroy(&net_dev->channel_init_sema);
free(net_dev, M_NETVSC);
}
return (NULL);
}
/*
* Net VSC on device remove
*/
int
hv_nv_on_device_remove(struct hv_device *device, boolean_t destroy_channel)
{
hn_softc_t *sc = device_get_softc(device->device);
netvsc_dev *net_dev = sc->net_dev;;
/* Stop outbound traffic ie sends and receives completions */
mtx_lock(&device->channel->inbound_lock);
net_dev->destroy = TRUE;
mtx_unlock(&device->channel->inbound_lock);
/* Wait for all send completions */
while (net_dev->num_outstanding_sends) {
DELAY(100);
}
hv_nv_disconnect_from_vsp(net_dev);
/* At this point, no one should be accessing net_dev except in here */
/* Now, we can close the channel safely */
if (!destroy_channel) {
device->channel->state =
HV_CHANNEL_CLOSING_NONDESTRUCTIVE_STATE;
}
hv_vmbus_channel_close(device->channel);
sema_destroy(&net_dev->channel_init_sema);
free(net_dev, M_NETVSC);
return (0);
}
/*
* Net VSC on send completion
*/
static void
hv_nv_on_send_completion(netvsc_dev *net_dev,
struct hv_device *device, hv_vm_packet_descriptor *pkt)
{
nvsp_msg *nvsp_msg_pkt;
netvsc_packet *net_vsc_pkt;
nvsp_msg_pkt =
(nvsp_msg *)((unsigned long)pkt + (pkt->data_offset8 << 3));
if (nvsp_msg_pkt->hdr.msg_type == nvsp_msg_type_init_complete
|| nvsp_msg_pkt->hdr.msg_type
== nvsp_msg_1_type_send_rx_buf_complete
|| nvsp_msg_pkt->hdr.msg_type
== nvsp_msg_1_type_send_send_buf_complete) {
/* Copy the response back */
memcpy(&net_dev->channel_init_packet, nvsp_msg_pkt,
sizeof(nvsp_msg));
sema_post(&net_dev->channel_init_sema);
} else if (nvsp_msg_pkt->hdr.msg_type ==
nvsp_msg_1_type_send_rndis_pkt_complete) {
/* Get the send context */
net_vsc_pkt =
(netvsc_packet *)(unsigned long)pkt->transaction_id;
if (NULL != net_vsc_pkt) {
if (net_vsc_pkt->send_buf_section_idx !=
NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX) {
synch_change_bit(net_vsc_pkt->send_buf_section_idx,
net_dev->send_section_bitsmap);
}
/* Notify the layer above us */
net_vsc_pkt->compl.send.on_send_completion(
net_vsc_pkt->compl.send.send_completion_context);
}
atomic_subtract_int(&net_dev->num_outstanding_sends, 1);
}
}
/*
* Net VSC on send
* Sends a packet on the specified Hyper-V device.
* Returns 0 on success, non-zero on failure.
*/
int
hv_nv_on_send(struct hv_device *device, netvsc_packet *pkt)
{
netvsc_dev *net_dev;
nvsp_msg send_msg;
int ret;
net_dev = hv_nv_get_outbound_net_device(device);
if (!net_dev)
return (ENODEV);
send_msg.hdr.msg_type = nvsp_msg_1_type_send_rndis_pkt;
if (pkt->is_data_pkt) {
/* 0 is RMC_DATA */
send_msg.msgs.vers_1_msgs.send_rndis_pkt.chan_type = 0;
} else {
/* 1 is RMC_CONTROL */
send_msg.msgs.vers_1_msgs.send_rndis_pkt.chan_type = 1;
}
send_msg.msgs.vers_1_msgs.send_rndis_pkt.send_buf_section_idx =
pkt->send_buf_section_idx;
send_msg.msgs.vers_1_msgs.send_rndis_pkt.send_buf_section_size =
pkt->send_buf_section_size;
if (pkt->page_buf_count) {
ret = hv_vmbus_channel_send_packet_pagebuffer(device->channel,
pkt->page_buffers, pkt->page_buf_count,
&send_msg, sizeof(nvsp_msg), (uint64_t)(uintptr_t)pkt);
} else {
ret = hv_vmbus_channel_send_packet(device->channel,
&send_msg, sizeof(nvsp_msg), (uint64_t)(uintptr_t)pkt,
HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
}
/* Record outstanding send only if send_packet() succeeded */
if (ret == 0)
atomic_add_int(&net_dev->num_outstanding_sends, 1);
return (ret);
}
/*
* Net VSC on receive
*
* In the FreeBSD Hyper-V virtual world, this function deals exclusively
* with virtual addresses.
*/
static void
hv_nv_on_receive(netvsc_dev *net_dev, struct hv_device *device,
hv_vm_packet_descriptor *pkt)
{
hv_vm_transfer_page_packet_header *vm_xfer_page_pkt;
nvsp_msg *nvsp_msg_pkt;
netvsc_packet vsc_pkt;
netvsc_packet *net_vsc_pkt = &vsc_pkt;
device_t dev = device->device;
int count = 0;
int i = 0;
int status = nvsp_status_success;
/*
* All inbound packets other than send completion should be
* xfer page packet.
*/
if (pkt->type != HV_VMBUS_PACKET_TYPE_DATA_USING_TRANSFER_PAGES) {
device_printf(dev, "packet type %d is invalid!\n", pkt->type);
return;
}
nvsp_msg_pkt = (nvsp_msg *)((unsigned long)pkt
+ (pkt->data_offset8 << 3));
/* Make sure this is a valid nvsp packet */
if (nvsp_msg_pkt->hdr.msg_type != nvsp_msg_1_type_send_rndis_pkt) {
device_printf(dev, "packet hdr type %d is invalid!\n",
pkt->type);
return;
}
vm_xfer_page_pkt = (hv_vm_transfer_page_packet_header *)pkt;
if (vm_xfer_page_pkt->transfer_page_set_id !=
NETVSC_RECEIVE_BUFFER_ID) {
device_printf(dev, "transfer_page_set_id %d is invalid!\n",
vm_xfer_page_pkt->transfer_page_set_id);
return;
}
count = vm_xfer_page_pkt->range_count;
net_vsc_pkt->device = device;
/* Each range represents 1 RNDIS pkt that contains 1 Ethernet frame */
for (i = 0; i < count; i++) {
net_vsc_pkt->status = nvsp_status_success;
net_vsc_pkt->data = (void *)((unsigned long)net_dev->rx_buf +
vm_xfer_page_pkt->ranges[i].byte_offset);
net_vsc_pkt->tot_data_buf_len =
vm_xfer_page_pkt->ranges[i].byte_count;
hv_rf_on_receive(net_dev, device, net_vsc_pkt);
if (net_vsc_pkt->status != nvsp_status_success) {
status = nvsp_status_failure;
}
}
/*
* Moved completion call back here so that all received
* messages (not just data messages) will trigger a response
* message back to the host.
*/
hv_nv_on_receive_completion(device, vm_xfer_page_pkt->d.transaction_id,
status);
}
/*
* Net VSC on receive completion
*
* Send a receive completion packet to RNDIS device (ie NetVsp)
*/
void
hv_nv_on_receive_completion(struct hv_device *device, uint64_t tid,
uint32_t status)
{
nvsp_msg rx_comp_msg;
int retries = 0;
int ret = 0;
rx_comp_msg.hdr.msg_type = nvsp_msg_1_type_send_rndis_pkt_complete;
/* Pass in the status */
rx_comp_msg.msgs.vers_1_msgs.send_rndis_pkt_complete.status =
status;
retry_send_cmplt:
/* Send the completion */
ret = hv_vmbus_channel_send_packet(device->channel, &rx_comp_msg,
sizeof(nvsp_msg), tid, HV_VMBUS_PACKET_TYPE_COMPLETION, 0);
if (ret == 0) {
/* success */
/* no-op */
} else if (ret == EAGAIN) {
/* no more room... wait a bit and attempt to retry 3 times */
retries++;
if (retries < 4) {
DELAY(100);
goto retry_send_cmplt;
}
}
}
/*
* Net VSC on channel callback
*/
static void
hv_nv_on_channel_callback(void *context)
{
struct hv_device *device = (struct hv_device *)context;
netvsc_dev *net_dev;
device_t dev = device->device;
uint32_t bytes_rxed;
uint64_t request_id;
hv_vm_packet_descriptor *desc;
uint8_t *buffer;
int bufferlen = NETVSC_PACKET_SIZE;
int ret = 0;
net_dev = hv_nv_get_inbound_net_device(device);
if (net_dev == NULL)
return;
buffer = net_dev->callback_buf;
do {
ret = hv_vmbus_channel_recv_packet_raw(device->channel,
buffer, bufferlen, &bytes_rxed, &request_id);
if (ret == 0) {
if (bytes_rxed > 0) {
desc = (hv_vm_packet_descriptor *)buffer;
switch (desc->type) {
case HV_VMBUS_PACKET_TYPE_COMPLETION:
hv_nv_on_send_completion(net_dev, device, desc);
break;
case HV_VMBUS_PACKET_TYPE_DATA_USING_TRANSFER_PAGES:
hv_nv_on_receive(net_dev, device, desc);
break;
default:
device_printf(dev,
"hv_cb recv unknow type %d "
" packet\n", desc->type);
break;
}
} else {
break;
}
} else if (ret == ENOBUFS) {
/* Handle large packet */
if (bufferlen > NETVSC_PACKET_SIZE) {
free(buffer, M_NETVSC);
buffer = NULL;
}
/* alloc new buffer */
buffer = malloc(bytes_rxed, M_NETVSC, M_NOWAIT);
if (buffer == NULL) {
device_printf(dev,
"hv_cb malloc buffer failed, len=%u\n",
bytes_rxed);
bufferlen = 0;
break;
}
bufferlen = bytes_rxed;
}
} while (1);
if (bufferlen > NETVSC_PACKET_SIZE)
free(buffer, M_NETVSC);
}
|
61663.c | /*
* linux/net/sunrpc/sysctl.c
*
* Sysctl interface to sunrpc module.
*
* I would prefer to register the sunrpc table below sys/net, but that's
* impossible at the moment.
*/
#include <linux/types.h>
#include <linux/linkage.h>
#include <linux/ctype.h>
#include <linux/fs.h>
#include <linux/sysctl.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/sunrpc/types.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/stats.h>
#include <linux/sunrpc/svc_xprt.h>
#include "netns.h"
/*
* Declare the debug flags here
*/
unsigned int rpc_debug;
EXPORT_SYMBOL_GPL(rpc_debug);
unsigned int nfs_debug;
EXPORT_SYMBOL_GPL(nfs_debug);
unsigned int nfsd_debug;
EXPORT_SYMBOL_GPL(nfsd_debug);
unsigned int nlm_debug;
EXPORT_SYMBOL_GPL(nlm_debug);
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
static struct ctl_table_header *sunrpc_table_header;
static struct ctl_table sunrpc_table[];
void
rpc_register_sysctl(void)
{
if (!sunrpc_table_header)
sunrpc_table_header = register_sysctl_table(sunrpc_table);
}
void
rpc_unregister_sysctl(void)
{
if (sunrpc_table_header) {
unregister_sysctl_table(sunrpc_table_header);
sunrpc_table_header = NULL;
}
}
static int proc_do_xprt(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
char tmpbuf[256];
size_t len;
if ((*ppos && !write) || !*lenp) {
*lenp = 0;
return 0;
}
len = svc_print_xprts(tmpbuf, sizeof(tmpbuf));
return simple_read_from_buffer(buffer, *lenp, ppos, tmpbuf, len);
}
static int
proc_dodebug(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
char tmpbuf[20], c, *s = NULL;
char __user *p;
unsigned int value;
size_t left, len;
if ((*ppos && !write) || !*lenp) {
*lenp = 0;
return 0;
}
left = *lenp;
if (write) {
if (!access_ok(buffer, left))
return -EFAULT;
p = buffer;
while (left && __get_user(c, p) >= 0 && isspace(c))
left--, p++;
if (!left)
goto done;
if (left > sizeof(tmpbuf) - 1)
return -EINVAL;
if (copy_from_user(tmpbuf, p, left))
return -EFAULT;
tmpbuf[left] = '\0';
value = simple_strtol(tmpbuf, &s, 0);
if (s) {
left -= (s - tmpbuf);
if (left && !isspace(*s))
return -EINVAL;
while (left && isspace(*s))
left--, s++;
} else
left = 0;
*(unsigned int *) table->data = value;
/* Display the RPC tasks on writing to rpc_debug */
if (strcmp(table->procname, "rpc_debug") == 0)
rpc_show_tasks(&init_net);
} else {
len = sprintf(tmpbuf, "0x%04x", *(unsigned int *) table->data);
if (len > left)
len = left;
if (copy_to_user(buffer, tmpbuf, len))
return -EFAULT;
if ((left -= len) > 0) {
if (put_user('\n', (char __user *)buffer + len))
return -EFAULT;
left--;
}
}
done:
*lenp -= left;
*ppos += *lenp;
return 0;
}
static struct ctl_table debug_table[] = {
{
.procname = "rpc_debug",
.data = &rpc_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nfs_debug",
.data = &nfs_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nfsd_debug",
.data = &nfsd_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nlm_debug",
.data = &nlm_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "transports",
.maxlen = 256,
.mode = 0444,
.proc_handler = proc_do_xprt,
},
{ }
};
static struct ctl_table sunrpc_table[] = {
{
.procname = "sunrpc",
.mode = 0555,
.child = debug_table
},
{ }
};
#endif
|
610930.c | // RUN: %sea abc -O0 --abc-encoding=%abc_encoding %dsa "%s" %abc3_definitions 2>&1 | OutputCheck %s
// CHECK: ^sat$
// Used to avoid llvm to optimize away
extern void read(int);
extern int unknown();
#define MAX_ARRAY 10
// To test loops
int main(int argc, char **argv) {
int i, j;
int a[MAX_ARRAY][MAX_ARRAY];
for (i = 0; i < MAX_ARRAY; i++) {
for (j = 0; j < MAX_ARRAY; j++)
a[i][j - 1] = unknown(); // some unknown value here
}
for (i = 0; i < MAX_ARRAY; i++) {
read(a[i][i]);
}
return 0;
}
|
698634.c | /*
* ATone
*
* This code has been extracted from the Csound opcode "atone".
* It has been modified to work as a Soundpipe module.
*
* Original Author(s): Barry Vercoe, John FFitch, Gabriel Maldonado
* Year: 1991
* Location: OOps/ugens5.c
*
*/
#include <stdlib.h>
#include <math.h>
#include "utone.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
int ut_atone_create(ut_atone **p)
{
*p = malloc(sizeof(ut_atone));
return UT_OK;
}
int ut_atone_destroy(ut_atone **p)
{
free(*p);
return UT_OK;
}
int ut_atone_init(ut_data *ut, ut_atone *p)
{
p->hp = 1000;
UTFLOAT b;
p->tpidsr = (2.0 * M_PI) / ut->sr * 1.0;
p->prvhp = (UTFLOAT)p->hp;
b = 2.0 - cos((UTFLOAT)(p->prvhp * p->tpidsr));
p->c2 = b - sqrt(b * b - 1.0);
p->c1 = 1.0 - p->c2;
p->yt1 = 0.0;
return UT_OK;
}
int ut_atone_compute(ut_data *ut, ut_atone *p, UTFLOAT *in, UTFLOAT *out)
{
UTFLOAT c2 = p->c2, yt1 = p->yt1;
UTFLOAT x;
if (p->hp != p->prvhp) {
UTFLOAT b;
p->prvhp = p->hp;
b = 2.0 - cos((UTFLOAT)(p->hp * p->tpidsr));
p->c2 = c2 = b - sqrt(b * b - 1.0);
}
x = yt1 = c2 * (yt1 + *in);
*out = x;
yt1 -= *in;
p->yt1 = yt1;
return UT_OK;
}
|
719945.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/fcall.h"
#include "kernel/operators.h"
#include "kernel/exception.h"
#include "kernel/file.h"
#include "ext/spl/spl_exceptions.h"
#include "kernel/object.h"
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <[email protected]>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*
* Implementation of this file has been influenced by Zend Diactoros
* @link https://github.com/zendframework/zend-diactoros
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md
*/
/**
* PSR-17 StreamFactory
*/
ZEPHIR_INIT_CLASS(Phalcon_Http_Message_StreamFactory) {
ZEPHIR_REGISTER_CLASS(Phalcon\\Http\\Message, StreamFactory, phalcon, http_message_streamfactory, phalcon_http_message_streamfactory_method_entry, ZEND_ACC_FINAL_CLASS);
zend_class_implements(phalcon_http_message_streamfactory_ce, 1, zephir_get_internal_ce(SL("psr\\http\\message\\streamfactoryinterface")));
return SUCCESS;
}
/**
* Create a new stream from a string.
*
* The stream SHOULD be created with a temporary resource.
*
* @param string $content String content with which to populate the stream.
*
* @return StreamInterface
*/
PHP_METHOD(Phalcon_Http_Message_StreamFactory, createStream) {
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *content_param = NULL, handle, _0, _1;
zval content;
zval *this_ptr = getThis();
ZVAL_UNDEF(&content);
ZVAL_UNDEF(&handle);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 0, 1, &content_param);
if (!content_param) {
ZEPHIR_INIT_VAR(&content);
ZVAL_STRING(&content, "");
} else {
if (UNEXPECTED(Z_TYPE_P(content_param) != IS_STRING && Z_TYPE_P(content_param) != IS_NULL)) {
zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'content' must be of the type string"));
RETURN_MM_NULL();
}
if (EXPECTED(Z_TYPE_P(content_param) == IS_STRING)) {
zephir_get_strval(&content, content_param);
} else {
ZEPHIR_INIT_VAR(&content);
ZVAL_EMPTY_STRING(&content);
}
}
ZEPHIR_INIT_VAR(&_0);
ZVAL_STRING(&_0, "php://temp");
ZEPHIR_INIT_VAR(&_1);
ZVAL_STRING(&_1, "r+b");
ZEPHIR_CALL_FUNCTION(&handle, "fopen", NULL, 87, &_0, &_1);
zephir_check_call_status();
if (UNEXPECTED(ZEPHIR_IS_FALSE_IDENTICAL(&handle))) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_http_message_exception_invalidargumentexception_ce, "Cannot write to file.", "/home/nikos/Work/niden/cphalcon/phalcon/Http/Message/StreamFactory.zep", 41);
return;
}
zephir_fwrite(NULL, &handle, &content);
ZEPHIR_CALL_FUNCTION(NULL, "rewind", NULL, 340, &handle);
zephir_check_call_status();
ZEPHIR_RETURN_CALL_METHOD(this_ptr, "createstreamfromresource", NULL, 341, &handle);
zephir_check_call_status();
RETURN_MM();
}
/**
* Create a stream from an existing file.
*
* The file MUST be opened using the given mode, which may be any mode
* supported by the `fopen` function.
*
* The `$filename` MAY be any string supported by `fopen()`.
*
* @param string $filename The filename or stream URI to use as basis of
* stream.
* @param string $mode The mode with which to open the underlying
* filename/stream.
*
* @return StreamInterface
*/
PHP_METHOD(Phalcon_Http_Message_StreamFactory, createStreamFromFile) {
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *filename_param = NULL, *mode_param = NULL;
zval filename, mode;
zval *this_ptr = getThis();
ZVAL_UNDEF(&filename);
ZVAL_UNDEF(&mode);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 1, &filename_param, &mode_param);
if (UNEXPECTED(Z_TYPE_P(filename_param) != IS_STRING && Z_TYPE_P(filename_param) != IS_NULL)) {
zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'filename' must be of the type string"));
RETURN_MM_NULL();
}
if (EXPECTED(Z_TYPE_P(filename_param) == IS_STRING)) {
zephir_get_strval(&filename, filename_param);
} else {
ZEPHIR_INIT_VAR(&filename);
ZVAL_EMPTY_STRING(&filename);
}
if (!mode_param) {
ZEPHIR_INIT_VAR(&mode);
ZVAL_STRING(&mode, "r+b");
} else {
if (UNEXPECTED(Z_TYPE_P(mode_param) != IS_STRING && Z_TYPE_P(mode_param) != IS_NULL)) {
zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'mode' must be of the type string"));
RETURN_MM_NULL();
}
if (EXPECTED(Z_TYPE_P(mode_param) == IS_STRING)) {
zephir_get_strval(&mode, mode_param);
} else {
ZEPHIR_INIT_VAR(&mode);
ZVAL_EMPTY_STRING(&mode);
}
}
object_init_ex(return_value, phalcon_http_message_stream_ce);
ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 43, &filename, &mode);
zephir_check_call_status();
RETURN_MM();
}
/**
* Create a new stream from an existing resource.
*
* The stream MUST be readable and may be writable.
*/
PHP_METHOD(Phalcon_Http_Message_StreamFactory, createStreamFromResource) {
zend_bool _0;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *phpResource, phpResource_sub, _1, _2;
zval *this_ptr = getThis();
ZVAL_UNDEF(&phpResource_sub);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_2);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &phpResource);
_0 = Z_TYPE_P(phpResource) != IS_RESOURCE;
if (!(_0)) {
ZEPHIR_CALL_FUNCTION(&_1, "get_resource_type", NULL, 89, phpResource);
zephir_check_call_status();
ZEPHIR_INIT_VAR(&_2);
ZVAL_STRING(&_2, "stream");
_0 = !ZEPHIR_IS_IDENTICAL(&_2, &_1);
}
if (UNEXPECTED(_0)) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_http_message_exception_invalidargumentexception_ce, "Invalid stream provided", "/home/nikos/Work/niden/cphalcon/phalcon/Http/Message/StreamFactory.zep", 79);
return;
}
object_init_ex(return_value, phalcon_http_message_stream_ce);
ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 43, phpResource);
zephir_check_call_status();
RETURN_MM();
}
|
218290.c | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* apr_uri.c: URI related utility things
*
*/
#include <stdlib.h>
#include "apu.h"
#include "apr.h"
#include "apr_general.h"
#include "apr_strings.h"
#define APR_WANT_STRFUNC
#include "apr_want.h"
#include "apr_uri.h"
typedef struct schemes_t schemes_t;
/** Structure to store various schemes and their default ports */
struct schemes_t {
/** The name of the scheme */
const char *name;
/** The default port for the scheme */
apr_port_t default_port;
};
/* Some WWW schemes and their default ports; this is basically /etc/services */
/* This will become global when the protocol abstraction comes */
/* As the schemes are searched by a linear search, */
/* they are sorted by their expected frequency */
static schemes_t schemes[] =
{
{"http", APR_URI_HTTP_DEFAULT_PORT},
{"ftp", APR_URI_FTP_DEFAULT_PORT},
{"https", APR_URI_HTTPS_DEFAULT_PORT},
{"gopher", APR_URI_GOPHER_DEFAULT_PORT},
{"ldap", APR_URI_LDAP_DEFAULT_PORT},
{"nntp", APR_URI_NNTP_DEFAULT_PORT},
{"snews", APR_URI_SNEWS_DEFAULT_PORT},
{"imap", APR_URI_IMAP_DEFAULT_PORT},
{"pop", APR_URI_POP_DEFAULT_PORT},
{"sip", APR_URI_SIP_DEFAULT_PORT},
{"rtsp", APR_URI_RTSP_DEFAULT_PORT},
{"wais", APR_URI_WAIS_DEFAULT_PORT},
{"z39.50r", APR_URI_WAIS_DEFAULT_PORT},
{"z39.50s", APR_URI_WAIS_DEFAULT_PORT},
{"prospero", APR_URI_PROSPERO_DEFAULT_PORT},
{"nfs", APR_URI_NFS_DEFAULT_PORT},
{"tip", APR_URI_TIP_DEFAULT_PORT},
{"acap", APR_URI_ACAP_DEFAULT_PORT},
{"telnet", APR_URI_TELNET_DEFAULT_PORT},
{"ssh", APR_URI_SSH_DEFAULT_PORT},
{ NULL, 0xFFFF } /* unknown port */
};
APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str)
{
schemes_t *scheme;
if (scheme_str) {
for (scheme = schemes; scheme->name != NULL; ++scheme) {
if (strcasecmp(scheme_str, scheme->name) == 0) {
return scheme->default_port;
}
}
}
return 0;
}
/* Unparse a apr_uri_t structure to an URI string.
* Optionally suppress the password for security reasons.
*/
APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p,
const apr_uri_t *uptr,
unsigned flags)
{
char *ret = "";
/* If suppressing the site part, omit both user name & scheme://hostname */
if (!(flags & APR_URI_UNP_OMITSITEPART)) {
/* Construct a "user:password@" string, honoring the passed
* APR_URI_UNP_ flags: */
if (uptr->user || uptr->password) {
ret = apr_pstrcat(p,
(uptr->user && !(flags & APR_URI_UNP_OMITUSER))
? uptr->user : "",
(uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD))
? ":" : "",
(uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD))
? ((flags & APR_URI_UNP_REVEALPASSWORD)
? uptr->password : "XXXXXXXX")
: "",
((uptr->user && !(flags & APR_URI_UNP_OMITUSER)) ||
(uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD)))
? "@" : "",
NULL);
}
/* Construct scheme://site string */
if (uptr->hostname) {
int is_default_port;
const char *lbrk = "", *rbrk = "";
if (strchr(uptr->hostname, ':')) { /* v6 literal */
lbrk = "[";
rbrk = "]";
}
is_default_port =
(uptr->port_str == NULL ||
uptr->port == 0 ||
uptr->port == apr_uri_port_of_scheme(uptr->scheme));
ret = apr_pstrcat(p, "//", ret, lbrk, uptr->hostname, rbrk,
is_default_port ? "" : ":",
is_default_port ? "" : uptr->port_str,
NULL);
}
if (uptr->scheme) {
ret = apr_pstrcat(p, uptr->scheme, ":", ret, NULL);
}
}
/* Should we suppress all path info? */
if (!(flags & APR_URI_UNP_OMITPATHINFO)) {
/* Append path, query and fragment strings: */
ret = apr_pstrcat(p,
ret,
(uptr->path)
? uptr->path : "",
(uptr->query && !(flags & APR_URI_UNP_OMITQUERY))
? "?" : "",
(uptr->query && !(flags & APR_URI_UNP_OMITQUERY))
? uptr->query : "",
(uptr->fragment && !(flags & APR_URI_UNP_OMITQUERY))
? "#" : NULL,
(uptr->fragment && !(flags & APR_URI_UNP_OMITQUERY))
? uptr->fragment : NULL,
NULL);
}
return ret;
}
/* Here is the hand-optimized parse_uri_components(). There are some wild
* tricks we could pull in assembly language that we don't pull here... like we
* can do word-at-time scans for delimiter characters using the same technique
* that fast memchr()s use. But that would be way non-portable. -djg
*/
/* We have a apr_table_t that we can index by character and it tells us if the
* character is one of the interesting delimiters. Note that we even get
* compares for NUL for free -- it's just another delimiter.
*/
#define T_COLON 0x01 /* ':' */
#define T_SLASH 0x02 /* '/' */
#define T_QUESTION 0x04 /* '?' */
#define T_HASH 0x08 /* '#' */
#define T_NUL 0x80 /* '\0' */
#if APR_CHARSET_EBCDIC
/* Delimiter table for the EBCDIC character set */
static const unsigned char uri_delims[256] = {
T_NUL,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,T_SLASH,0,0,0,0,0,0,0,0,0,0,0,0,0,T_QUESTION,
0,0,0,0,0,0,0,0,0,0,T_COLON,T_HASH,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
#else
/* Delimiter table for the ASCII character set */
static const unsigned char uri_delims[256] = {
T_NUL,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,T_HASH,0,0,0,0,0,0,0,0,0,0,0,T_SLASH,
0,0,0,0,0,0,0,0,0,0,T_COLON,0,0,0,0,T_QUESTION,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
#endif
/* it works like this:
if (uri_delims[ch] & NOTEND_foobar) {
then we're not at a delimiter for foobar
}
*/
/* Note that we optimize the scheme scanning here, we cheat and let the
* compiler know that it doesn't have to do the & masking.
*/
#define NOTEND_SCHEME (0xff)
#define NOTEND_HOSTINFO (T_SLASH | T_QUESTION | T_HASH | T_NUL)
#define NOTEND_PATH (T_QUESTION | T_HASH | T_NUL)
/* parse_uri_components():
* Parse a given URI, fill in all supplied fields of a uri_components
* structure. This eliminates the necessity of extracting host, port,
* path, query info repeatedly in the modules.
* Side effects:
* - fills in fields of uri_components *uptr
* - none on any of the r->* fields
*/
APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri,
apr_uri_t *uptr)
{
const char *s;
const char *s1;
const char *hostinfo;
char *endstr;
int port;
int v6_offset1 = 0, v6_offset2 = 0;
/* Initialize the structure. parse_uri() and parse_uri_components()
* can be called more than once per request.
*/
memset (uptr, '\0', sizeof(*uptr));
uptr->is_initialized = 1;
/* We assume the processor has a branch predictor like most --
* it assumes forward branches are untaken and backwards are taken. That's
* the reason for the gotos. -djg
*/
if (uri[0] == '/') {
/* RFC2396 #4.3 says that two leading slashes mean we have an
* authority component, not a path! Fixing this looks scary
* with the gotos here. But if the existing logic is valid,
* then presumably a goto pointing to deal_with_authority works.
*
* RFC2396 describes this as resolving an ambiguity. In the
* case of three or more slashes there would seem to be no
* ambiguity, so it is a path after all.
*/
if (uri[1] == '/' && uri[2] != '/') {
s = uri + 2 ;
goto deal_with_authority ;
}
deal_with_path:
/* we expect uri to point to first character of path ... remember
* that the path could be empty -- http://foobar?query for example
*/
s = uri;
while ((uri_delims[*(unsigned char *)s] & NOTEND_PATH) == 0) {
++s;
}
if (s != uri) {
uptr->path = apr_pstrmemdup(p, uri, s - uri);
}
if (*s == 0) {
return APR_SUCCESS;
}
if (*s == '?') {
++s;
s1 = strchr(s, '#');
if (s1) {
uptr->fragment = apr_pstrdup(p, s1 + 1);
uptr->query = apr_pstrmemdup(p, s, s1 - s);
}
else {
uptr->query = apr_pstrdup(p, s);
}
return APR_SUCCESS;
}
/* otherwise it's a fragment */
uptr->fragment = apr_pstrdup(p, s + 1);
return APR_SUCCESS;
}
/* find the scheme: */
s = uri;
while ((uri_delims[*(unsigned char *)s] & NOTEND_SCHEME) == 0) {
++s;
}
/* scheme must be non-empty and followed by : */
if (s == uri || s[0] != ':') {
goto deal_with_path; /* backwards predicted taken! */
}
uptr->scheme = apr_pstrmemdup(p, uri, s - uri);
if (s[1] != '/' || s[2] != '/') {
uri = s + 1;
goto deal_with_path;
}
s += 3;
deal_with_authority:
hostinfo = s;
while ((uri_delims[*(unsigned char *)s] & NOTEND_HOSTINFO) == 0) {
++s;
}
uri = s; /* whatever follows hostinfo is start of uri */
uptr->hostinfo = apr_pstrmemdup(p, hostinfo, uri - hostinfo);
/* If there's a username:password@host:port, the @ we want is the last @...
* too bad there's no memrchr()... For the C purists, note that hostinfo
* is definately not the first character of the original uri so therefore
* &hostinfo[-1] < &hostinfo[0] ... and this loop is valid C.
*/
do {
--s;
} while (s >= hostinfo && *s != '@');
if (s < hostinfo) {
/* again we want the common case to be fall through */
deal_with_host:
/* We expect hostinfo to point to the first character of
* the hostname. If there's a port it is the first colon,
* except with IPv6.
*/
if (*hostinfo == '[') {
v6_offset1 = 1;
v6_offset2 = 2;
s = memchr(hostinfo, ']', uri - hostinfo);
if (s == NULL) {
return APR_EGENERAL;
}
if (*++s != ':') {
s = NULL; /* no port */
}
}
else {
s = memchr(hostinfo, ':', uri - hostinfo);
}
if (s == NULL) {
/* we expect the common case to have no port */
uptr->hostname = apr_pstrmemdup(p,
hostinfo + v6_offset1,
uri - hostinfo - v6_offset2);
goto deal_with_path;
}
uptr->hostname = apr_pstrmemdup(p,
hostinfo + v6_offset1,
s - hostinfo - v6_offset2);
++s;
uptr->port_str = apr_pstrmemdup(p, s, uri - s);
if (uri != s) {
port = strtol(uptr->port_str, &endstr, 10);
uptr->port = port;
if (*endstr == '\0') {
goto deal_with_path;
}
/* Invalid characters after ':' found */
return APR_EGENERAL;
}
uptr->port = apr_uri_port_of_scheme(uptr->scheme);
goto deal_with_path;
}
/* first colon delimits username:password */
s1 = memchr(hostinfo, ':', s - hostinfo);
if (s1) {
uptr->user = apr_pstrmemdup(p, hostinfo, s1 - hostinfo);
++s1;
uptr->password = apr_pstrmemdup(p, s1, s - s1);
}
else {
uptr->user = apr_pstrmemdup(p, hostinfo, s - hostinfo);
}
hostinfo = s + 1;
goto deal_with_host;
}
/* Special case for CONNECT parsing: it comes with the hostinfo part only */
/* See the INTERNET-DRAFT document "Tunneling SSL Through a WWW Proxy"
* currently at http://www.mcom.com/newsref/std/tunneling_ssl.html
* for the format of the "CONNECT host:port HTTP/1.0" request
*/
APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p,
const char *hostinfo,
apr_uri_t *uptr)
{
const char *s;
char *endstr;
const char *rsb;
int v6_offset1 = 0;
/* Initialize the structure. parse_uri() and parse_uri_components()
* can be called more than once per request.
*/
memset(uptr, '\0', sizeof(*uptr));
uptr->is_initialized = 1;
uptr->hostinfo = apr_pstrdup(p, hostinfo);
/* We expect hostinfo to point to the first character of
* the hostname. There must be a port, separated by a colon
*/
if (*hostinfo == '[') {
if ((rsb = strchr(hostinfo, ']')) == NULL ||
*(rsb + 1) != ':') {
return APR_EGENERAL;
}
/* literal IPv6 address */
s = rsb + 1;
++hostinfo;
v6_offset1 = 1;
}
else {
s = strchr(hostinfo, ':');
}
if (s == NULL) {
return APR_EGENERAL;
}
uptr->hostname = apr_pstrndup(p, hostinfo, s - hostinfo - v6_offset1);
++s;
uptr->port_str = apr_pstrdup(p, s);
if (*s != '\0') {
uptr->port = (unsigned short) strtol(uptr->port_str, &endstr, 10);
if (*endstr == '\0') {
return APR_SUCCESS;
}
/* Invalid characters after ':' found */
}
return APR_EGENERAL;
}
|
791641.c | //------------------------------------------------------------------------------
// GB_to_nonhyper: convert a matrix to non-hypersparse form
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// On input, the matrix may have shallow A->p and A->h content; it is safely
// removed. On output, the matrix is always non-hypersparse (even if out of
// memory). If the input matrix is hypersparse, it is given a new A->p that is
// not shallow. If the input matrix is already non-hypersparse, nothing is
// changed (and in that case A->p remains shallow on output if shallow on
// input). The A->x and A->i content is not changed; it remains in whatever
// shallow/non-shallow state that it had on input).
// If an out-of-memory condition occurs, all content of the matrix is cleared.
// The input matrix may be jumbled; this is not an error condition.
#include "GB.h"
GB_PUBLIC // accessed by the MATLAB tests in GraphBLAS/Test only
GrB_Info GB_to_nonhyper // convert a matrix to non-hypersparse
(
GrB_Matrix A, // matrix to convert to non-hypersparse
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT_MATRIX_OK_OR_JUMBLED (A, "A being converted to nonhyper", GB0) ;
ASSERT (GB_ZOMBIES_OK (A)) ;
//--------------------------------------------------------------------------
// convert A to non-hypersparse form
//--------------------------------------------------------------------------
if (A->is_hyper)
{
//----------------------------------------------------------------------
// determine the number of threads to use
//----------------------------------------------------------------------
int64_t n = A->vdim ;
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (n, chunk, nthreads_max) ;
int ntasks = (nthreads == 1) ? 1 : (8 * nthreads) ;
ntasks = GB_IMIN (ntasks, n) ;
ntasks = GB_IMAX (ntasks, 1) ;
//----------------------------------------------------------------------
// allocate the new Ap array, of size n+1
//----------------------------------------------------------------------
int64_t *GB_RESTRICT Ap_new ;
GB_MALLOC_MEMORY (Ap_new, n+1, sizeof (int64_t)) ;
if (Ap_new == NULL)
{
// out of memory
A->is_hyper = false ; // A is non-hypersparse, but invalid
GB_PHIX_FREE (A) ;
return (GB_OUT_OF_MEMORY) ;
}
#ifdef GB_DEBUG
// to ensure all values of Ap_new are assigned below.
for (int64_t j = 0 ; j <= n ; j++) Ap_new [j] = -99999 ;
#endif
//----------------------------------------------------------------------
// get the old hyperlist
//----------------------------------------------------------------------
int64_t nvec = A->nvec ; // # of vectors in Ah_old
int64_t *GB_RESTRICT Ap_old = A->p ; // size nvec+1
int64_t *GB_RESTRICT Ah_old = A->h ; // size nvec
int64_t nvec_nonempty = 0 ; // recompute A->nvec_nonempty
int64_t anz = GB_NNZ (A) ;
//----------------------------------------------------------------------
// construct the new vector pointers
//----------------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nvec_nonempty)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t jstart, jend, my_nvec_nonempty = 0 ;
GB_PARTITION (jstart, jend, n, tid, ntasks) ;
ASSERT (0 <= jstart && jstart <= jend && jend <= n) ;
// task tid computes Ap_new [jstart:jend-1] from Ap_old, Ah_old.
// GB_SPLIT_BINARY_SEARCH of Ah_old [0..nvec-1] for jstart:
// If found is true then Ah_old [k] == jstart.
// If found is false, and nvec > 0 then
// Ah_old [0 ... k-1] < jstart < Ah_old [k ... nvec-1]
// Whether or not i is found, if nvec > 0
// Ah_old [0 ... k-1] < jstart <= Ah_old [k ... nvec-1]
// If nvec == 0, then k == 0 and found will be false. In this
// case, jstart cannot be compared with any content of Ah_old,
// since Ah_old is completely empty (Ah_old [0] is invalid).
int64_t k = 0, pright = nvec-1 ;
bool found ;
GB_SPLIT_BINARY_SEARCH (jstart, Ah_old, k, pright, found) ;
ASSERT (k >= 0 && k <= nvec) ;
ASSERT (GB_IMPLIES (nvec == 0, !found && k == 0)) ;
ASSERT (GB_IMPLIES (found, jstart == Ah_old [k])) ;
ASSERT (GB_IMPLIES (!found && k < nvec, jstart < Ah_old [k])) ;
// Let jk = Ah_old [k], jlast = Ah_old [k-1], and pk = Ah_old [k].
// Then Ap_new [jlast+1:jk] must be set to pk. This must be done
// for all k = 0:nvec-1. In addition, the last vector k=nvec-1
// must be terminated by setting Ap_new [jk+1:n-1] to Ap_old [nvec].
// A task owns the kth vector if jk is in jstart:jend-1, inclusive.
// It counts all non-empty vectors that it owns. However, the task
// must also set Ap_new [...] = pk for any jlast+1:jk that overlaps
// jstart:jend-1, even if it does not own that particular vector k.
// This happens only at the tail end of jstart:jend-1.
int64_t jlast = (k == 0) ? (-1) : Ah_old [k-1] ;
jlast = GB_IMAX (jstart-1, jlast) ;
bool done = false ;
for ( ; k <= nvec && !done ; k++)
{
//--------------------------------------------------------------
// get the kth vector in Ah_old, which is vector index jk.
//--------------------------------------------------------------
int64_t jk = (k < nvec) ? Ah_old [k] : n ;
int64_t pk = (k < nvec) ? Ap_old [k] : anz ;
//--------------------------------------------------------------
// determine if this task owns jk
//--------------------------------------------------------------
int64_t jfin ;
if (jk >= jend)
{
// This is the last iteration for this task. This task
// does not own the kth vector. However, it does own the
// vector indices jlast+1:jend-1, and these vectors must
// be handled by this task.
jfin = jend - 1 ;
done = true ;
}
else
{
// This task owns the kth vector, which is vector index jk.
// Ap must be set to pk for all vector indices jlast+1:jk.
jfin = jk ;
ASSERT (k >= 0 && k < nvec && nvec > 0) ;
if (pk < Ap_old [k+1]) my_nvec_nonempty++ ;
}
//--------------------------------------------------------------
// set Ap_new for this vector
//--------------------------------------------------------------
// Ap_new [jlast+1:jk] must be set to pk. This tasks handles
// the intersection of jlast+1:jk with jstart:jend-1.
for (int64_t j = jlast+1 ; j <= jfin ; j++)
{
Ap_new [j] = pk ;
}
//--------------------------------------------------------------
// keep track of the prior vector index
//--------------------------------------------------------------
jlast = jk ;
}
nvec_nonempty += my_nvec_nonempty ;
//------------------------------------------------------------------
// no task owns Ap_new [n] so it is set by the last task
//------------------------------------------------------------------
if (tid == ntasks-1)
{
ASSERT (jend == n) ;
Ap_new [n] = anz ;
}
}
// free the old A->p and A->h hyperlist content.
// this clears A->nvec_nonempty so it must be restored below.
GB_ph_free (A) ;
// transplant the new vector pointers; matrix is no longer hypersparse
A->p = Ap_new ;
A->h = NULL ;
A->is_hyper = false ;
A->nvec = n ;
A->nvec_nonempty = nvec_nonempty ;
A->plen = n ;
A->p_shallow = false ;
A->h_shallow = false ;
A->magic = GB_MAGIC ;
ASSERT (anz == GB_NNZ (A)) ;
ASSERT (A->nvec_nonempty == GB_nvec_nonempty (A, Context)) ;
}
//--------------------------------------------------------------------------
// A is now in non-hypersparse form
//--------------------------------------------------------------------------
ASSERT_MATRIX_OK_OR_JUMBLED (A, "A converted to nonhypersparse", GB0) ;
ASSERT (!(A->is_hyper)) ;
return (GrB_SUCCESS) ;
}
|
81325.c | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// This is meant to be `LD_PRELOAD`ed into `yum` or `dnf`. We intercept the
// `rename` glibc call, and check whether the destination path exists under
// `FS_IMAGE_SHADOWED_PATHS_ROOT`. If the shadowed path does exist, change
// the destination path of the `rename` to overwrite it. If the shadowed
// path does not exist, or the environment variable is not set, perform the
// unmodified `rename`.
//
// Caveats:
//
// - This is implemented in a way that is asynchronous signal-unsafe,
// whereas `rename (3)` is supposed to be AS-safe according to POSIX.
//
// We don't bother with an AS-safe implementation because of its cost,
// and because the risk seems low. Specifically:
// * Both `yum` and `dnf` call out to `rpm` to do package installation.
// * The `dnf` codebase has no mentions of `rename` at all.
// * `yum` has some `os.rename` calls, but it is in Python, and as such
// it's almost impossible to run anything in a context that requires
// async-signal safety.
// * `rpm` calls `rename (3)` through `fsmRename`, which in its current
// incarnation has several AS-unsafe calls.
//
// It is technically possible that some dependency of either package
// manager uses `rename` in a signal handler for some kind of last-ditch
// cleanup thing. However, it is not very plausible because libraries
// should not install signal handlers. Moreover, we're not too concerned
// about breaking error handling, since we expect image builds to
// generally be on the "gold path" where programs exit cleanly.
//
// While the risk is low, the cost is considerable:
// * One can replace uses of `malloc` and `free` by stack buffers of
// `PATH_MAX` in size, and lose the `strndup`. This has some
// downsides since it may artificially limit path length in some
// settings, but it's probably good enough.
// * `realpath` and `canonicalize_file_name` are AS-unsafe because of
// heap accesses. I suspect that `realpath` with a pre-allocated
// buffer might be fine (same caveat: artificially limiting the path
// length), but the docs don't explicitly promise it.
// * Reimplementing `realpath` with static buffers is a big pain.
// * Losing the dependency on `snprintf` is also a pain.
// * Removing the `fprintf` reduces debuggability.
// On net, an AS-safe implementation would be far longer and would require
// a much higher test burden.
//
// - This lacks support for directories because we don't currently shadow
// directories, and `yum` / `dnf` do not (and cannot) use `rename` for
// overwriting directories.
//
// - About logging & error handling: we log to stderr only when we alter
// the `rename`. Many "error" cases in the code is actually just an
// indication that we shouldn't be interposing. There are also a few
// "this should never happen" conditions, where we would still get an
// error message from `yum` when it fails to overwrite the read-only
// bind mount.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <dlfcn.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // With _GNU_SOURCE gives us the GNU `basename`
#include <sys/stat.h>
#ifdef __cplusplus
extern "C" {
#endif
static char* g_shadowed_paths_root = NULL;
static size_t g_len_shadowed_paths_root = 0;
__attribute__((__constructor__)) static void __init__() {
// Grabbing the root for shadowed paths from the environment is less
// robust than hardcoding it (something can unset the env var), but in
// our current usage, there is nothing between `yum-dnf-from-snapshot`
// and `yum` or `dnf` that would do that. And we have tests.
//
// The upside is that it makes our tests cleaner, and eliminates the
// need to rebuild the `.so` (and with it, the BA) to change the root.
//
// As far as security, we're an `LD_PRELOAD` library, so we already
// trust the environment roughly 100%.
g_shadowed_paths_root = getenv("FS_IMAGE_SHADOWED_PATHS_ROOT");
if (g_shadowed_paths_root) {
g_len_shadowed_paths_root = strlen(g_shadowed_paths_root);
}
}
// If the parent directory of `path` exists, and the environment variable
// `FS_IMAGE_SHADOWED_PATHS_ROOT` is set, allocates and returns a
// NUL-terminated canonical "shadowed original" for `path`, under that root.
//
// Returns NULL on error.
//
// This is not `static` so our tests can see it. In production builds, it
// gets hidden via `-fvisibility=hidden`.
char* get_shadowed_original(const char* path) {
// No shadow paths root? Don't alter any `rename` calls.
if (!g_shadowed_paths_root) {
return NULL;
}
const char* base = basename(path);
const int len_base = strlen(base);
const int len_path = strlen(path);
char* dirname = (len_base == len_path)
? strdup(".") // Otherwise path == "a" would make bad dirname == ""
: strndup(path, len_path - len_base); // Keep trailing / for path == /a
if (!dirname) {
return NULL;
}
// `rename` does not follow symlinks in the last component
char* realdir = canonicalize_file_name(dirname);
char* orig = NULL;
if (realdir && realdir[0] == '/') {
const size_t len_orig =
g_len_shadowed_paths_root + strlen(realdir) + 1 + len_base;
orig = malloc(len_orig + 1);
if (orig) {
snprintf(
orig, len_orig + 1, "%s%s%s%s",
g_shadowed_paths_root,
realdir,
// Don't emit an extra / for `realdir == "/"`
(realdir[1] == '\0' ? "" : "/"),
base
);
}
}
if (realdir) {
free(realdir);
}
free(dirname);
return orig;
}
// For us to decide to redirect a `rename`'s `new` to its shadow location,
// a few conditions have to be met:
// - `new` has to exist and not be a directory (see top doc)
// - `new` must not be the same inode as `old` (inline comment)
// - the shadow of `new` must exist and not be a directory
//
// If all conditions are met, return an allocated path to the shadow of
// `new`, to be `free`d by the caller. Otherwise, return NULL.
//
// This is not `static` so our tests can see it. In production builds, it
// gets hidden via `-fvisibility=hidden`.
char* get_shadowed_rename_dest(const char* old, const char* new) {
// We don't support shadowing directories.
struct stat st;
if (0 != lstat(new, &st)) {
return NULL;
}
if (S_ISDIR(st.st_mode)) {
return NULL;
}
struct stat st_old;
if (0 != lstat(old, &st_old)) {
return NULL;
}
// `rename` should be a no-op if `old` and `new` are the same. However,
// if we were to rewrite the destination path, then `rename` would fail
// because `old`, a shadowed path, would be a read-only bind mount.
if (st.st_ino == st_old.st_ino && st.st_dev == st_old.st_dev) {
return NULL;
}
char* replaced_new = get_shadowed_original(new);
if (!replaced_new) {
return NULL;
}
if (0 != lstat(replaced_new, &st) || S_ISDIR(st.st_mode)) {
free(replaced_new);
return NULL;
}
return replaced_new;
}
__attribute__ ((visibility ("default")))
int rename(const char *old, const char *new)
{
static int (*memoized_real_rename)(const char *, const char *) = NULL;
// In a multi-threaded environment this is subject to a race, so use
// GCC/CLANG an atomic load/stores to avoid pointer shear.
int (*real_rename)(const char *, const char *) = NULL;
__atomic_load(&memoized_real_rename, &real_rename, __ATOMIC_ACQUIRE);
if (!real_rename) {
real_rename = dlsym(RTLD_NEXT, "rename");
// We don't mind if several threads race to store a value here, it
// would presumably be the same anyway.
__atomic_store(&memoized_real_rename, &real_rename, __ATOMIC_RELEASE);
}
char* original = get_shadowed_rename_dest(old, new);
int ret;
if (original) {
fprintf(
stderr,
"`rename(%s, %s)` will replace shadowed original `%s`\n",
old, new, original
);
ret = real_rename(old, original);
free(original);
} else {
ret = real_rename(old, new);
}
return ret;
}
#ifdef __cplusplus
}
#endif
|
328767.c | // Test that fork fails gracefully.
// Tiny executable so that the limit can be filling the proc table.
#include "types.h"
#include "stat.h"
#include "user.h"
#define N 1000
#define FAIL_STATUS 0
#define PASS_STATUS 1
void
printf(int fd, const char *s, ...)
{
write(fd, s, strlen(s));
}
void
forktest(void)
{
int n, pid;
int status;
printf(1, "fork test\n");
for(n=0; n<N; n++){
pid = fork();
if(pid < 0)
break;
if(pid == 0)
exit(PASS_STATUS);
}
if(n == N){
printf(1, "fork claimed to work N times!\n", N);
exit(FAIL_STATUS);
}
for(; n > 0; n--){
if(wait(&status) < 0){
printf(1, "wait stopped early\n");
exit(FAIL_STATUS);
}
}
if(wait(&status) != -1){
printf(1, "wait got too many\n");
exit(FAIL_STATUS);
}
printf(1, "fork test OK\n");
}
int
main(void)
{
forktest();
exit(PASS_STATUS);
}
|
995352.c | /** @file
*
* Copyright (c) 2017, Linaro, Ltd. All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*
**/
#include <Uefi.h>
#include <IndustryStandard/Acpi.h>
#include <libfdt.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/DevicePathLib.h>
#include <Library/HiiLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiDriverEntryPoint.h>
#include <Library/UefiLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Protocol/AcpiTable.h>
#include <Protocol/AcpiSystemDescriptionTable.h>
#include "ConsolePrefDxe.h"
#define SPCR_SIG EFI_ACPI_2_0_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_SIGNATURE
extern UINT8 ConsolePrefHiiBin[];
extern UINT8 ConsolePrefDxeStrings[];
typedef struct {
VENDOR_DEVICE_PATH VendorDevicePath;
EFI_DEVICE_PATH_PROTOCOL End;
} HII_VENDOR_DEVICE_PATH;
STATIC HII_VENDOR_DEVICE_PATH mConsolePrefDxeVendorDevicePath = {
{
{
HARDWARE_DEVICE_PATH,
HW_VENDOR_DP,
{
(UINT8) (sizeof (VENDOR_DEVICE_PATH)),
(UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
}
},
CONSOLE_PREF_FORMSET_GUID
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
(UINT8) (END_DEVICE_PATH_LENGTH),
(UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
}
}
};
STATIC EFI_EVENT mReadyToBootEvent;
STATIC
EFI_STATUS
InstallHiiPages (
VOID
)
{
EFI_STATUS Status;
EFI_HII_HANDLE HiiHandle;
EFI_HANDLE DriverHandle;
DriverHandle = NULL;
Status = gBS->InstallMultipleProtocolInterfaces (&DriverHandle,
&gEfiDevicePathProtocolGuid,
&mConsolePrefDxeVendorDevicePath,
NULL);
if (EFI_ERROR (Status)) {
return Status;
}
HiiHandle = HiiAddPackages (&gConsolePrefFormSetGuid,
DriverHandle,
ConsolePrefDxeStrings,
ConsolePrefHiiBin,
NULL);
if (HiiHandle == NULL) {
gBS->UninstallMultipleProtocolInterfaces (DriverHandle,
&gEfiDevicePathProtocolGuid,
&mConsolePrefDxeVendorDevicePath,
NULL);
return EFI_OUT_OF_RESOURCES;
}
return EFI_SUCCESS;
}
STATIC
VOID
RemoveDtStdoutPath (
VOID
)
{
VOID *Dtb;
INT32 Node;
INT32 Error;
EFI_STATUS Status;
Status = EfiGetSystemConfigurationTable (&gFdtTableGuid, &Dtb);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "%a: could not retrieve DT blob - %r\n", __FUNCTION__,
Status));
return;
}
Node = fdt_path_offset (Dtb, "/chosen");
if (Node < 0) {
return;
}
Error = fdt_delprop (Dtb, Node, "stdout-path");
if (Error) {
DEBUG ((DEBUG_INFO, "%a: Failed to delete 'stdout-path' property: %a\n",
__FUNCTION__, fdt_strerror (Error)));
}
}
STATIC
VOID
RemoveSpcrTable (
VOID
)
{
EFI_ACPI_SDT_PROTOCOL *Sdt;
EFI_ACPI_TABLE_PROTOCOL *AcpiTable;
EFI_STATUS Status;
UINTN TableIndex;
EFI_ACPI_SDT_HEADER *TableHeader;
EFI_ACPI_TABLE_VERSION TableVersion;
UINTN TableKey;
Status = gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, NULL,
(VOID **)&AcpiTable);
if (EFI_ERROR (Status)) {
return;
}
Status = gBS->LocateProtocol (&gEfiAcpiSdtProtocolGuid, NULL, (VOID **)&Sdt);
if (EFI_ERROR (Status)) {
return;
}
TableIndex = 0;
TableKey = 0;
TableHeader = NULL;
do {
Status = Sdt->GetAcpiTable (TableIndex++, &TableHeader, &TableVersion,
&TableKey);
if (EFI_ERROR (Status)) {
break;
}
if (TableHeader->Signature != SPCR_SIG) {
continue;
}
Status = AcpiTable->UninstallAcpiTable (AcpiTable, TableKey);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_WARN, "%a: failed to uninstall SPCR table - %r\n",
__FUNCTION__, Status));
}
break;
} while (TRUE);
}
STATIC
VOID
OnReadyToBoot (
IN EFI_EVENT Event,
IN VOID *Context
)
{
CONSOLE_PREF_VARSTORE_DATA ConsolePref;
UINTN BufferSize;
EFI_STATUS Status;
VOID *Gop;
BufferSize = sizeof (ConsolePref);
Status = gRT->GetVariable (CONSOLE_PREF_VARIABLE_NAME,
&gConsolePrefFormSetGuid, NULL, &BufferSize, &ConsolePref);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR,
"%a: variable '%s' could not be read - bailing!\n", __FUNCTION__,
CONSOLE_PREF_VARIABLE_NAME));
return;
}
if (ConsolePref.Console == CONSOLE_PREF_SERIAL) {
DEBUG ((DEBUG_INFO,
"%a: serial console preferred - doing nothing\n", __FUNCTION__));
return;
}
//
// Check if any GOP instances exist: if so, disable stdout-path and SPCR
//
Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, &Gop);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO,
"%a: no GOP instances found - doing nothing (%r)\n", __FUNCTION__,
Status));
return;
}
RemoveDtStdoutPath ();
RemoveSpcrTable ();
}
/**
The entry point for ConsolePrefDxe driver.
@param[in] ImageHandle The image handle of the driver.
@param[in] SystemTable The system table.
@retval EFI_ALREADY_STARTED The driver already exists in system.
@retval EFI_OUT_OF_RESOURCES Fail to execute entry point due to lack of
resources.
@retval EFI_SUCCES All the related protocols are installed on
the driver.
**/
EFI_STATUS
EFIAPI
ConsolePrefDxeEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
CONSOLE_PREF_VARSTORE_DATA ConsolePref;
UINTN BufferSize;
//
// Get the current console preference from the ConsolePref variable.
//
BufferSize = sizeof (ConsolePref);
Status = gRT->GetVariable (CONSOLE_PREF_VARIABLE_NAME,
&gConsolePrefFormSetGuid, NULL, &BufferSize, &ConsolePref);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO,
"%a: no console preference found, defaulting to graphical\n",
__FUNCTION__));
ConsolePref.Console = CONSOLE_PREF_GRAPHICAL;
}
if (!EFI_ERROR (Status) &&
ConsolePref.Console != CONSOLE_PREF_GRAPHICAL &&
ConsolePref.Console != CONSOLE_PREF_SERIAL) {
DEBUG ((DEBUG_WARN, "%a: invalid value for %s, defaulting to graphical\n",
__FUNCTION__, CONSOLE_PREF_VARIABLE_NAME));
ConsolePref.Console = CONSOLE_PREF_GRAPHICAL;
Status = EFI_INVALID_PARAMETER; // trigger setvar below
}
//
// Write the newly selected value back to the variable store.
//
if (EFI_ERROR (Status)) {
ZeroMem (&ConsolePref.Reserved, sizeof (ConsolePref.Reserved));
Status = gRT->SetVariable (CONSOLE_PREF_VARIABLE_NAME,
&gConsolePrefFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (ConsolePref), &ConsolePref);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "%a: gRT->SetVariable () failed - %r\n",
__FUNCTION__, Status));
return Status;
}
}
Status = gBS->CreateEventEx (EVT_NOTIFY_SIGNAL, TPL_CALLBACK,
OnReadyToBoot, NULL, &gEfiEventReadyToBootGuid,
&mReadyToBootEvent);
ASSERT_EFI_ERROR (Status);
return InstallHiiPages ();
}
|
640578.c | /****************************************************************************
* arch/risc-v/src/esp32c3/esp32c3_wireless.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/kmalloc.h>
#include <semaphore.h>
#include <debug.h>
#include "riscv_internal.h"
#include "hardware/esp32c3_system.h"
#include "hardware/esp32c3_soc.h"
#include "hardware/esp32c3_syscon.h"
#include "hardware/esp32c3_efuse.h"
#include "esp32c3_wireless.h"
#include "esp32c3.h"
#include "esp32c3_irq.h"
#include "esp32c3_attr.h"
#include "esp32c3_wireless.h"
#include "espidf_wifi.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define MAC_ADDR0_REG EFUSE_RD_MAC_SPI_SYS_0_REG
#define MAC_ADDR1_REG EFUSE_RD_MAC_SPI_SYS_1_REG
/* Software Interrupt */
#define SWI_IRQ ESP32C3_IRQ_FROM_CPU_INT0
#define SWI_PERIPH ESP32C3_PERIPH_FROM_CPU_INT0
/****************************************************************************
* Private Types
****************************************************************************/
/* ESP32-C3 Wireless Private Data */
struct esp32c3_wl_priv_s
{
volatile int ref; /* Reference count */
int cpuint; /* CPU interrupt assigned to SWI */
struct list_node sc_list; /* Semaphore cache list */
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
static inline void phy_digital_regs_store(void);
static inline void phy_digital_regs_load(void);
static void esp32c3_phy_enable_clock(void);
static void esp32c3_phy_disable_clock(void);
/****************************************************************************
* Extern Functions declaration
****************************************************************************/
#ifdef CONFIG_ESP32C3_BLE
extern void coex_pti_v2(void);
#endif
/****************************************************************************
* Private Data
****************************************************************************/
/* Wi-Fi sleep private data */
static uint32_t g_phy_clk_en_cnt;
/* Reference count of enabling PHY */
static uint8_t g_phy_access_ref;
/* Memory to store PHY digital registers */
static uint32_t *g_phy_digital_regs_mem = NULL;
/* Indicate PHY is calibrated or not */
static bool g_is_phy_calibrated = false;
static struct esp32c3_wl_priv_s g_esp32c3_wl_priv;
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: phy_digital_regs_store
*
* Description:
* Store PHY digital registers.
*
****************************************************************************/
static inline void phy_digital_regs_store(void)
{
if (g_phy_digital_regs_mem == NULL)
{
g_phy_digital_regs_mem = (uint32_t *)
kmm_malloc(SOC_PHY_DIG_REGS_MEM_SIZE);
}
DEBUGASSERT(g_phy_digital_regs_mem != NULL);
phy_dig_reg_backup(true, g_phy_digital_regs_mem);
}
/****************************************************************************
* Name: phy_digital_regs_load
*
* Description:
* Load PHY digital registers.
*
****************************************************************************/
static inline void phy_digital_regs_load(void)
{
if (g_phy_digital_regs_mem != NULL)
{
phy_dig_reg_backup(false, g_phy_digital_regs_mem);
}
}
/****************************************************************************
* Name: esp32c3_phy_enable_clock
*
* Description:
* Enable PHY hardware clock
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void esp32c3_phy_enable_clock(void)
{
irqstate_t flags;
flags = enter_critical_section();
if (g_phy_clk_en_cnt == 0)
{
modifyreg32(SYSTEM_WIFI_CLK_EN_REG, 0,
SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M);
}
g_phy_clk_en_cnt++;
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_phy_disable_clock
*
* Description:
* Disable PHY hardware clock
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void esp32c3_phy_disable_clock(void)
{
irqstate_t flags;
flags = enter_critical_section();
if (g_phy_clk_en_cnt)
{
g_phy_clk_en_cnt--;
if (!g_phy_clk_en_cnt)
{
modifyreg32(SYSTEM_WIFI_CLK_EN_REG,
SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M,
0);
}
}
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_wl_swi_irq
*
* Description:
* Wireless software interrupt callback function.
*
* Parameters:
* cpuint - CPU interrupt index
* context - Context data from the ISR
* arg - NULL
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
static int esp32c3_wl_swi_irq(int irq, void *context, void *arg)
{
int i;
int ret;
struct esp32c3_wl_semcache_s *sc;
struct esp32c3_wl_semcache_s *tmp;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
putreg32(0, SYSTEM_CPU_INTR_FROM_CPU_0_REG);
list_for_every_entry_safe(&priv->sc_list, sc, tmp,
struct esp32c3_wl_semcache_s, node)
{
for (i = 0; i < sc->count; i++)
{
ret = nxsem_post(sc->sem);
if (ret < 0)
{
wlerr("ERROR: Failed to post sem ret=%d\n", ret);
}
}
sc->count = 0;
list_delete(&sc->node);
}
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: esp32c3_phy_disable
*
* Description:
* Deinitialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_disable(void)
{
irqstate_t flags;
flags = enter_critical_section();
g_phy_access_ref--;
if (g_phy_access_ref == 0)
{
/* Store PHY digital register. */
phy_digital_regs_store();
/* Disable PHY and RF. */
phy_close_rf();
phy_xpd_tsens();
/* Disable Wi-Fi/BT common peripheral clock.
* Do not disable clock for hardware RNG.
*/
esp32c3_phy_disable_clock();
}
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_phy_enable
*
* Description:
* Initialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_enable(void)
{
static bool debug = false;
irqstate_t flags;
esp_phy_calibration_data_t *cal_data;
char *phy_version = get_phy_version_str();
if (debug == false)
{
debug = true;
wlinfo("phy_version %s\n", phy_version);
}
cal_data = kmm_zalloc(sizeof(esp_phy_calibration_data_t));
if (!cal_data)
{
wlerr("ERROR: Failed to kmm_zalloc");
DEBUGASSERT(0);
}
flags = enter_critical_section();
if (g_phy_access_ref == 0)
{
esp32c3_phy_enable_clock();
if (g_is_phy_calibrated == false)
{
register_chipv7_phy(&phy_init_data, cal_data, PHY_RF_CAL_FULL);
g_is_phy_calibrated = true;
}
else
{
phy_wakeup_init();
phy_digital_regs_load();
}
#ifdef CONFIG_ESP32C3_BLE
coex_pti_v2();
#endif
}
g_phy_access_ref++;
leave_critical_section(flags);
kmm_free(cal_data);
}
/****************************************************************************
* Name: esp32c3_wl_init_semcache
*
* Description:
* Initialize semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
* sem - Semaphore data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_wl_init_semcache(struct esp32c3_wl_semcache_s *sc,
sem_t *sem)
{
sc->sem = sem;
sc->count = 0;
list_initialize(&sc->node);
}
/****************************************************************************
* Name: esp32c3_wl_post_semcache
*
* Description:
* Store posting semaphore action into semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void IRAM_ATTR esp32c3_wl_post_semcache(
struct esp32c3_wl_semcache_s *sc)
{
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
if (!sc->count)
{
list_add_tail(&priv->sc_list, &sc->node);
}
sc->count++;
putreg32(SYSTEM_CPU_INTR_FROM_CPU_0_M, SYSTEM_CPU_INTR_FROM_CPU_0_REG);
}
/****************************************************************************
* Name: esp32c3_wl_init
*
* Description:
* Initialize ESP32-C3 wireless common components for both BT and Wi-Fi.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_init(void)
{
int ret;
irqstate_t flags;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
flags = enter_critical_section();
if (priv->ref != 0)
{
priv->ref++;
leave_critical_section(flags);
return OK;
}
priv->cpuint = esp32c3_request_irq(SWI_PERIPH,
ESP32C3_INT_PRIO_DEF,
ESP32C3_INT_LEVEL);
ret = irq_attach(SWI_IRQ, esp32c3_wl_swi_irq, NULL);
if (ret < 0)
{
esp32c3_free_cpuint(SWI_PERIPH);
leave_critical_section(flags);
wlerr("ERROR: Failed to attach IRQ ret=%d\n", ret);
return ret;
}
list_initialize(&priv->sc_list);
up_enable_irq(priv->cpuint);
priv->ref++;
leave_critical_section(flags);
return OK;
}
/****************************************************************************
* Name: esp32c3_wl_deinit
*
* Description:
* De-initialize ESP32-C3 wireless common components.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_deinit(void)
{
irqstate_t flags;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
flags = enter_critical_section();
if (priv->ref == 0)
{
leave_critical_section(flags);
return OK;
}
up_disable_irq(priv->cpuint);
irq_detach(SWI_IRQ);
esp32c3_free_cpuint(SWI_PERIPH);
priv->ref--;
leave_critical_section(flags);
return OK;
}
/****************************************************************************
* Name: esp_read_mac
*
* Description:
* Read MAC address from efuse
*
* Input Parameters:
* mac - MAC address buffer pointer
* type - MAC address type
*
* Returned Value:
* 0 if success or -1 if fail
*
****************************************************************************/
int esp_read_mac(uint8_t *mac, esp_mac_type_t type)
{
uint32_t regval[2];
uint8_t tmp;
uint8_t *data = (uint8_t *)regval;
int i;
if (type > ESP_MAC_BT)
{
wlerr("ERROR: Input type is error=%d\n", type);
return -1;
}
regval[0] = getreg32(MAC_ADDR0_REG);
regval[1] = getreg32(MAC_ADDR1_REG);
for (i = 0; i < MAC_LEN; i++)
{
mac[i] = data[5 - i];
}
if (type == ESP_MAC_WIFI_SOFTAP)
{
tmp = mac[0];
for (i = 0; i < 64; i++)
{
mac[0] = tmp | 0x02;
mac[0] ^= i << 2;
if (mac[0] != tmp)
{
break;
}
}
if (i >= 64)
{
wlerr("ERROR: Failed to generate softAP MAC\n");
return -1;
}
}
if (type == ESP_MAC_BT)
{
tmp = mac[0];
for (i = 0; i < 64; i++)
{
mac[0] = tmp | 0x02;
mac[0] ^= i << 2;
if (mac[0] != tmp)
{
break;
}
}
mac[5] += 1;
}
return 0;
}
|
168535.c | /* $NoKeywords:$ */
/**
* @file
*
* External Interface implementation, general purpose features.
*
* Contains routines for implementing the interface to the client BIOS. This file
* includes the interface support which is not removed with various build options.
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: HyperTransport
* @e \$Revision: 63425 $ @e \$Date: 2011-12-22 11:24:10 -0600 (Thu, 22 Dec 2011) $
*
*/
/*
*****************************************************************************
*
* Copyright (c) 2008 - 2012, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. 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.
* ***************************************************************************
*
*/
/*
*----------------------------------------------------------------------------
* MODULES USED
*
*----------------------------------------------------------------------------
*/
#include "AGESA.h"
#include "amdlib.h"
#include "OptionMultiSocket.h"
#include "Ids.h"
#include "Topology.h"
#include "htFeat.h"
#include "htInterface.h"
#include "htInterfaceGeneral.h"
#include "htNb.h"
#include "cpuServices.h"
#include "cpuFeatures.h"
#include "heapManager.h"
#include "Filecode.h"
CODE_GROUP (G1_PEICC)
RDATA_GROUP (G1_PEICC)
#define FILECODE PROC_HT_HTINTERFACEGENERAL_FILECODE
/*----------------------------------------------------------------------------
* DEFINITIONS AND MACROS
*
*----------------------------------------------------------------------------
*/
extern OPTION_MULTISOCKET_CONFIGURATION OptionMultiSocketConfiguration;
/*----------------------------------------------------------------------------
* TYPEDEFS AND STRUCTURES
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* PROTOTYPES OF LOCAL FUNCTIONS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* EXPORTED FUNCTIONS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* LOCAL FUNCTIONS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------------------*/
/**
* Is PackageLink an Internal Link?
*
* This is a test for the logical link match codes in the user interface, not a test for
* the actual northbridge links.
*
* @param[in] PackageLink The link
*
* @retval TRUE This is an internal link
* @retval FALSE This is not an internal link
*/
BOOLEAN
IsPackageLinkInternal (
IN UINT8 PackageLink
)
{
return (BOOLEAN) ((PackageLink <= HT_LIST_MATCH_INTERNAL_LINK_2) && (PackageLink >= HT_LIST_MATCH_INTERNAL_LINK_0));
}
/*----------------------------------------------------------------------------------------*/
/**
* Ignore a Link.
*
* @HtInterfaceMethod{::F_GET_IGNORE_LINK}
*
* This routine is called every time a coherent Link is found and then every time a
* non-coherent Link from a CPU is found. Any coherent or non-coherent Link from a
* CPU can be ignored and not used for discovery or initialization. Useful for
* connection based systems.
*
* @note not called for IO device to IO Device Links.
*
* @param[in] Node The Node on which this Link is located
* @param[in] Link The Link about to be initialized
* @param[in] NbIgnoreLinkList The northbridge default ignore link list
* @param[in] State the input data
*
* @retval MATCHED ignore this Link and skip it
* @retval POWERED_OFF ignore this link and power it off.
* @retval UNMATCHED initialize the Link normally
*/
FINAL_LINK_STATE
GetIgnoreLink (
IN UINT8 Node,
IN UINT8 Link,
IN IGNORE_LINK *NbIgnoreLinkList,
IN STATE_DATA *State
)
{
IGNORE_LINK *p;
FINAL_LINK_STATE Result;
BOOLEAN IsFound;
UINT8 Socket;
UINT8 PackageLink;
ASSERT ((Node < MAX_NODES) && (Link < MAX_NODES));
Result = UNMATCHED;
IsFound = FALSE;
Socket = State->HtInterface->GetSocketFromMap (Node, State);
PackageLink = State->Nb->GetPackageLink (Node, Link, State->Nb);
if (State->HtBlock->IgnoreLinkList != NULL) {
p = State->HtBlock->IgnoreLinkList;
while (p->Socket != HT_LIST_TERMINAL) {
if (((p->Socket == Socket) || (p->Socket == HT_LIST_MATCH_ANY)) &&
((p->Link == PackageLink) ||
((p->Link == HT_LIST_MATCH_ANY) && (!IsPackageLinkInternal (PackageLink))) ||
((p->Link == HT_LIST_MATCH_INTERNAL_LINK) && (IsPackageLinkInternal (PackageLink))))) {
// Found a match return the desired link state.
ASSERT (Result < MaxFinalLinkState);
Result = p->LinkState;
IsFound = TRUE;
break;
} else {
p++;
}
}
}
// If there wasn't a match in the user interface, see if the northbridge provides one.
if (!IsFound && (NbIgnoreLinkList != NULL)) {
p = NbIgnoreLinkList;
while (p->Socket != HT_LIST_TERMINAL) {
if (((p->Socket == Socket) || (p->Socket == HT_LIST_MATCH_ANY)) &&
((p->Link == PackageLink) ||
((p->Link == HT_LIST_MATCH_ANY) && (!IsPackageLinkInternal (PackageLink))) ||
((p->Link == HT_LIST_MATCH_INTERNAL_LINK) && (IsPackageLinkInternal (PackageLink))))) {
// Found a match return the desired link state.
ASSERT (Result < MaxFinalLinkState);
Result = p->LinkState;
break;
} else {
p++;
}
}
}
return Result;
}
/*----------------------------------------------------------------------------------------*/
/**
* Get the Socket number for a given Node number.
*
* @HtInterfaceMethod{::F_GET_SOCKET_FROM_MAP}
*
* Return the id.
*
* @param[in] Node The Node to translate
* @param[in] State reference to Node to socket map
*
* @return the socket id
*
*/
UINT8
GetSocketFromMap (
IN UINT8 Node,
IN STATE_DATA *State
)
{
UINT8 Socket;
ASSERT (State->NodeToSocketDieMap != NULL);
Socket = (*State->NodeToSocketDieMap)[Node].Socket;
return Socket;
}
/*----------------------------------------------------------------------------------------*/
/**
* Get a new Socket Die to Node Map.
*
* @HtInterfaceMethod{::F_NEW_NODE_AND_SOCKET_TABLES}
*
* Put the Socket Die Table in heap with a known handle. Content will be generated as
* each node is discovered.
*
* @param[in,out] State global state
*/
VOID
NewNodeAndSocketTables (
IN OUT STATE_DATA *State
)
{
UINT8 i;
UINT8 j;
ALLOCATE_HEAP_PARAMS AllocHeapParams;
// Allocate heap for the table
State->SocketDieToNodeMap = NULL;
AllocHeapParams.RequestedBufferSize = (((MAX_SOCKETS) * (MAX_DIES)) * sizeof (SOCKET_DIE_TO_NODE_ITEM));
AllocHeapParams.BufferHandle = SOCKET_DIE_MAP_HANDLE;
AllocHeapParams.Persist = HEAP_SYSTEM_MEM;
if (HeapAllocateBuffer (&AllocHeapParams, State->ConfigHandle) == AGESA_SUCCESS) {
State->SocketDieToNodeMap = (SOCKET_DIE_TO_NODE_MAP)AllocHeapParams.BufferPtr;
// Initialize shared data structures
for (i = 0; i < MAX_SOCKETS; i++) {
for (j = 0; j < MAX_DIES; j++) {
(*State->SocketDieToNodeMap)[i][j].Node = HT_LIST_TERMINAL;
(*State->SocketDieToNodeMap)[i][j].LowCore = HT_LIST_TERMINAL;
(*State->SocketDieToNodeMap)[i][j].HighCore = HT_LIST_TERMINAL;
}
}
}
// Allocate heap for the table
State->NodeToSocketDieMap = NULL;
AllocHeapParams.RequestedBufferSize = (MAX_NODES * sizeof (NODE_TO_SOCKET_DIE_ITEM));
AllocHeapParams.BufferHandle = NODE_ID_MAP_HANDLE;
AllocHeapParams.Persist = HEAP_SYSTEM_MEM;
if (HeapAllocateBuffer (&AllocHeapParams, State->ConfigHandle) == AGESA_SUCCESS) {
State->NodeToSocketDieMap = (NODE_TO_SOCKET_DIE_MAP)AllocHeapParams.BufferPtr;
// Initialize shared data structures
for (i = 0; i < MAX_NODES; i++) {
(*State->NodeToSocketDieMap)[i].Socket = HT_LIST_TERMINAL;
(*State->NodeToSocketDieMap)[i].Die = HT_LIST_TERMINAL;
}
}
}
/*----------------------------------------------------------------------------------------*/
/**
* Get the minimum Northbridge frequency for the system.
*
* @HtInterfaceMethod{::F_GET_MIN_NB_CORE_FREQ}
*
* Invoke the CPU component power mgt interface.
*
* @param[in] PlatformConfig Platform profile/build option config structure.
* @param[in] StdHeader Config for library and services.
*
* @return Frequency in MHz.
*
*/
UINT32
GetMinNbCoreFreq (
IN PLATFORM_CONFIGURATION *PlatformConfig,
IN AMD_CONFIG_PARAMS *StdHeader
)
{
UINT32 MinSysNbFreq;
UINT32 MinP0NbFreq;
OptionMultiSocketConfiguration.GetMinNbCof (PlatformConfig, &MinSysNbFreq, &MinP0NbFreq, StdHeader);
ASSERT (MinSysNbFreq != 0);
return MinSysNbFreq;
}
/**
* @page physicalsockethowto Physical Socket Map, How To Create
*
* To create a physical system socket map for a platform:
*
* - Start at the Node which will be the BSP.
*
* - Begin a breadth first enumeration of all the coherent Links between sockets
* by creating a socket structure for each socket connection from the BSP.
* For example, if the BSP is in socket zero and Link one connects to socket two,
* create socket {0, 1, 2}.
*
* - When all Links from the BSP are described, go to the first socket connected
* to the BSP and continue the breadth first enumeration.
*
* - It should not be necessary to describe the back Links; in the example above, there
* should be no need to create {2, 1, 0} (assuming socket two connects back to
* socket zero on its Link one).
*
* - When completed:
*
* - Every socket except the BSP's (usually zero) must be listed as a targetSocket,
* at least once. Some sockets may be listed more than once.
*
* - There usually should be at least as many entries as Links. An exception is a
* fully connected system, only the Links from the BSP are needed.
*
* - Every socket but the last one in the breadth first order should usually have one
* or more entries listing it as a currentSocket. (The last one has only back Links.)
*
* There are no strict assumptions about the ordering of the socket structures.
*/
/*----------------------------------------------------------------------------------------*/
/**
* Update maps between Sockets and Nodes for a specific newly discovered node.
*
* @HtInterfaceMethod{::F_SET_NODE_TO_SOCKET_MAP}
*
* There are two methods for providing socket naming of nodes.
*
* Hardware Method (preferred): A value strapped in hardware by the board is read and
* passed to this routine.
*
* Software Method: The current node's socket is looked up, since it was
* previously a new node and went through this process. The link is converted to
* a package level link. A user data structure describing the package level
* layout of the system is searched for the current node's socket and package link,
* and now we know the new node's socket.
*
* In either case, the Socket, Module to Node map and the Node to Socket, Module
* map are updated with the new node, socket, and module.
*
* Data needed to do this is passed in to the routine as arguments rather than read by this routine,
* so that it is not necessary to know a valid temporary route to either node at the time this code runs.
*
* @param[in] Node Node from which a new node was discovered
* @param[in] CurrentNodeModule The current node's module id in it's processor.
* @param[in] PackageLink The package link for the current node's link.
* @param[in] NewNode The new node's id
* @param[in] HardwareSocket If we use the hardware method (preferred), this is the socket of new node.
* @param[in] Module The new node's module id in it's processor.
* @param[in] State our State
*/
VOID
SetNodeToSocketMap (
IN UINT8 Node,
IN UINT8 CurrentNodeModule,
IN UINT8 PackageLink,
IN UINT8 NewNode,
IN UINT8 HardwareSocket,
IN UINT8 Module,
IN STATE_DATA *State
)
{
UINT8 SourceSocket;
UINT8 TargetSocket;
SYSTEM_PHYSICAL_SOCKET_MAP *Map;
// While this code could be written to recover from a NULL socket map, AGESA cannot function without one.
ASSERT (State->SocketDieToNodeMap != NULL);
if (State->HtBlock->SystemPhysicalSocketMap != NULL) {
if (NewNode != 0) {
// Find the logical Node from which a new Node was discovered in the Node field of
// some socket. It must already be there, Nodes are assigned ascending.
//
for (SourceSocket = 0; SourceSocket < MAX_SOCKETS; SourceSocket++) {
if ((*State->SocketDieToNodeMap)[SourceSocket][CurrentNodeModule].Node == Node) {
break;
}
}
// This ASSERT should be understood as "the Node did not have a match", not as a limit check on SourceSocket.
ASSERT (SourceSocket != MAX_SOCKETS);
// Find the sourceSocket in the CurrentSocket field, for the Link on which a new Node
// was discovered. When we find an entry with that socket and Link number, update the
// Node for that socket.
//
if (IsPackageLinkInternal (PackageLink)) {
// Internal Nodes are in the same socket, don't search the physical system map.
TargetSocket = SourceSocket;
} else {
// Find the target socket in the physical system map.
Map = State->HtBlock->SystemPhysicalSocketMap;
while ((Map->CurrentSocket != 0xFF) &&
((Map->CurrentSocket != SourceSocket) || (Map->CurrentLink != PackageLink))) {
Map++;
}
ASSERT (Map->CurrentSocket != 0xFF);
TargetSocket = Map->TargetSocket;
}
} else {
// The BSP (BSN, if you will) has no predecessor node from which it is discovered.
TargetSocket = 0;
}
} else {
// Use the hardware method
// The hardware strapped socket id is passed to us in this case.
TargetSocket = HardwareSocket;
}
// If the target socket, module is already mapped to something, that's not good. Socket labeling conflict.
// Check that the board is strapped correctly. If not you need a SystemPhysicalSocketMap. If you have one,
// check it for correctness.
ASSERT ((*State->SocketDieToNodeMap)[TargetSocket][Module].Node == 0xFF);
// Update the map for the rest of agesa
(*State->SocketDieToNodeMap)[TargetSocket][Module].Node = NewNode;
// and the node to socket map
ASSERT (State->NodeToSocketDieMap != NULL);
(*State->NodeToSocketDieMap)[NewNode].Socket = TargetSocket;
(*State->NodeToSocketDieMap)[NewNode].Die = Module;
}
/*----------------------------------------------------------------------------------------*/
/**
* Clean up the map structures after severe event has caused a fall back to 1 node.
*
* @HtInterfaceMethod{::F_CLEAN_MAPS_AFTER_ERROR}
*
* @param[in] State Our state, access to socket, node maps
*
*/
VOID
CleanMapsAfterError (
IN STATE_DATA *State
)
{
UINTN Socket;
UINTN Module;
UINTN Node;
ASSERT (State->NodeToSocketDieMap != NULL);
ASSERT (State->SocketDieToNodeMap != NULL);
// Clear all the socket, module items except for the socket and module containing node zero.
for (Socket = 0; Socket < MAX_SOCKETS; Socket++) {
for (Module = 0; Module < MAX_DIES; Module++) {
if (((*State->NodeToSocketDieMap)[0].Socket != Socket) || ((*State->NodeToSocketDieMap)[0].Die != Module)) {
(*State->SocketDieToNodeMap)[Socket][Module].Node = HT_LIST_TERMINAL;
(*State->SocketDieToNodeMap)[Socket][Module].LowCore = HT_LIST_TERMINAL;
(*State->SocketDieToNodeMap)[Socket][Module].HighCore = HT_LIST_TERMINAL;
}
}
}
// Clear all the node items except for node zero.
for (Node = 1; Node < MAX_NODES; Node++) {
(*State->NodeToSocketDieMap)[Node].Socket = HT_LIST_TERMINAL;
(*State->NodeToSocketDieMap)[Node].Die = HT_LIST_TERMINAL;
}
}
/*----------------------------------------------------------------------------------------*/
/**
* Post Node id and other context info to AP cores via mailbox.
*
* @HtInterfaceMethod{::F_POST_MAP_TO_AP}
*
* Since Ap's can not view map until after mp communication is established,
* provide them with initial context info via a mailbox register. A mailbox
* register is one that can be written in PCI space and read in MSR space.
*
* @param[in] State Our state, access to socket, node maps
*/
VOID
PostMapToAp (
IN STATE_DATA *State
)
{
UINT8 ModuleType;
UINT8 Module;
AP_MAILBOXES ApMailboxes;
UINT8 Node;
UINT32 Degree;
AGESA_STATUS CalledStatus;
// Dispatch any features (such as Preserve Mailbox) that need to run as soon as discovery is completed.
IDS_HDT_CONSOLE (CPU_TRACE, " Dispatch CPU features after HT discovery\n");
CalledStatus = DispatchCpuFeatures (CPU_FEAT_AFTER_COHERENT_DISCOVERY, State->PlatformConfiguration, State->ConfigHandle);
ASSERT (State->Fabric != NULL);
Degree = 0;
// Compute the degree of the system by finding the maximum degree of any node.
for (Node = 0; Node < (State->NodesDiscovered + 1); Node++) {
if (State->Fabric->SysDegree[Node] > Degree) {
Degree = State->Fabric->SysDegree[Node];
}
}
// Post the information on all nodes.
for (Node = 0; Node < (State->NodesDiscovered + 1); Node++) {
ModuleType = 0;
Module = 0;
State->Nb->GetModuleInfo (Node, &ModuleType, &Module, State->Nb);
ApMailboxes.ApMailInfo.Info = 0;
ApMailboxes.ApMailInfo.Fields.Node = Node;
ApMailboxes.ApMailInfo.Fields.Socket = State->HtInterface->GetSocketFromMap (Node, State);
ApMailboxes.ApMailInfo.Fields.ModuleType = ModuleType;
ApMailboxes.ApMailInfo.Fields.Module = Module;
ApMailboxes.ApMailExtInfo.Info = 0;
ApMailboxes.ApMailExtInfo.Fields.SystemDegree = Degree;
// other fields of the extended info are used during ap init, and will be initialized at that time.
State->Nb->PostMailbox (Node, ApMailboxes, State->Nb);
}
// Now that the mailboxes have been initialized, cache the info on the BSC. The APs
// will cache during heap initialization.
CacheApMailbox (State->ConfigHandle);
}
|
1633.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 2021 Sifive.
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/bug.h>
#include <asm/patch.h>
#include <asm/alternative.h>
#include <asm/vendorid_list.h>
#include <asm/errata_list.h>
struct errata_info_t {
char name[ERRATA_STRING_LENGTH_MAX];
bool (*check_func)(unsigned long arch_id, unsigned long impid);
};
static bool errata_cip_453_check_func(unsigned long arch_id, unsigned long impid)
{
/*
* Affected cores:
* Architecture ID: 0x8000000000000007
* Implement ID: 0x20181004 <= impid <= 0x20191105
*/
if (arch_id != 0x8000000000000007 ||
(impid < 0x20181004 || impid > 0x20191105))
return false;
return true;
}
static bool errata_cip_1200_check_func(unsigned long arch_id, unsigned long impid)
{
/*
* Affected cores:
* Architecture ID: 0x8000000000000007 or 0x1
* Implement ID: mimpid[23:0] <= 0x200630 and mimpid != 0x01200626
*/
if (arch_id != 0x8000000000000007 && arch_id != 0x1)
return false;
if ((impid & 0xffffff) > 0x200630 || impid == 0x1200626)
return false;
return true;
}
static struct errata_info_t errata_list[ERRATA_SIFIVE_NUMBER] = {
{
.name = "cip-453",
.check_func = errata_cip_453_check_func
},
{
.name = "cip-1200",
.check_func = errata_cip_1200_check_func
},
};
static u32 __init sifive_errata_probe(unsigned long archid, unsigned long impid)
{
int idx;
u32 cpu_req_errata = 0;
for (idx = 0; idx < ERRATA_SIFIVE_NUMBER; idx++)
if (errata_list[idx].check_func(archid, impid))
cpu_req_errata |= (1U << idx);
return cpu_req_errata;
}
static void __init warn_miss_errata(u32 miss_errata)
{
int i;
pr_warn("----------------------------------------------------------------\n");
pr_warn("WARNING: Missing the following errata may cause potential issues\n");
for (i = 0; i < ERRATA_SIFIVE_NUMBER; i++)
if (miss_errata & 0x1 << i)
pr_warn("\tSiFive Errata[%d]:%s\n", i, errata_list[i].name);
pr_warn("Please enable the corresponding Kconfig to apply them\n");
pr_warn("----------------------------------------------------------------\n");
}
void __init sifive_errata_patch_func(struct alt_entry *begin, struct alt_entry *end,
unsigned long archid, unsigned long impid)
{
struct alt_entry *alt;
u32 cpu_req_errata = sifive_errata_probe(archid, impid);
u32 cpu_apply_errata = 0;
u32 tmp;
for (alt = begin; alt < end; alt++) {
if (alt->vendor_id != SIFIVE_VENDOR_ID)
continue;
if (alt->errata_id >= ERRATA_SIFIVE_NUMBER) {
WARN(1, "This errata id:%d is not in kernel errata list", alt->errata_id);
continue;
}
tmp = (1U << alt->errata_id);
if (cpu_req_errata & tmp) {
patch_text_nosync(alt->old_ptr, alt->alt_ptr, alt->alt_len);
cpu_apply_errata |= tmp;
}
}
if (cpu_apply_errata != cpu_req_errata)
warn_miss_errata(cpu_req_errata - cpu_apply_errata);
}
|
59069.c | /*-
* Copyright (c) 1983, 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if !defined(lint) && !defined(_KERNEL) && defined(LIBC_SCCS)
static char rcsid[] = "$OpenBSD: mcount.c,v 1.6 1997/07/23 21:11:27 kstailey Exp $";
#endif
/*
* This file is taken from Cygwin distribution. Please keep it in sync.
* The differences should be within __MINGW32__ guard.
*/
#ifndef __MINGW32__
#include <sys/param.h>
#endif
#include <sys/types.h>
#include <gmon.h>
/*
* mcount is called on entry to each function compiled with the profiling
* switch set. _mcount(), which is declared in a machine-dependent way
* with _MCOUNT_DECL, does the actual work and is either inlined into a
* C routine or called by an assembly stub. In any case, this magic is
* taken care of by the MCOUNT definition in <machine/profile.h>.
*
* _mcount updates data structures that represent traversals of the
* program's call graph edges. frompc and selfpc are the return
* address and function address that represents the given call graph edge.
*
* Note: the original BSD code used the same variable (frompcindex) for
* both frompcindex and frompc. Any reasonable, modern compiler will
* perform this optimization.
*/
/* _mcount; may be static, inline, etc */
_MCOUNT_DECL (frompc, selfpc)
{
register unsigned short *frompcindex;
register struct tostruct *top, *prevtop;
register struct gmonparam *p;
register long toindex;
p = &_gmonparam;
/*
* check that we are profiling
* and that we aren't recursively invoked.
*/
if (p->state != GMON_PROF_ON)
return;
p->state = GMON_PROF_BUSY;
/*
* check that frompcindex is a reasonable pc value.
* for example: signal catchers get called from the stack,
* not from text space. too bad.
*/
frompc -= p->lowpc;
if (frompc > p->textsize)
goto done;
#if (HASHFRACTION & (HASHFRACTION - 1)) == 0
if (p->hashfraction == HASHFRACTION)
frompcindex =
&p->froms[frompc / (HASHFRACTION * sizeof(*p->froms))];
else
#endif
frompcindex =
&p->froms[frompc / (p->hashfraction * sizeof(*p->froms))];
toindex = *frompcindex;
if (toindex == 0) {
/*
* first time traversing this arc
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit)
/* halt further profiling */
goto overflow;
*frompcindex = toindex;
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = 0;
goto done;
}
top = &p->tos[toindex];
if (top->selfpc == selfpc) {
/*
* arc at front of chain; usual case.
*/
top->count++;
goto done;
}
/*
* have to go looking down chain for it.
* top points to what we are looking at,
* prevtop points to previous top.
* we know it is not at the head of the chain.
*/
for (; /* goto done */; ) {
if (top->link == 0) {
/*
* top is end of the chain and none of the chain
* had top->selfpc == selfpc.
* so we allocate a new tostruct
* and link it to the head of the chain.
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit)
goto overflow;
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
/*
* otherwise, check the next arc on the chain.
*/
prevtop = top;
top = &p->tos[top->link];
if (top->selfpc == selfpc) {
/*
* there it is.
* increment its count
* move it to the head of the chain.
*/
top->count++;
toindex = prevtop->link;
prevtop->link = top->link;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
}
done:
p->state = GMON_PROF_ON;
return;
overflow:
p->state = GMON_PROF_ERROR;
return;
}
/*
* Actual definition of mcount function. Defined in <machine/profile.h>,
* which is included by <sys/gmon.h>
*/
MCOUNT
|
221712.c | /*-
* BSD LICENSE
*
* Copyright(c) 2010-2014 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 <string.h>
#include <stdint.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include <sys/queue.h>
#include <rte_log.h>
#include <rte_branch_prediction.h>
#include <rte_common.h>
#include <rte_memory.h>
#include <rte_malloc.h>
#include <rte_memzone.h>
#include <rte_memcpy.h>
#include <rte_tailq.h>
#include <rte_eal.h>
#include <rte_eal_memconfig.h>
#include <rte_per_lcore.h>
#include <rte_string_fns.h>
#include <rte_errno.h>
#include <rte_rwlock.h>
#include <rte_spinlock.h>
#include "rte_lpm6.h"
#define RTE_LPM6_TBL24_NUM_ENTRIES (1 << 24)
#define RTE_LPM6_TBL8_GROUP_NUM_ENTRIES 256
#define RTE_LPM6_TBL8_MAX_NUM_GROUPS (1 << 21)
#define RTE_LPM6_VALID_EXT_ENTRY_BITMASK 0xA0000000
#define RTE_LPM6_LOOKUP_SUCCESS 0x20000000
#define RTE_LPM6_TBL8_BITMASK 0x001FFFFF
#define ADD_FIRST_BYTE 3
#define LOOKUP_FIRST_BYTE 4
#define BYTE_SIZE 8
#define BYTES2_SIZE 16
#define lpm6_tbl8_gindex next_hop
/** Flags for setting an entry as valid/invalid. */
enum valid_flag {
INVALID = 0,
VALID
};
TAILQ_HEAD(rte_lpm6_list, rte_tailq_entry);
/** Tbl entry structure. It is the same for both tbl24 and tbl8 */
struct rte_lpm6_tbl_entry {
uint32_t next_hop: 21; /**< Next hop / next table to be checked. */
uint32_t depth :8; /**< Rule depth. */
/* Flags. */
uint32_t valid :1; /**< Validation flag. */
uint32_t valid_group :1; /**< Group validation flag. */
uint32_t ext_entry :1; /**< External entry. */
};
/** Rules tbl entry structure. */
struct rte_lpm6_rule {
uint8_t ip[RTE_LPM6_IPV6_ADDR_SIZE]; /**< Rule IP address. */
uint8_t next_hop; /**< Rule next hop. */
uint8_t depth; /**< Rule depth. */
};
/** LPM6 structure. */
struct rte_lpm6 {
/* LPM metadata. */
char name[RTE_LPM6_NAMESIZE]; /**< Name of the lpm. */
uint32_t max_rules; /**< Max number of rules. */
uint32_t used_rules; /**< Used rules so far. */
uint32_t number_tbl8s; /**< Number of tbl8s to allocate. */
uint32_t next_tbl8; /**< Next tbl8 to be used. */
/* LPM Tables. */
struct rte_lpm6_rule *rules_tbl; /**< LPM rules. */
struct rte_lpm6_tbl_entry tbl24[RTE_LPM6_TBL24_NUM_ENTRIES]
__rte_cache_aligned; /**< LPM tbl24 table. */
struct rte_lpm6_tbl_entry tbl8[0]
__rte_cache_aligned; /**< LPM tbl8 table. */
};
/*
* Takes an array of uint8_t (IPv6 address) and masks it using the depth.
* It leaves untouched one bit per unit in the depth variable
* and set the rest to 0.
*/
static inline void
mask_ip(uint8_t *ip, uint8_t depth)
{
int16_t part_depth, mask;
int i;
part_depth = depth;
for (i = 0; i < RTE_LPM6_IPV6_ADDR_SIZE; i++) {
if (part_depth < BYTE_SIZE && part_depth >= 0) {
mask = (uint16_t)(~(UINT8_MAX >> part_depth));
ip[i] = (uint8_t)(ip[i] & mask);
} else if (part_depth < 0) {
ip[i] = 0;
}
part_depth -= BYTE_SIZE;
}
}
/*
* Allocates memory for LPM object
*/
struct rte_lpm6 *
rte_lpm6_create(const char *name, int socket_id,
const struct rte_lpm6_config *config)
{
char mem_name[RTE_LPM6_NAMESIZE];
struct rte_lpm6 *lpm = NULL;
struct rte_tailq_entry *te;
uint64_t mem_size, rules_size;
struct rte_lpm6_list *lpm_list;
/* Check that we have an initialised tail queue */
if ((lpm_list =
RTE_TAILQ_LOOKUP_BY_IDX(RTE_TAILQ_LPM6, rte_lpm6_list)) == NULL) {
rte_errno = E_RTE_NO_TAILQ;
return NULL;
}
RTE_BUILD_BUG_ON(sizeof(struct rte_lpm6_tbl_entry) != sizeof(uint32_t));
/* Check user arguments. */
if ((name == NULL) || (socket_id < -1) || (config == NULL) ||
(config->max_rules == 0) ||
config->number_tbl8s > RTE_LPM6_TBL8_MAX_NUM_GROUPS) {
rte_errno = EINVAL;
return NULL;
}
snprintf(mem_name, sizeof(mem_name), "LPM_%s", name);
/* Determine the amount of memory to allocate. */
mem_size = sizeof(*lpm) + (sizeof(lpm->tbl8[0]) *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES * config->number_tbl8s);
rules_size = sizeof(struct rte_lpm6_rule) * config->max_rules;
rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
/* Guarantee there's no existing */
TAILQ_FOREACH(te, lpm_list, next) {
lpm = (struct rte_lpm6 *) te->data;
if (strncmp(name, lpm->name, RTE_LPM6_NAMESIZE) == 0)
break;
}
if (te != NULL)
goto exit;
/* allocate tailq entry */
te = rte_zmalloc("LPM6_TAILQ_ENTRY", sizeof(*te), 0);
if (te == NULL) {
RTE_LOG(ERR, LPM, "Failed to allocate tailq entry!\n");
goto exit;
}
/* Allocate memory to store the LPM data structures. */
lpm = (struct rte_lpm6 *)rte_zmalloc_socket(mem_name, (size_t)mem_size,
CACHE_LINE_SIZE, socket_id);
if (lpm == NULL) {
RTE_LOG(ERR, LPM, "LPM memory allocation failed\n");
rte_free(te);
goto exit;
}
lpm->rules_tbl = (struct rte_lpm6_rule *)rte_zmalloc_socket(NULL,
(size_t)rules_size, CACHE_LINE_SIZE, socket_id);
if (lpm->rules_tbl == NULL) {
RTE_LOG(ERR, LPM, "LPM memory allocation failed\n");
rte_free(lpm);
rte_free(te);
goto exit;
}
/* Save user arguments. */
lpm->max_rules = config->max_rules;
lpm->number_tbl8s = config->number_tbl8s;
snprintf(lpm->name, sizeof(lpm->name), "%s", name);
te->data = (void *) lpm;
TAILQ_INSERT_TAIL(lpm_list, te, next);
exit:
rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
return lpm;
}
/*
* Find an existing lpm table and return a pointer to it.
*/
struct rte_lpm6 *
rte_lpm6_find_existing(const char *name)
{
struct rte_lpm6 *l = NULL;
struct rte_tailq_entry *te;
struct rte_lpm6_list *lpm_list;
/* Check that we have an initialised tail queue */
if ((lpm_list = RTE_TAILQ_LOOKUP_BY_IDX(RTE_TAILQ_LPM6,
rte_lpm6_list)) == NULL) {
rte_errno = E_RTE_NO_TAILQ;
return NULL;
}
rte_rwlock_read_lock(RTE_EAL_TAILQ_RWLOCK);
TAILQ_FOREACH(te, lpm_list, next) {
l = (struct rte_lpm6 *) te->data;
if (strncmp(name, l->name, RTE_LPM6_NAMESIZE) == 0)
break;
}
rte_rwlock_read_unlock(RTE_EAL_TAILQ_RWLOCK);
if (te == NULL) {
rte_errno = ENOENT;
return NULL;
}
return l;
}
/*
* Deallocates memory for given LPM table.
*/
void
rte_lpm6_free(struct rte_lpm6 *lpm)
{
struct rte_lpm6_list *lpm_list;
struct rte_tailq_entry *te;
/* Check user arguments. */
if (lpm == NULL)
return;
/* check that we have an initialised tail queue */
if ((lpm_list =
RTE_TAILQ_LOOKUP_BY_IDX(RTE_TAILQ_LPM, rte_lpm6_list)) == NULL) {
rte_errno = E_RTE_NO_TAILQ;
return;
}
rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
/* find our tailq entry */
TAILQ_FOREACH(te, lpm_list, next) {
if (te->data == (void *) lpm)
break;
}
if (te == NULL) {
rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
return;
}
TAILQ_REMOVE(lpm_list, te, next);
rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
rte_free(lpm);
rte_free(te);
}
/*
* Checks if a rule already exists in the rules table and updates
* the nexthop if so. Otherwise it adds a new rule if enough space is available.
*/
static inline int32_t
rule_add(struct rte_lpm6 *lpm, uint8_t *ip, uint8_t next_hop, uint8_t depth)
{
uint32_t rule_index;
/* Scan through rule list to see if rule already exists. */
for (rule_index = 0; rule_index < lpm->used_rules; rule_index++) {
/* If rule already exists update its next_hop and return. */
if ((memcmp (lpm->rules_tbl[rule_index].ip, ip,
RTE_LPM6_IPV6_ADDR_SIZE) == 0) &&
lpm->rules_tbl[rule_index].depth == depth) {
lpm->rules_tbl[rule_index].next_hop = next_hop;
return rule_index;
}
}
/*
* If rule does not exist check if there is space to add a new rule to
* this rule group. If there is no space return error.
*/
if (lpm->used_rules == lpm->max_rules) {
return -ENOSPC;
}
/* If there is space for the new rule add it. */
rte_memcpy(lpm->rules_tbl[rule_index].ip, ip, RTE_LPM6_IPV6_ADDR_SIZE);
lpm->rules_tbl[rule_index].next_hop = next_hop;
lpm->rules_tbl[rule_index].depth = depth;
/* Increment the used rules counter for this rule group. */
lpm->used_rules++;
return rule_index;
}
/*
* Function that expands a rule across the data structure when a less-generic
* one has been added before. It assures that every possible combination of bits
* in the IP address returns a match.
*/
static void
expand_rule(struct rte_lpm6 *lpm, uint32_t tbl8_gindex, uint8_t depth,
uint8_t next_hop)
{
uint32_t tbl8_group_end, tbl8_gindex_next, j;
tbl8_group_end = tbl8_gindex + RTE_LPM6_TBL8_GROUP_NUM_ENTRIES;
struct rte_lpm6_tbl_entry new_tbl8_entry = {
.valid = VALID,
.valid_group = VALID,
.depth = depth,
.next_hop = next_hop,
.ext_entry = 0,
};
for (j = tbl8_gindex; j < tbl8_group_end; j++) {
if (!lpm->tbl8[j].valid || (lpm->tbl8[j].ext_entry == 0
&& lpm->tbl8[j].depth <= depth)) {
lpm->tbl8[j] = new_tbl8_entry;
} else if (lpm->tbl8[j].ext_entry == 1) {
tbl8_gindex_next = lpm->tbl8[j].lpm6_tbl8_gindex
* RTE_LPM6_TBL8_GROUP_NUM_ENTRIES;
expand_rule(lpm, tbl8_gindex_next, depth, next_hop);
}
}
}
/*
* Partially adds a new route to the data structure (tbl24+tbl8s).
* It returns 0 on success, a negative number on failure, or 1 if
* the process needs to be continued by calling the function again.
*/
static inline int
add_step(struct rte_lpm6 *lpm, struct rte_lpm6_tbl_entry *tbl,
struct rte_lpm6_tbl_entry **tbl_next, uint8_t *ip, uint8_t bytes,
uint8_t first_byte, uint8_t depth, uint8_t next_hop)
{
uint32_t tbl_index, tbl_range, tbl8_group_start, tbl8_group_end, i;
int32_t tbl8_gindex;
int8_t bitshift;
uint8_t bits_covered;
/*
* Calculate index to the table based on the number and position
* of the bytes being inspected in this step.
*/
tbl_index = 0;
for (i = first_byte; i < (uint32_t)(first_byte + bytes); i++) {
bitshift = (int8_t)((bytes - i)*BYTE_SIZE);
if (bitshift < 0) bitshift = 0;
tbl_index = tbl_index | ip[i-1] << bitshift;
}
/* Number of bits covered in this step */
bits_covered = (uint8_t)((bytes+first_byte-1)*BYTE_SIZE);
/*
* If depth if smaller than this number (ie this is the last step)
* expand the rule across the relevant positions in the table.
*/
if (depth <= bits_covered) {
tbl_range = 1 << (bits_covered - depth);
for (i = tbl_index; i < (tbl_index + tbl_range); i++) {
if (!tbl[i].valid || (tbl[i].ext_entry == 0 &&
tbl[i].depth <= depth)) {
struct rte_lpm6_tbl_entry new_tbl_entry = {
.next_hop = next_hop,
.depth = depth,
.valid = VALID,
.valid_group = VALID,
.ext_entry = 0,
};
tbl[i] = new_tbl_entry;
} else if (tbl[i].ext_entry == 1) {
/*
* If tbl entry is valid and extended calculate the index
* into next tbl8 and expand the rule across the data structure.
*/
tbl8_gindex = tbl[i].lpm6_tbl8_gindex *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES;
expand_rule(lpm, tbl8_gindex, depth, next_hop);
}
}
return 0;
}
/*
* If this is not the last step just fill one position
* and calculate the index to the next table.
*/
else {
/* If it's invalid a new tbl8 is needed */
if (!tbl[tbl_index].valid) {
if (lpm->next_tbl8 < lpm->number_tbl8s)
tbl8_gindex = (lpm->next_tbl8)++;
else
return -ENOSPC;
struct rte_lpm6_tbl_entry new_tbl_entry = {
.lpm6_tbl8_gindex = tbl8_gindex,
.depth = 0,
.valid = VALID,
.valid_group = VALID,
.ext_entry = 1,
};
tbl[tbl_index] = new_tbl_entry;
}
/*
* If it's valid but not extended the rule that was stored *
* here needs to be moved to the next table.
*/
else if (tbl[tbl_index].ext_entry == 0) {
/* Search for free tbl8 group. */
if (lpm->next_tbl8 < lpm->number_tbl8s)
tbl8_gindex = (lpm->next_tbl8)++;
else
return -ENOSPC;
tbl8_group_start = tbl8_gindex *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES;
tbl8_group_end = tbl8_group_start +
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES;
/* Populate new tbl8 with tbl value. */
for (i = tbl8_group_start; i < tbl8_group_end; i++) {
lpm->tbl8[i].valid = VALID;
lpm->tbl8[i].depth = tbl[tbl_index].depth;
lpm->tbl8[i].next_hop = tbl[tbl_index].next_hop;
lpm->tbl8[i].ext_entry = 0;
}
/*
* Update tbl entry to point to new tbl8 entry. Note: The
* ext_flag and tbl8_index need to be updated simultaneously,
* so assign whole structure in one go.
*/
struct rte_lpm6_tbl_entry new_tbl_entry = {
.lpm6_tbl8_gindex = tbl8_gindex,
.depth = 0,
.valid = VALID,
.valid_group = VALID,
.ext_entry = 1,
};
tbl[tbl_index] = new_tbl_entry;
}
*tbl_next = &(lpm->tbl8[tbl[tbl_index].lpm6_tbl8_gindex *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES]);
}
return 1;
}
/*
* Add a route
*/
int
rte_lpm6_add(struct rte_lpm6 *lpm, uint8_t *ip, uint8_t depth,
uint8_t next_hop)
{
struct rte_lpm6_tbl_entry *tbl;
struct rte_lpm6_tbl_entry *tbl_next;
int32_t rule_index;
int status;
uint8_t masked_ip[RTE_LPM6_IPV6_ADDR_SIZE];
int i;
/* Check user arguments. */
if ((lpm == NULL) || (depth < 1) || (depth > RTE_LPM6_MAX_DEPTH))
return -EINVAL;
/* Copy the IP and mask it to avoid modifying user's input data. */
memcpy(masked_ip, ip, RTE_LPM6_IPV6_ADDR_SIZE);
mask_ip(masked_ip, depth);
/* Add the rule to the rule table. */
rule_index = rule_add(lpm, masked_ip, next_hop, depth);
/* If there is no space available for new rule return error. */
if (rule_index < 0) {
return rule_index;
}
/* Inspect the first three bytes through tbl24 on the first step. */
tbl = lpm->tbl24;
status = add_step (lpm, tbl, &tbl_next, masked_ip, ADD_FIRST_BYTE, 1,
depth, next_hop);
if (status < 0) {
rte_lpm6_delete(lpm, masked_ip, depth);
return status;
}
/*
* Inspect one by one the rest of the bytes until
* the process is completed.
*/
for (i = ADD_FIRST_BYTE; i < RTE_LPM6_IPV6_ADDR_SIZE && status == 1; i++) {
tbl = tbl_next;
status = add_step (lpm, tbl, &tbl_next, masked_ip, 1, (uint8_t)(i+1),
depth, next_hop);
if (status < 0) {
rte_lpm6_delete(lpm, masked_ip, depth);
return status;
}
}
return status;
}
/*
* Takes a pointer to a table entry and inspect one level.
* The function returns 0 on lookup success, ENOENT if no match was found
* or 1 if the process needs to be continued by calling the function again.
*/
static inline int
lookup_step(const struct rte_lpm6 *lpm, const struct rte_lpm6_tbl_entry *tbl,
const struct rte_lpm6_tbl_entry **tbl_next, uint8_t *ip,
uint8_t first_byte, uint8_t *next_hop)
{
uint32_t tbl8_index, tbl_entry;
/* Take the integer value from the pointer. */
tbl_entry = *(const uint32_t *)tbl;
/* If it is valid and extended we calculate the new pointer to return. */
if ((tbl_entry & RTE_LPM6_VALID_EXT_ENTRY_BITMASK) ==
RTE_LPM6_VALID_EXT_ENTRY_BITMASK) {
tbl8_index = ip[first_byte-1] +
((tbl_entry & RTE_LPM6_TBL8_BITMASK) *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES);
*tbl_next = &lpm->tbl8[tbl8_index];
return 1;
} else {
/* If not extended then we can have a match. */
*next_hop = (uint8_t)tbl_entry;
return (tbl_entry & RTE_LPM6_LOOKUP_SUCCESS) ? 0 : -ENOENT;
}
}
/*
* Looks up an IP
*/
int
rte_lpm6_lookup(const struct rte_lpm6 *lpm, uint8_t *ip, uint8_t *next_hop)
{
const struct rte_lpm6_tbl_entry *tbl;
const struct rte_lpm6_tbl_entry *tbl_next;
int status;
uint8_t first_byte;
uint32_t tbl24_index;
/* DEBUG: Check user input arguments. */
if ((lpm == NULL) || (ip == NULL) || (next_hop == NULL)) {
return -EINVAL;
}
first_byte = LOOKUP_FIRST_BYTE;
tbl24_index = (ip[0] << BYTES2_SIZE) | (ip[1] << BYTE_SIZE) | ip[2];
/* Calculate pointer to the first entry to be inspected */
tbl = &lpm->tbl24[tbl24_index];
do {
/* Continue inspecting following levels until success or failure */
status = lookup_step(lpm, tbl, &tbl_next, ip, first_byte++, next_hop);
tbl = tbl_next;
} while (status == 1);
return status;
}
/*
* Looks up a group of IP addresses
*/
int
rte_lpm6_lookup_bulk_func(const struct rte_lpm6 *lpm,
uint8_t ips[][RTE_LPM6_IPV6_ADDR_SIZE],
int16_t * next_hops, unsigned n)
{
unsigned i;
const struct rte_lpm6_tbl_entry *tbl;
const struct rte_lpm6_tbl_entry *tbl_next;
uint32_t tbl24_index;
uint8_t first_byte, next_hop;
int status;
/* DEBUG: Check user input arguments. */
if ((lpm == NULL) || (ips == NULL) || (next_hops == NULL)) {
return -EINVAL;
}
for (i = 0; i < n; i++) {
first_byte = LOOKUP_FIRST_BYTE;
tbl24_index = (ips[i][0] << BYTES2_SIZE) |
(ips[i][1] << BYTE_SIZE) | ips[i][2];
/* Calculate pointer to the first entry to be inspected */
tbl = &lpm->tbl24[tbl24_index];
do {
/* Continue inspecting following levels until success or failure */
status = lookup_step(lpm, tbl, &tbl_next, ips[i], first_byte++,
&next_hop);
tbl = tbl_next;
} while (status == 1);
if (status < 0)
next_hops[i] = -1;
else
next_hops[i] = next_hop;
}
return 0;
}
/*
* Finds a rule in rule table.
* NOTE: Valid range for depth parameter is 1 .. 128 inclusive.
*/
static inline int32_t
rule_find(struct rte_lpm6 *lpm, uint8_t *ip, uint8_t depth)
{
uint32_t rule_index;
/* Scan used rules at given depth to find rule. */
for (rule_index = 0; rule_index < lpm->used_rules; rule_index++) {
/* If rule is found return the rule index. */
if ((memcmp (lpm->rules_tbl[rule_index].ip, ip,
RTE_LPM6_IPV6_ADDR_SIZE) == 0) &&
lpm->rules_tbl[rule_index].depth == depth) {
return rule_index;
}
}
/* If rule is not found return -ENOENT. */
return -ENOENT;
}
/*
* Look for a rule in the high-level rules table
*/
int
rte_lpm6_is_rule_present(struct rte_lpm6 *lpm, uint8_t *ip, uint8_t depth,
uint8_t *next_hop)
{
uint8_t ip_masked[RTE_LPM6_IPV6_ADDR_SIZE];
int32_t rule_index;
/* Check user arguments. */
if ((lpm == NULL) || next_hop == NULL || ip == NULL ||
(depth < 1) || (depth > RTE_LPM6_MAX_DEPTH))
return -EINVAL;
/* Copy the IP and mask it to avoid modifying user's input data. */
memcpy(ip_masked, ip, RTE_LPM6_IPV6_ADDR_SIZE);
mask_ip(ip_masked, depth);
/* Look for the rule using rule_find. */
rule_index = rule_find(lpm, ip_masked, depth);
if (rule_index >= 0) {
*next_hop = lpm->rules_tbl[rule_index].next_hop;
return 1;
}
/* If rule is not found return 0. */
return 0;
}
/*
* Delete a rule from the rule table.
* NOTE: Valid range for depth parameter is 1 .. 128 inclusive.
*/
static inline void
rule_delete(struct rte_lpm6 *lpm, int32_t rule_index)
{
/*
* Overwrite redundant rule with last rule in group and decrement rule
* counter.
*/
lpm->rules_tbl[rule_index] = lpm->rules_tbl[lpm->used_rules-1];
lpm->used_rules--;
}
/*
* Deletes a rule
*/
int
rte_lpm6_delete(struct rte_lpm6 *lpm, uint8_t *ip, uint8_t depth)
{
int32_t rule_to_delete_index;
uint8_t ip_masked[RTE_LPM6_IPV6_ADDR_SIZE];
unsigned i;
/*
* Check input arguments.
*/
if ((lpm == NULL) || (depth < 1) || (depth > RTE_LPM6_MAX_DEPTH)) {
return -EINVAL;
}
/* Copy the IP and mask it to avoid modifying user's input data. */
memcpy(ip_masked, ip, RTE_LPM6_IPV6_ADDR_SIZE);
mask_ip(ip_masked, depth);
/*
* Find the index of the input rule, that needs to be deleted, in the
* rule table.
*/
rule_to_delete_index = rule_find(lpm, ip_masked, depth);
/*
* Check if rule_to_delete_index was found. If no rule was found the
* function rule_find returns -ENOENT.
*/
if (rule_to_delete_index < 0)
return rule_to_delete_index;
/* Delete the rule from the rule table. */
rule_delete(lpm, rule_to_delete_index);
/*
* Set all the table entries to 0 (ie delete every rule
* from the data structure.
*/
lpm->next_tbl8 = 0;
memset(lpm->tbl24, 0, sizeof(lpm->tbl24));
memset(lpm->tbl8, 0, sizeof(lpm->tbl8[0])
* RTE_LPM6_TBL8_GROUP_NUM_ENTRIES * lpm->number_tbl8s);
/*
* Add every rule again (except for the one that was removed from
* the rules table).
*/
for (i = 0; i < lpm->used_rules; i++) {
rte_lpm6_add(lpm, lpm->rules_tbl[i].ip, lpm->rules_tbl[i].depth,
lpm->rules_tbl[i].next_hop);
}
return 0;
}
/*
* Deletes a group of rules
*/
int
rte_lpm6_delete_bulk_func(struct rte_lpm6 *lpm,
uint8_t ips[][RTE_LPM6_IPV6_ADDR_SIZE], uint8_t *depths, unsigned n)
{
int32_t rule_to_delete_index;
uint8_t ip_masked[RTE_LPM6_IPV6_ADDR_SIZE];
unsigned i;
/*
* Check input arguments.
*/
if ((lpm == NULL) || (ips == NULL) || (depths == NULL)) {
return -EINVAL;
}
for (i = 0; i < n; i++) {
/* Copy the IP and mask it to avoid modifying user's input data. */
memcpy(ip_masked, ips[i], RTE_LPM6_IPV6_ADDR_SIZE);
mask_ip(ip_masked, depths[i]);
/*
* Find the index of the input rule, that needs to be deleted, in the
* rule table.
*/
rule_to_delete_index = rule_find(lpm, ip_masked, depths[i]);
/*
* Check if rule_to_delete_index was found. If no rule was found the
* function rule_find returns -ENOENT.
*/
if (rule_to_delete_index < 0)
continue;
/* Delete the rule from the rule table. */
rule_delete(lpm, rule_to_delete_index);
}
/*
* Set all the table entries to 0 (ie delete every rule
* from the data structure.
*/
lpm->next_tbl8 = 0;
memset(lpm->tbl24, 0, sizeof(lpm->tbl24));
memset(lpm->tbl8, 0, sizeof(lpm->tbl8[0])
* RTE_LPM6_TBL8_GROUP_NUM_ENTRIES * lpm->number_tbl8s);
/*
* Add every rule again (except for the ones that were removed from
* the rules table).
*/
for (i = 0; i < lpm->used_rules; i++) {
rte_lpm6_add(lpm, lpm->rules_tbl[i].ip, lpm->rules_tbl[i].depth,
lpm->rules_tbl[i].next_hop);
}
return 0;
}
/*
* Delete all rules from the LPM table.
*/
void
rte_lpm6_delete_all(struct rte_lpm6 *lpm)
{
/* Zero used rules counter. */
lpm->used_rules = 0;
/* Zero next tbl8 index. */
lpm->next_tbl8 = 0;
/* Zero tbl24. */
memset(lpm->tbl24, 0, sizeof(lpm->tbl24));
/* Zero tbl8. */
memset(lpm->tbl8, 0, sizeof(lpm->tbl8[0]) *
RTE_LPM6_TBL8_GROUP_NUM_ENTRIES * lpm->number_tbl8s);
/* Delete all rules form the rules table. */
memset(lpm->rules_tbl, 0, sizeof(struct rte_lpm6_rule) * lpm->max_rules);
}
|
206054.c | /*
* Copyright 2014, 2015 Red Hat.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* on the rights to use, copy, modify, merge, publish, distribute, sub
* license, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include "util/u_format.h"
#include "util/u_memory.h"
#include "util/u_math.h"
#include "pipe/p_state.h"
#include "tgsi/tgsi_dump.h"
#include "tgsi/tgsi_parse.h"
#include "virgl_context.h"
#include "virgl_encode.h"
#include "virgl_protocol.h"
#include "virgl_resource.h"
#include "virgl_screen.h"
static int virgl_encoder_write_cmd_dword(struct virgl_context *ctx,
uint32_t dword)
{
int len = (dword >> 16);
if ((ctx->cbuf->cdw + len + 1) > VIRGL_MAX_CMDBUF_DWORDS)
ctx->base.flush(&ctx->base, NULL, 0);
virgl_encoder_write_dword(ctx->cbuf, dword);
return 0;
}
static void virgl_encoder_write_res(struct virgl_context *ctx,
struct virgl_resource *res)
{
struct virgl_winsys *vws = virgl_screen(ctx->base.screen)->vws;
if (res && res->hw_res)
vws->emit_res(vws, ctx->cbuf, res->hw_res, TRUE);
else {
virgl_encoder_write_dword(ctx->cbuf, 0);
}
}
int virgl_encode_bind_object(struct virgl_context *ctx,
uint32_t handle, uint32_t object)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_BIND_OBJECT, object, 1));
virgl_encoder_write_dword(ctx->cbuf, handle);
return 0;
}
int virgl_encode_delete_object(struct virgl_context *ctx,
uint32_t handle, uint32_t object)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_DESTROY_OBJECT, object, 1));
virgl_encoder_write_dword(ctx->cbuf, handle);
return 0;
}
int virgl_encode_blend_state(struct virgl_context *ctx,
uint32_t handle,
const struct pipe_blend_state *blend_state)
{
uint32_t tmp;
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_BLEND, VIRGL_OBJ_BLEND_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
tmp =
VIRGL_OBJ_BLEND_S0_INDEPENDENT_BLEND_ENABLE(blend_state->independent_blend_enable) |
VIRGL_OBJ_BLEND_S0_LOGICOP_ENABLE(blend_state->logicop_enable) |
VIRGL_OBJ_BLEND_S0_DITHER(blend_state->dither) |
VIRGL_OBJ_BLEND_S0_ALPHA_TO_COVERAGE(blend_state->alpha_to_coverage) |
VIRGL_OBJ_BLEND_S0_ALPHA_TO_ONE(blend_state->alpha_to_one);
virgl_encoder_write_dword(ctx->cbuf, tmp);
tmp = VIRGL_OBJ_BLEND_S1_LOGICOP_FUNC(blend_state->logicop_func);
virgl_encoder_write_dword(ctx->cbuf, tmp);
for (i = 0; i < VIRGL_MAX_COLOR_BUFS; i++) {
tmp =
VIRGL_OBJ_BLEND_S2_RT_BLEND_ENABLE(blend_state->rt[i].blend_enable) |
VIRGL_OBJ_BLEND_S2_RT_RGB_FUNC(blend_state->rt[i].rgb_func) |
VIRGL_OBJ_BLEND_S2_RT_RGB_SRC_FACTOR(blend_state->rt[i].rgb_src_factor) |
VIRGL_OBJ_BLEND_S2_RT_RGB_DST_FACTOR(blend_state->rt[i].rgb_dst_factor)|
VIRGL_OBJ_BLEND_S2_RT_ALPHA_FUNC(blend_state->rt[i].alpha_func) |
VIRGL_OBJ_BLEND_S2_RT_ALPHA_SRC_FACTOR(blend_state->rt[i].alpha_src_factor) |
VIRGL_OBJ_BLEND_S2_RT_ALPHA_DST_FACTOR(blend_state->rt[i].alpha_dst_factor) |
VIRGL_OBJ_BLEND_S2_RT_COLORMASK(blend_state->rt[i].colormask);
virgl_encoder_write_dword(ctx->cbuf, tmp);
}
return 0;
}
int virgl_encode_dsa_state(struct virgl_context *ctx,
uint32_t handle,
const struct pipe_depth_stencil_alpha_state *dsa_state)
{
uint32_t tmp;
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_DSA, VIRGL_OBJ_DSA_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
tmp = VIRGL_OBJ_DSA_S0_DEPTH_ENABLE(dsa_state->depth.enabled) |
VIRGL_OBJ_DSA_S0_DEPTH_WRITEMASK(dsa_state->depth.writemask) |
VIRGL_OBJ_DSA_S0_DEPTH_FUNC(dsa_state->depth.func) |
VIRGL_OBJ_DSA_S0_ALPHA_ENABLED(dsa_state->alpha.enabled) |
VIRGL_OBJ_DSA_S0_ALPHA_FUNC(dsa_state->alpha.func);
virgl_encoder_write_dword(ctx->cbuf, tmp);
for (i = 0; i < 2; i++) {
tmp = VIRGL_OBJ_DSA_S1_STENCIL_ENABLED(dsa_state->stencil[i].enabled) |
VIRGL_OBJ_DSA_S1_STENCIL_FUNC(dsa_state->stencil[i].func) |
VIRGL_OBJ_DSA_S1_STENCIL_FAIL_OP(dsa_state->stencil[i].fail_op) |
VIRGL_OBJ_DSA_S1_STENCIL_ZPASS_OP(dsa_state->stencil[i].zpass_op) |
VIRGL_OBJ_DSA_S1_STENCIL_ZFAIL_OP(dsa_state->stencil[i].zfail_op) |
VIRGL_OBJ_DSA_S1_STENCIL_VALUEMASK(dsa_state->stencil[i].valuemask) |
VIRGL_OBJ_DSA_S1_STENCIL_WRITEMASK(dsa_state->stencil[i].writemask);
virgl_encoder_write_dword(ctx->cbuf, tmp);
}
virgl_encoder_write_dword(ctx->cbuf, fui(dsa_state->alpha.ref_value));
return 0;
}
int virgl_encode_rasterizer_state(struct virgl_context *ctx,
uint32_t handle,
const struct pipe_rasterizer_state *state)
{
uint32_t tmp;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_RASTERIZER, VIRGL_OBJ_RS_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
tmp = VIRGL_OBJ_RS_S0_FLATSHADE(state->flatshade) |
VIRGL_OBJ_RS_S0_DEPTH_CLIP(state->depth_clip) |
VIRGL_OBJ_RS_S0_CLIP_HALFZ(state->clip_halfz) |
VIRGL_OBJ_RS_S0_RASTERIZER_DISCARD(state->rasterizer_discard) |
VIRGL_OBJ_RS_S0_FLATSHADE_FIRST(state->flatshade_first) |
VIRGL_OBJ_RS_S0_LIGHT_TWOSIZE(state->light_twoside) |
VIRGL_OBJ_RS_S0_SPRITE_COORD_MODE(state->sprite_coord_mode) |
VIRGL_OBJ_RS_S0_POINT_QUAD_RASTERIZATION(state->point_quad_rasterization) |
VIRGL_OBJ_RS_S0_CULL_FACE(state->cull_face) |
VIRGL_OBJ_RS_S0_FILL_FRONT(state->fill_front) |
VIRGL_OBJ_RS_S0_FILL_BACK(state->fill_back) |
VIRGL_OBJ_RS_S0_SCISSOR(state->scissor) |
VIRGL_OBJ_RS_S0_FRONT_CCW(state->front_ccw) |
VIRGL_OBJ_RS_S0_CLAMP_VERTEX_COLOR(state->clamp_vertex_color) |
VIRGL_OBJ_RS_S0_CLAMP_FRAGMENT_COLOR(state->clamp_fragment_color) |
VIRGL_OBJ_RS_S0_OFFSET_LINE(state->offset_line) |
VIRGL_OBJ_RS_S0_OFFSET_POINT(state->offset_point) |
VIRGL_OBJ_RS_S0_OFFSET_TRI(state->offset_tri) |
VIRGL_OBJ_RS_S0_POLY_SMOOTH(state->poly_smooth) |
VIRGL_OBJ_RS_S0_POLY_STIPPLE_ENABLE(state->poly_stipple_enable) |
VIRGL_OBJ_RS_S0_POINT_SMOOTH(state->point_smooth) |
VIRGL_OBJ_RS_S0_POINT_SIZE_PER_VERTEX(state->point_size_per_vertex) |
VIRGL_OBJ_RS_S0_MULTISAMPLE(state->multisample) |
VIRGL_OBJ_RS_S0_LINE_SMOOTH(state->line_smooth) |
VIRGL_OBJ_RS_S0_LINE_STIPPLE_ENABLE(state->line_stipple_enable) |
VIRGL_OBJ_RS_S0_LINE_LAST_PIXEL(state->line_last_pixel) |
VIRGL_OBJ_RS_S0_HALF_PIXEL_CENTER(state->half_pixel_center) |
VIRGL_OBJ_RS_S0_BOTTOM_EDGE_RULE(state->bottom_edge_rule);
virgl_encoder_write_dword(ctx->cbuf, tmp); /* S0 */
virgl_encoder_write_dword(ctx->cbuf, fui(state->point_size)); /* S1 */
virgl_encoder_write_dword(ctx->cbuf, state->sprite_coord_enable); /* S2 */
tmp = VIRGL_OBJ_RS_S3_LINE_STIPPLE_PATTERN(state->line_stipple_pattern) |
VIRGL_OBJ_RS_S3_LINE_STIPPLE_FACTOR(state->line_stipple_factor) |
VIRGL_OBJ_RS_S3_CLIP_PLANE_ENABLE(state->clip_plane_enable);
virgl_encoder_write_dword(ctx->cbuf, tmp); /* S3 */
virgl_encoder_write_dword(ctx->cbuf, fui(state->line_width)); /* S4 */
virgl_encoder_write_dword(ctx->cbuf, fui(state->offset_units)); /* S5 */
virgl_encoder_write_dword(ctx->cbuf, fui(state->offset_scale)); /* S6 */
virgl_encoder_write_dword(ctx->cbuf, fui(state->offset_clamp)); /* S7 */
return 0;
}
static void virgl_emit_shader_header(struct virgl_context *ctx,
uint32_t handle, uint32_t len,
uint32_t type, uint32_t offlen,
uint32_t num_tokens)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_SHADER, len));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_dword(ctx->cbuf, type);
virgl_encoder_write_dword(ctx->cbuf, offlen);
virgl_encoder_write_dword(ctx->cbuf, num_tokens);
}
static void virgl_emit_shader_streamout(struct virgl_context *ctx,
const struct pipe_stream_output_info *so_info)
{
int num_outputs = 0;
int i;
uint32_t tmp;
if (so_info)
num_outputs = so_info->num_outputs;
virgl_encoder_write_dword(ctx->cbuf, num_outputs);
if (num_outputs) {
for (i = 0; i < 4; i++)
virgl_encoder_write_dword(ctx->cbuf, so_info->stride[i]);
for (i = 0; i < so_info->num_outputs; i++) {
tmp =
VIRGL_OBJ_SHADER_SO_OUTPUT_REGISTER_INDEX(so_info->output[i].register_index) |
VIRGL_OBJ_SHADER_SO_OUTPUT_START_COMPONENT(so_info->output[i].start_component) |
VIRGL_OBJ_SHADER_SO_OUTPUT_NUM_COMPONENTS(so_info->output[i].num_components) |
VIRGL_OBJ_SHADER_SO_OUTPUT_BUFFER(so_info->output[i].output_buffer) |
VIRGL_OBJ_SHADER_SO_OUTPUT_DST_OFFSET(so_info->output[i].dst_offset);
virgl_encoder_write_dword(ctx->cbuf, tmp);
virgl_encoder_write_dword(ctx->cbuf, 0);
}
}
}
int virgl_encode_shader_state(struct virgl_context *ctx,
uint32_t handle,
uint32_t type,
const struct pipe_stream_output_info *so_info,
const struct tgsi_token *tokens)
{
char *str, *sptr;
uint32_t shader_len, len;
bool bret;
int num_tokens = tgsi_num_tokens(tokens);
int str_total_size = 65536;
int retry_size = 1;
uint32_t left_bytes, base_hdr_size, strm_hdr_size, thispass;
bool first_pass;
str = CALLOC(1, str_total_size);
if (!str)
return -1;
do {
int old_size;
bret = tgsi_dump_str(tokens, TGSI_DUMP_FLOAT_AS_HEX, str, str_total_size);
if (bret == false) {
fprintf(stderr, "Failed to translate shader in available space - trying again\n");
old_size = str_total_size;
str_total_size = 65536 * ++retry_size;
str = REALLOC(str, old_size, str_total_size);
if (!str)
return -1;
}
} while (bret == false && retry_size < 10);
if (bret == false)
return -1;
shader_len = strlen(str) + 1;
left_bytes = shader_len;
base_hdr_size = 5;
strm_hdr_size = so_info->num_outputs ? so_info->num_outputs * 2 + 4 : 0;
first_pass = true;
sptr = str;
while (left_bytes) {
uint32_t length, offlen;
int hdr_len = base_hdr_size + (first_pass ? strm_hdr_size : 0);
if (ctx->cbuf->cdw + hdr_len + 1 > VIRGL_MAX_CMDBUF_DWORDS)
ctx->base.flush(&ctx->base, NULL, 0);
thispass = (VIRGL_MAX_CMDBUF_DWORDS - ctx->cbuf->cdw - hdr_len - 1) * 4;
length = MIN2(thispass, left_bytes);
len = ((length + 3) / 4) + hdr_len;
if (first_pass)
offlen = VIRGL_OBJ_SHADER_OFFSET_VAL(shader_len);
else
offlen = VIRGL_OBJ_SHADER_OFFSET_VAL((uintptr_t)sptr - (uintptr_t)str) | VIRGL_OBJ_SHADER_OFFSET_CONT;
virgl_emit_shader_header(ctx, handle, len, type, offlen, num_tokens);
virgl_emit_shader_streamout(ctx, first_pass ? so_info : NULL);
virgl_encoder_write_block(ctx->cbuf, (uint8_t *)sptr, length);
sptr += length;
first_pass = false;
left_bytes -= length;
}
FREE(str);
return 0;
}
int virgl_encode_clear(struct virgl_context *ctx,
unsigned buffers,
const union pipe_color_union *color,
double depth, unsigned stencil)
{
int i;
uint64_t qword;
STATIC_ASSERT(sizeof(qword) == sizeof(depth));
memcpy(&qword, &depth, sizeof(qword));
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CLEAR, 0, VIRGL_OBJ_CLEAR_SIZE));
virgl_encoder_write_dword(ctx->cbuf, buffers);
for (i = 0; i < 4; i++)
virgl_encoder_write_dword(ctx->cbuf, color->ui[i]);
virgl_encoder_write_qword(ctx->cbuf, qword);
virgl_encoder_write_dword(ctx->cbuf, stencil);
return 0;
}
int virgl_encoder_set_framebuffer_state(struct virgl_context *ctx,
const struct pipe_framebuffer_state *state)
{
struct virgl_surface *zsurf = virgl_surface(state->zsbuf);
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_FRAMEBUFFER_STATE, 0, VIRGL_SET_FRAMEBUFFER_STATE_SIZE(state->nr_cbufs)));
virgl_encoder_write_dword(ctx->cbuf, state->nr_cbufs);
virgl_encoder_write_dword(ctx->cbuf, zsurf ? zsurf->handle : 0);
for (i = 0; i < state->nr_cbufs; i++) {
struct virgl_surface *surf = virgl_surface(state->cbufs[i]);
virgl_encoder_write_dword(ctx->cbuf, surf ? surf->handle : 0);
}
return 0;
}
int virgl_encoder_set_viewport_states(struct virgl_context *ctx,
int start_slot,
int num_viewports,
const struct pipe_viewport_state *states)
{
int i,v;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_VIEWPORT_STATE, 0, VIRGL_SET_VIEWPORT_STATE_SIZE(num_viewports)));
virgl_encoder_write_dword(ctx->cbuf, start_slot);
for (v = 0; v < num_viewports; v++) {
for (i = 0; i < 3; i++)
virgl_encoder_write_dword(ctx->cbuf, fui(states[v].scale[i]));
for (i = 0; i < 3; i++)
virgl_encoder_write_dword(ctx->cbuf, fui(states[v].translate[i]));
}
return 0;
}
int virgl_encoder_create_vertex_elements(struct virgl_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *element)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_VERTEX_ELEMENTS, VIRGL_OBJ_VERTEX_ELEMENTS_SIZE(num_elements)));
virgl_encoder_write_dword(ctx->cbuf, handle);
for (i = 0; i < num_elements; i++) {
virgl_encoder_write_dword(ctx->cbuf, element[i].src_offset);
virgl_encoder_write_dword(ctx->cbuf, element[i].instance_divisor);
virgl_encoder_write_dword(ctx->cbuf, element[i].vertex_buffer_index);
virgl_encoder_write_dword(ctx->cbuf, element[i].src_format);
}
return 0;
}
int virgl_encoder_set_vertex_buffers(struct virgl_context *ctx,
unsigned num_buffers,
const struct pipe_vertex_buffer *buffers)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_VERTEX_BUFFERS, 0, VIRGL_SET_VERTEX_BUFFERS_SIZE(num_buffers)));
for (i = 0; i < num_buffers; i++) {
struct virgl_resource *res = virgl_resource(buffers[i].buffer.resource);
virgl_encoder_write_dword(ctx->cbuf, buffers[i].stride);
virgl_encoder_write_dword(ctx->cbuf, buffers[i].buffer_offset);
virgl_encoder_write_res(ctx, res);
}
return 0;
}
int virgl_encoder_set_index_buffer(struct virgl_context *ctx,
const struct virgl_indexbuf *ib)
{
int length = VIRGL_SET_INDEX_BUFFER_SIZE(ib);
struct virgl_resource *res = NULL;
if (ib)
res = virgl_resource(ib->buffer);
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_INDEX_BUFFER, 0, length));
virgl_encoder_write_res(ctx, res);
if (ib) {
virgl_encoder_write_dword(ctx->cbuf, ib->index_size);
virgl_encoder_write_dword(ctx->cbuf, ib->offset);
}
return 0;
}
int virgl_encoder_draw_vbo(struct virgl_context *ctx,
const struct pipe_draw_info *info)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_DRAW_VBO, 0, VIRGL_DRAW_VBO_SIZE));
virgl_encoder_write_dword(ctx->cbuf, info->start);
virgl_encoder_write_dword(ctx->cbuf, info->count);
virgl_encoder_write_dword(ctx->cbuf, info->mode);
virgl_encoder_write_dword(ctx->cbuf, !!info->index_size);
virgl_encoder_write_dword(ctx->cbuf, info->instance_count);
virgl_encoder_write_dword(ctx->cbuf, info->index_bias);
virgl_encoder_write_dword(ctx->cbuf, info->start_instance);
virgl_encoder_write_dword(ctx->cbuf, info->primitive_restart);
virgl_encoder_write_dword(ctx->cbuf, info->restart_index);
virgl_encoder_write_dword(ctx->cbuf, info->min_index);
virgl_encoder_write_dword(ctx->cbuf, info->max_index);
if (info->count_from_stream_output)
virgl_encoder_write_dword(ctx->cbuf, info->count_from_stream_output->buffer_size);
else
virgl_encoder_write_dword(ctx->cbuf, 0);
return 0;
}
int virgl_encoder_create_surface(struct virgl_context *ctx,
uint32_t handle,
struct virgl_resource *res,
const struct pipe_surface *templat)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_SURFACE, VIRGL_OBJ_SURFACE_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_res(ctx, res);
virgl_encoder_write_dword(ctx->cbuf, templat->format);
if (templat->texture->target == PIPE_BUFFER) {
virgl_encoder_write_dword(ctx->cbuf, templat->u.buf.first_element);
virgl_encoder_write_dword(ctx->cbuf, templat->u.buf.last_element);
} else {
virgl_encoder_write_dword(ctx->cbuf, templat->u.tex.level);
virgl_encoder_write_dword(ctx->cbuf, templat->u.tex.first_layer | (templat->u.tex.last_layer << 16));
}
return 0;
}
int virgl_encoder_create_so_target(struct virgl_context *ctx,
uint32_t handle,
struct virgl_resource *res,
unsigned buffer_offset,
unsigned buffer_size)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_STREAMOUT_TARGET, VIRGL_OBJ_STREAMOUT_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_res(ctx, res);
virgl_encoder_write_dword(ctx->cbuf, buffer_offset);
virgl_encoder_write_dword(ctx->cbuf, buffer_size);
return 0;
}
static void virgl_encoder_iw_emit_header_1d(struct virgl_context *ctx,
struct virgl_resource *res,
unsigned level, unsigned usage,
const struct pipe_box *box,
unsigned stride, unsigned layer_stride)
{
virgl_encoder_write_res(ctx, res);
virgl_encoder_write_dword(ctx->cbuf, level);
virgl_encoder_write_dword(ctx->cbuf, usage);
virgl_encoder_write_dword(ctx->cbuf, stride);
virgl_encoder_write_dword(ctx->cbuf, layer_stride);
virgl_encoder_write_dword(ctx->cbuf, box->x);
virgl_encoder_write_dword(ctx->cbuf, box->y);
virgl_encoder_write_dword(ctx->cbuf, box->z);
virgl_encoder_write_dword(ctx->cbuf, box->width);
virgl_encoder_write_dword(ctx->cbuf, box->height);
virgl_encoder_write_dword(ctx->cbuf, box->depth);
}
int virgl_encoder_inline_write(struct virgl_context *ctx,
struct virgl_resource *res,
unsigned level, unsigned usage,
const struct pipe_box *box,
const void *data, unsigned stride,
unsigned layer_stride)
{
uint32_t size = (stride ? stride : box->width) * box->height;
uint32_t length, thispass, left_bytes;
struct pipe_box mybox = *box;
length = 11 + (size + 3) / 4;
if ((ctx->cbuf->cdw + length + 1) > VIRGL_MAX_CMDBUF_DWORDS) {
if (box->height > 1 || box->depth > 1) {
debug_printf("inline transfer failed due to multi dimensions and too large\n");
assert(0);
}
}
left_bytes = size;
while (left_bytes) {
if (ctx->cbuf->cdw + 12 > VIRGL_MAX_CMDBUF_DWORDS)
ctx->base.flush(&ctx->base, NULL, 0);
thispass = (VIRGL_MAX_CMDBUF_DWORDS - ctx->cbuf->cdw - 12) * 4;
length = MIN2(thispass, left_bytes);
mybox.width = length;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_RESOURCE_INLINE_WRITE, 0, ((length + 3) / 4) + 11));
virgl_encoder_iw_emit_header_1d(ctx, res, level, usage, &mybox, stride, layer_stride);
virgl_encoder_write_block(ctx->cbuf, data, length);
left_bytes -= length;
mybox.x += length;
data += length;
}
return 0;
}
int virgl_encoder_flush_frontbuffer(struct virgl_context *ctx,
struct virgl_resource *res)
{
// virgl_encoder_write_dword(ctx->cbuf, VIRGL_CMD0(VIRGL_CCMD_FLUSH_FRONTUBFFER, 0, 1));
// virgl_encoder_write_dword(ctx->cbuf, res_handle);
return 0;
}
int virgl_encode_sampler_state(struct virgl_context *ctx,
uint32_t handle,
const struct pipe_sampler_state *state)
{
uint32_t tmp;
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_SAMPLER_STATE, VIRGL_OBJ_SAMPLER_STATE_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
tmp = VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_S(state->wrap_s) |
VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_T(state->wrap_t) |
VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_R(state->wrap_r) |
VIRGL_OBJ_SAMPLE_STATE_S0_MIN_IMG_FILTER(state->min_img_filter) |
VIRGL_OBJ_SAMPLE_STATE_S0_MIN_MIP_FILTER(state->min_mip_filter) |
VIRGL_OBJ_SAMPLE_STATE_S0_MAG_IMG_FILTER(state->mag_img_filter) |
VIRGL_OBJ_SAMPLE_STATE_S0_COMPARE_MODE(state->compare_mode) |
VIRGL_OBJ_SAMPLE_STATE_S0_COMPARE_FUNC(state->compare_func);
virgl_encoder_write_dword(ctx->cbuf, tmp);
virgl_encoder_write_dword(ctx->cbuf, fui(state->lod_bias));
virgl_encoder_write_dword(ctx->cbuf, fui(state->min_lod));
virgl_encoder_write_dword(ctx->cbuf, fui(state->max_lod));
for (i = 0; i < 4; i++)
virgl_encoder_write_dword(ctx->cbuf, state->border_color.ui[i]);
return 0;
}
int virgl_encode_sampler_view(struct virgl_context *ctx,
uint32_t handle,
struct virgl_resource *res,
const struct pipe_sampler_view *state)
{
unsigned elem_size = util_format_get_blocksize(state->format);
uint32_t tmp;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_SAMPLER_VIEW, VIRGL_OBJ_SAMPLER_VIEW_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_res(ctx, res);
virgl_encoder_write_dword(ctx->cbuf, state->format);
if (res->u.b.target == PIPE_BUFFER) {
virgl_encoder_write_dword(ctx->cbuf, state->u.buf.offset / elem_size);
virgl_encoder_write_dword(ctx->cbuf, (state->u.buf.offset + state->u.buf.size) / elem_size - 1);
} else {
virgl_encoder_write_dword(ctx->cbuf, state->u.tex.first_layer | state->u.tex.last_layer << 16);
virgl_encoder_write_dword(ctx->cbuf, state->u.tex.first_level | state->u.tex.last_level << 8);
}
tmp = VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_R(state->swizzle_r) |
VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_G(state->swizzle_g) |
VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_B(state->swizzle_b) |
VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_A(state->swizzle_a);
virgl_encoder_write_dword(ctx->cbuf, tmp);
return 0;
}
int virgl_encode_set_sampler_views(struct virgl_context *ctx,
uint32_t shader_type,
uint32_t start_slot,
uint32_t num_views,
struct virgl_sampler_view **views)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_SAMPLER_VIEWS, 0, VIRGL_SET_SAMPLER_VIEWS_SIZE(num_views)));
virgl_encoder_write_dword(ctx->cbuf, shader_type);
virgl_encoder_write_dword(ctx->cbuf, start_slot);
for (i = 0; i < num_views; i++) {
uint32_t handle = views[i] ? views[i]->handle : 0;
virgl_encoder_write_dword(ctx->cbuf, handle);
}
return 0;
}
int virgl_encode_bind_sampler_states(struct virgl_context *ctx,
uint32_t shader_type,
uint32_t start_slot,
uint32_t num_handles,
uint32_t *handles)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_BIND_SAMPLER_STATES, 0, VIRGL_BIND_SAMPLER_STATES(num_handles)));
virgl_encoder_write_dword(ctx->cbuf, shader_type);
virgl_encoder_write_dword(ctx->cbuf, start_slot);
for (i = 0; i < num_handles; i++)
virgl_encoder_write_dword(ctx->cbuf, handles[i]);
return 0;
}
int virgl_encoder_write_constant_buffer(struct virgl_context *ctx,
uint32_t shader,
uint32_t index,
uint32_t size,
const void *data)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_CONSTANT_BUFFER, 0, size + 2));
virgl_encoder_write_dword(ctx->cbuf, shader);
virgl_encoder_write_dword(ctx->cbuf, index);
if (data)
virgl_encoder_write_block(ctx->cbuf, data, size * 4);
return 0;
}
int virgl_encoder_set_uniform_buffer(struct virgl_context *ctx,
uint32_t shader,
uint32_t index,
uint32_t offset,
uint32_t length,
struct virgl_resource *res)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_UNIFORM_BUFFER, 0, VIRGL_SET_UNIFORM_BUFFER_SIZE));
virgl_encoder_write_dword(ctx->cbuf, shader);
virgl_encoder_write_dword(ctx->cbuf, index);
virgl_encoder_write_dword(ctx->cbuf, offset);
virgl_encoder_write_dword(ctx->cbuf, length);
virgl_encoder_write_res(ctx, res);
return 0;
}
int virgl_encoder_set_stencil_ref(struct virgl_context *ctx,
const struct pipe_stencil_ref *ref)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_STENCIL_REF, 0, VIRGL_SET_STENCIL_REF_SIZE));
virgl_encoder_write_dword(ctx->cbuf, VIRGL_STENCIL_REF_VAL(ref->ref_value[0] , (ref->ref_value[1])));
return 0;
}
int virgl_encoder_set_blend_color(struct virgl_context *ctx,
const struct pipe_blend_color *color)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_BLEND_COLOR, 0, VIRGL_SET_BLEND_COLOR_SIZE));
for (i = 0; i < 4; i++)
virgl_encoder_write_dword(ctx->cbuf, fui(color->color[i]));
return 0;
}
int virgl_encoder_set_scissor_state(struct virgl_context *ctx,
unsigned start_slot,
int num_scissors,
const struct pipe_scissor_state *ss)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_SCISSOR_STATE, 0, VIRGL_SET_SCISSOR_STATE_SIZE(num_scissors)));
virgl_encoder_write_dword(ctx->cbuf, start_slot);
for (i = 0; i < num_scissors; i++) {
virgl_encoder_write_dword(ctx->cbuf, (ss[i].minx | ss[i].miny << 16));
virgl_encoder_write_dword(ctx->cbuf, (ss[i].maxx | ss[i].maxy << 16));
}
return 0;
}
void virgl_encoder_set_polygon_stipple(struct virgl_context *ctx,
const struct pipe_poly_stipple *ps)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_POLYGON_STIPPLE, 0, VIRGL_POLYGON_STIPPLE_SIZE));
for (i = 0; i < VIRGL_POLYGON_STIPPLE_SIZE; i++) {
virgl_encoder_write_dword(ctx->cbuf, ps->stipple[i]);
}
}
void virgl_encoder_set_sample_mask(struct virgl_context *ctx,
unsigned sample_mask)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_SAMPLE_MASK, 0, VIRGL_SET_SAMPLE_MASK_SIZE));
virgl_encoder_write_dword(ctx->cbuf, sample_mask);
}
void virgl_encoder_set_clip_state(struct virgl_context *ctx,
const struct pipe_clip_state *clip)
{
int i, j;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_CLIP_STATE, 0, VIRGL_SET_CLIP_STATE_SIZE));
for (i = 0; i < VIRGL_MAX_CLIP_PLANES; i++) {
for (j = 0; j < 4; j++) {
virgl_encoder_write_dword(ctx->cbuf, fui(clip->ucp[i][j]));
}
}
}
int virgl_encode_resource_copy_region(struct virgl_context *ctx,
struct virgl_resource *dst_res,
unsigned dst_level,
unsigned dstx, unsigned dsty, unsigned dstz,
struct virgl_resource *src_res,
unsigned src_level,
const struct pipe_box *src_box)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_RESOURCE_COPY_REGION, 0, VIRGL_CMD_RESOURCE_COPY_REGION_SIZE));
virgl_encoder_write_res(ctx, dst_res);
virgl_encoder_write_dword(ctx->cbuf, dst_level);
virgl_encoder_write_dword(ctx->cbuf, dstx);
virgl_encoder_write_dword(ctx->cbuf, dsty);
virgl_encoder_write_dword(ctx->cbuf, dstz);
virgl_encoder_write_res(ctx, src_res);
virgl_encoder_write_dword(ctx->cbuf, src_level);
virgl_encoder_write_dword(ctx->cbuf, src_box->x);
virgl_encoder_write_dword(ctx->cbuf, src_box->y);
virgl_encoder_write_dword(ctx->cbuf, src_box->z);
virgl_encoder_write_dword(ctx->cbuf, src_box->width);
virgl_encoder_write_dword(ctx->cbuf, src_box->height);
virgl_encoder_write_dword(ctx->cbuf, src_box->depth);
return 0;
}
int virgl_encode_blit(struct virgl_context *ctx,
struct virgl_resource *dst_res,
struct virgl_resource *src_res,
const struct pipe_blit_info *blit)
{
uint32_t tmp;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_BLIT, 0, VIRGL_CMD_BLIT_SIZE));
tmp = VIRGL_CMD_BLIT_S0_MASK(blit->mask) |
VIRGL_CMD_BLIT_S0_FILTER(blit->filter) |
VIRGL_CMD_BLIT_S0_SCISSOR_ENABLE(blit->scissor_enable) |
VIRGL_CMD_BLIT_S0_RENDER_CONDITION_ENABLE(blit->render_condition_enable) |
VIRGL_CMD_BLIT_S0_ALPHA_BLEND(blit->alpha_blend);
virgl_encoder_write_dword(ctx->cbuf, tmp);
virgl_encoder_write_dword(ctx->cbuf, (blit->scissor.minx | blit->scissor.miny << 16));
virgl_encoder_write_dword(ctx->cbuf, (blit->scissor.maxx | blit->scissor.maxy << 16));
virgl_encoder_write_res(ctx, dst_res);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.level);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.format);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.x);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.y);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.z);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.width);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.height);
virgl_encoder_write_dword(ctx->cbuf, blit->dst.box.depth);
virgl_encoder_write_res(ctx, src_res);
virgl_encoder_write_dword(ctx->cbuf, blit->src.level);
virgl_encoder_write_dword(ctx->cbuf, blit->src.format);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.x);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.y);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.z);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.width);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.height);
virgl_encoder_write_dword(ctx->cbuf, blit->src.box.depth);
return 0;
}
int virgl_encoder_create_query(struct virgl_context *ctx,
uint32_t handle,
uint query_type,
uint query_index,
struct virgl_resource *res,
uint32_t offset)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_OBJECT, VIRGL_OBJECT_QUERY, VIRGL_OBJ_QUERY_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_dword(ctx->cbuf, ((query_type & 0xffff) | (query_index << 16)));
virgl_encoder_write_dword(ctx->cbuf, offset);
virgl_encoder_write_res(ctx, res);
return 0;
}
int virgl_encoder_begin_query(struct virgl_context *ctx,
uint32_t handle)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_BEGIN_QUERY, 0, 1));
virgl_encoder_write_dword(ctx->cbuf, handle);
return 0;
}
int virgl_encoder_end_query(struct virgl_context *ctx,
uint32_t handle)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_END_QUERY, 0, 1));
virgl_encoder_write_dword(ctx->cbuf, handle);
return 0;
}
int virgl_encoder_get_query_result(struct virgl_context *ctx,
uint32_t handle, boolean wait)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_GET_QUERY_RESULT, 0, 2));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_dword(ctx->cbuf, wait ? 1 : 0);
return 0;
}
int virgl_encoder_render_condition(struct virgl_context *ctx,
uint32_t handle, boolean condition,
enum pipe_render_cond_flag mode)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_RENDER_CONDITION, 0, VIRGL_RENDER_CONDITION_SIZE));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_dword(ctx->cbuf, condition);
virgl_encoder_write_dword(ctx->cbuf, mode);
return 0;
}
int virgl_encoder_set_so_targets(struct virgl_context *ctx,
unsigned num_targets,
struct pipe_stream_output_target **targets,
unsigned append_bitmask)
{
int i;
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_STREAMOUT_TARGETS, 0, num_targets + 1));
virgl_encoder_write_dword(ctx->cbuf, append_bitmask);
for (i = 0; i < num_targets; i++) {
struct virgl_so_target *tg = virgl_so_target(targets[i]);
virgl_encoder_write_dword(ctx->cbuf, tg->handle);
}
return 0;
}
int virgl_encoder_set_sub_ctx(struct virgl_context *ctx, uint32_t sub_ctx_id)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_SET_SUB_CTX, 0, 1));
virgl_encoder_write_dword(ctx->cbuf, sub_ctx_id);
return 0;
}
int virgl_encoder_create_sub_ctx(struct virgl_context *ctx, uint32_t sub_ctx_id)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_CREATE_SUB_CTX, 0, 1));
virgl_encoder_write_dword(ctx->cbuf, sub_ctx_id);
return 0;
}
int virgl_encoder_destroy_sub_ctx(struct virgl_context *ctx, uint32_t sub_ctx_id)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_DESTROY_SUB_CTX, 0, 1));
virgl_encoder_write_dword(ctx->cbuf, sub_ctx_id);
return 0;
}
int virgl_encode_bind_shader(struct virgl_context *ctx,
uint32_t handle, uint32_t type)
{
virgl_encoder_write_cmd_dword(ctx, VIRGL_CMD0(VIRGL_CCMD_BIND_SHADER, 0, 2));
virgl_encoder_write_dword(ctx->cbuf, handle);
virgl_encoder_write_dword(ctx->cbuf, type);
return 0;
}
|
952152.c | /*
Al ingresar un número entero desde teclado diferente de cero
Lo multiplica por menos uno
y lo hace varias veces hasta que se ingresa un número
mayor de -10 o menor de 10
Y al final muestra la suma de todos los numeros ingresados
*/
#include <stdio.h>
int main(void){
int iNumero,
iSuma = 0;
do{
printf("\nIngresa un n%cmero entero: ",163);
scanf("%d",&iNumero);
if(iNumero == 0){
printf("\nERROR.El cero NO es ni positivo ni negativo");
printf("\nPor lo tanto el cero no tiene inverso");
}//fin if
iNumero *= (-1);
printf("\nEl inverso de tu n%cmero es: %d",163,iNumero);
/*
printf("\nEl inverso de tu n%cmero es: %d",163,-iNumero);
*/
iSuma += iNumero;
//iSuma = iSuma + iNumero;
}while(iNumero >= -10 && iNumero <= 10);//fin do-while
printf("\nEl resultado de la suma de todos los n%cmeros es: %d",163,iSuma);
return 0;
}//fin int main
|
975614.c |
#include <stdint.h>
#include <oneos_config.h>
#include <spi.h>
#include <drv_spi.h>
#include <drv_gpio.h>
#ifdef OS_USING_SHELL
#include <drv_log.h>
#include <shell.h>
#endif
#define AT45DBXX_BUS_NAME "at45dbxx_spi"
#define AT45DB_CMD_JEDEC_ID 0x9F
struct JEDEC_ID
{
uint8_t manufacturer_id; /* Manufacturer ID */
uint8_t density_code : 5; /* Density Code */
uint8_t family_code : 3; /* Family Code */
uint8_t version_code : 5; /* Product Version Code */
uint8_t mlc_code : 3; /* MLC Code */
uint8_t byte_count; /* Byte Count */
};
#define BSP_AT45DBXX_SPI_CS GET_PIN(B, 12)
void spi_test(void)
{
const char *spi_device_name = "spi1";
struct os_spi_device *os_spi_device;
struct JEDEC_ID *JEDEC_ID;
os_hw_spi_device_attach(spi_device_name, AT45DBXX_BUS_NAME, BSP_AT45DBXX_SPI_CS);
os_spi_device = (struct os_spi_device *)os_device_find(AT45DBXX_BUS_NAME);
if (os_spi_device == OS_NULL)
{
LOG_EXT_E("spi device %s not found!\r\n", AT45DBXX_BUS_NAME);
return ;
}
/* config spi */
{
struct os_spi_configuration cfg;
cfg.data_width = 8;
cfg.mode = OS_SPI_MODE_0 | OS_SPI_MSB; /* SPI Compatible Modes 0 and 3 */
cfg.max_hz = 6000000; /* Atmel RapidS Serial Interface: 66MHz Maximum Clock Frequency */
os_spi_configure(os_spi_device, &cfg);
}
/* read JEDEC ID */
uint8_t cmd;
uint8_t id_recv[6];
JEDEC_ID = (struct JEDEC_ID *)id_recv;
cmd = AT45DB_CMD_JEDEC_ID;
os_spi_send_then_recv(os_spi_device, &cmd, 1, id_recv, 6);
if (JEDEC_ID->manufacturer_id != 0x1F || JEDEC_ID->family_code != 0x01)
{
LOG_EXT_E("Manufacturer ID or Memory Type error!\r\n");
LOG_EXT_E("JEDEC Read-ID Data : %02X %02X %02X\r\n", id_recv[0], id_recv[1], id_recv[2]);
return;
}
}
SH_CMD_EXPORT(spi_test, spi_test, "spi_test");
|
188073.c | /*
$Id$
Copyright (C) 2008-2011, The Perl Foundation.
=head1 NAME
src/binder/multidispatch.c - Perl 6 multi-dispatcher
=head1 DESCRIPTION
This implements Perl 6 multiple dispatch.
=cut
*/
#define PARROT_IN_EXTENSION
#include "parrot/parrot.h"
#include "parrot/extend.h"
#include "bind.h"
#include "multidispatch.h"
#include "container.h"
#include "types.h"
#include "sixmodelobject.h"
/* Some constants for candidate sorter. */
#define EDGE_REMOVAL_TODO -1
#define EDGE_REMOVED -2
/* Some constants for the dispatcher. */
#define MMD_ONE_RESULT 0
#define MMD_MANY_RESULTS 1
/* Special value we set arity to when we have a slurpy. */
#define SLURPY_ARITY 1 << 30
/*
=head1 FUNCTIONS
=over 4
=item C<static INTVAL is_narrower(PARROT_INTERP, Rakudo_md_candidate_info *a, Rakudo_md_candidate_info *b)>
Takes two candidates and determines if the first one is narrower than the
second. Returns a true value if they are.
=cut
*/
static INTVAL is_narrower(PARROT_INTERP, Rakudo_md_candidate_info *a, Rakudo_md_candidate_info *b) {
INTVAL narrower = 0;
INTVAL tied = 0;
INTVAL i, types_to_check;
/* Work out how many parameters to compare, factoring in slurpiness
* and optionals. */
if (a->num_types == b->num_types)
types_to_check = a->num_types;
else if (a->min_arity == b->min_arity)
types_to_check = a->num_types > b->num_types ? b->num_types : a->num_types;
else if (a->max_arity != SLURPY_ARITY && b->max_arity == SLURPY_ARITY)
return 1;
else
return 0;
/* Analyse each parameter in the two candidates. */
for (i = 0; i < types_to_check; i++) {
PMC * const type_obj_a = a->types[i];
PMC * const type_obj_b = b->types[i];
if (type_obj_a == type_obj_b) {
/* Same type; narrower if first has constraints and other doesn't;
* tied if neither has constraints or both have constraints. */
if (!PMC_IS_NULL(a->constraints[i]) && PMC_IS_NULL(b->constraints[i]))
narrower++;
else if ((PMC_IS_NULL(a->constraints[i]) && PMC_IS_NULL(b->constraints[i]))
||
(!PMC_IS_NULL(a->constraints[i]) && !PMC_IS_NULL(b->constraints[i])))
tied++;
}
else if ((a->type_flags[i] & TYPE_NATIVE_MASK) && !(b->type_flags[i] & TYPE_NATIVE_MASK))
{
/* Narrower because natives always are. */
narrower++;
}
else if ((b->type_flags[i] & TYPE_NATIVE_MASK) && !(a->type_flags[i] & TYPE_NATIVE_MASK))
{
/* Wider; skip over here so we don't go counting this as tied in
* the next branch. */
}
else {
if (STABLE(type_obj_a)->type_check(interp, type_obj_a, type_obj_b)) {
/* Narrower - note it and we're done. */
narrower++;
}
else {
/* Make sure it's tied, rather than the other way around. */
if (!STABLE(type_obj_b)->type_check(interp, type_obj_b, type_obj_a))
tied++;
}
}
}
/* If one is narrower than the other from current analysis, we're done. */
if (narrower >= 1 && narrower + tied == types_to_check)
return 1;
/* If they aren't tied, we're also done. */
else if (tied != types_to_check)
return 0;
/* Otherwise, we see if one has a slurpy and the other not. A lack of
* slurpiness makes the candidate narrower. */
if (a->max_arity != SLURPY_ARITY && b->max_arity == SLURPY_ARITY) {
return 1;
}
/* Also narrower if the first needs a bind check and the second doesn't, if
* we wouldn't deem the other one narrower than this one int terms of
* slurpyness. Otherwise, they're tied. */
return !(b->max_arity != SLURPY_ARITY && a->max_arity == SLURPY_ARITY)
&& (a->bind_check && !(b->bind_check));
}
/*
=item C<static Rakudo_md_candidate_info** sort_candidates(PMC *candidates)>
Takes a ResizablePMCArray of the candidates, collects information about them
and then does a topological sort of them.
=cut
*/
static Rakudo_md_candidate_info** sort_candidates(PARROT_INTERP, PMC *candidates) {
INTVAL i;
const char *error = NULL;
/* Allocate results array (just allocate it for worst case, which
* is no ties ever, so a null between all of them, and then space
* for the terminating null. */
INTVAL num_candidates = VTABLE_elements(interp, candidates);
Rakudo_md_candidate_info ** const result = mem_allocate_n_zeroed_typed(
2 * num_candidates + 2, Rakudo_md_candidate_info*);
/* Create a node for each candidate in the graph. */
Rakudo_md_candidate_graph_node ** const graph = mem_allocate_n_zeroed_typed(
num_candidates + 1, Rakudo_md_candidate_graph_node*);
INTVAL insert_pos = 0;
for (i = 0; i < num_candidates; i++) {
PMC *param_pmc;
Rakudo_Signature *sig;
Rakudo_md_candidate_info *info;
INTVAL num_params;
INTVAL j;
INTVAL significant_param;
/* Get information about this candidate. */
PMC * const candidate = VTABLE_get_pmc_keyed_int(interp, candidates, i);
/* Create it an entry. */
info = mem_allocate_zeroed_typed(Rakudo_md_candidate_info);
info->sub = candidate;
/* Get hold of signature. */
info->signature = ((Rakudo_Code *)PMC_data(candidate))->signature;
sig = (Rakudo_Signature *)PMC_data(info->signature);
num_params = VTABLE_elements(interp, sig->params);
/* Type information. */
info->types = mem_allocate_n_zeroed_typed(num_params + 1, PMC*);
info->type_flags = mem_allocate_n_zeroed_typed(num_params + 1, INTVAL);
info->constraints = mem_allocate_n_zeroed_typed(num_params + 1, PMC*);
significant_param = 0;
for (j = 0; j < num_params; j++) {
PMC *param_pmc = VTABLE_get_pmc_keyed_int(interp, sig->params, j);
Rakudo_Parameter *param = (Rakudo_Parameter *)PMC_data(param_pmc);
/* If it's named (and not slurpy) don't need its type info but we
* will need a bindability check during the dispatch for it. */
if (!PMC_IS_NULL(param->named_names)) {
if (!(param->flags & SIG_ELEM_IS_OPTIONAL) &&
VTABLE_elements(interp, param->named_names) == 1)
info->req_named = VTABLE_get_string_keyed_int(interp, param->named_names, 0);
info->bind_check = 1;
continue;
}
/* If it's got a sub-signature, also need a bind check. */
if (!PMC_IS_NULL(param->sub_llsig))
info->bind_check = 1;
/* If it's named slurpy, we're done. */
if (param->flags & SIG_ELEM_SLURPY_NAMED)
break;
/* Otherwise, positional or slurpy and contributes to arity. */
if (param->flags & SIG_ELEM_SLURPY_POS || param->flags & SIG_ELEM_IS_CAPTURE) {
info->max_arity = SLURPY_ARITY;
break;
}
else if (param->flags & SIG_ELEM_IS_OPTIONAL) {
info->max_arity++;
}
else {
info->max_arity++;
info->min_arity++;
}
/* Record type info for this parameter. */
if (param->flags & SIG_ELEM_NOMINAL_GENERIC) {
info->bind_check = 1;
info->types[significant_param] = Rakudo_types_any_get();
}
else {
info->types[significant_param] = param->nominal_type;
}
info->constraints[significant_param] = param->post_constraints;
if (!PMC_IS_NULL(info->constraints[significant_param]))
info->bind_check = 1;
if (param->flags & SIG_ELEM_MULTI_INVOCANT)
info->num_types++;
if (param->flags & SIG_ELEM_DEFINED_ONLY)
info->type_flags[significant_param] = DEFCON_DEFINED;
else if (param->flags & SIG_ELEM_UNDEFINED_ONLY)
info->type_flags[significant_param] = DEFCON_UNDEFINED;
if (param->flags & SIG_ELEM_NATIVE_INT_VALUE)
info->type_flags[significant_param] += TYPE_NATIVE_INT;
else if (param->flags & SIG_ELEM_NATIVE_NUM_VALUE)
info->type_flags[significant_param] += TYPE_NATIVE_NUM;
else if (param->flags & SIG_ELEM_NATIVE_STR_VALUE)
info->type_flags[significant_param] += TYPE_NATIVE_STR;
significant_param++;
}
/* Add it to graph node, and initialize list of edges. */
graph[insert_pos] = mem_allocate_zeroed_typed(Rakudo_md_candidate_graph_node);
graph[insert_pos]->info = info;
graph[insert_pos]->edges = mem_allocate_n_zeroed_typed(
num_candidates, Rakudo_md_candidate_graph_node*);
insert_pos++;
}
/* If we found duplicate protos, don't go any further. */
if (!error) {
INTVAL candidates_to_sort;
INTVAL result_pos;
/* The actual number of candidates needs to discount any protos. */
num_candidates = insert_pos;
/* Now analyze type narrowness of the candidates relative to each other
* and create the edges. */
for (i = 0; i < num_candidates; i++) {
INTVAL j;
for (j = 0; j < num_candidates; j++) {
if (i == j)
continue;
if (is_narrower(interp, graph[i]->info, graph[j]->info)) {
graph[i]->edges[graph[i]->edges_out] = graph[j];
graph[i]->edges_out++;
graph[j]->edges_in++;
}
}
}
/* Perform the topological sort. */
candidates_to_sort = num_candidates;
result_pos = 0;
while (candidates_to_sort > 0) {
const INTVAL rem_start_point = result_pos;
/* Find any nodes that have no incoming edges and add them to
* results. */
for (i = 0; i < num_candidates; i++) {
if (graph[i]->edges_in == 0) {
/* Add to results. */
result[result_pos] = graph[i]->info;
graph[i]->info = NULL;
result_pos++;
candidates_to_sort--;
graph[i]->edges_in = EDGE_REMOVAL_TODO;
}
}
if (rem_start_point == result_pos) {
error = "Circularity detected in multi sub types.";
break;
}
/* Now we need to decrement edges in counts for things that had
* edges from candidates we added here. */
for (i = 0; i < num_candidates; i++) {
if (graph[i]->edges_in == EDGE_REMOVAL_TODO) {
INTVAL j;
for (j = 0; j < graph[i]->edges_out; j++)
graph[i]->edges[j]->edges_in--;
graph[i]->edges_in = EDGE_REMOVED;
}
}
/* This is end of a tied group, so leave a gap. */
result_pos++;
}
}
/* Free memory associated with the graph. */
for (i = 0; i < num_candidates; i++) {
Rakudo_md_candidate_info *info = graph[i]->info;
if (info) {
if (info->types)
mem_sys_free(info->types);
if (info->type_flags)
mem_sys_free(info->type_flags);
if (info->constraints)
mem_sys_free(info->constraints);
mem_sys_free(info);
}
mem_sys_free(graph[i]->edges);
mem_sys_free(graph[i]);
}
mem_sys_free(graph);
/* If we had an error, free memory for result array and throw exception. */
if (error) {
mem_sys_free(result);
Parrot_ex_throw_from_c_args(interp, 0, 1, error);
}
return result;
}
/*
=item C<static PMC * find_in_cache(PARROT_INTERP, Rakudo_md_arity_cache cache, PMC *capture, INTVAL num_args)>
Looks for an entry in the multi-dispatch cache.
=cut
*/
static PMC *
find_in_cache(PARROT_INTERP, Rakudo_md_cache *cache, PMC *capture, INTVAL num_args) {
INTVAL arg_tup[MD_CACHE_MAX_ARITY];
INTVAL i, j, entries, t_pos;
struct Pcc_cell * pc_positionals;
/* If it's zero-arity, return result right off. */
if (num_args == 0)
return cache->zero_arity;
/* Create arg tuple. */
if (capture->vtable->base_type == enum_class_CallContext)
GETATTR_CallContext_positionals(interp, capture, pc_positionals);
else
return NULL;
for (i = 0; i < num_args; i++) {
if (pc_positionals[i].type == BIND_VAL_OBJ) {
PMC *arg = pc_positionals[i].u.p;
if (arg->vtable->base_type == Rakudo_smo_id()) {
arg = Rakudo_cont_decontainerize(interp, arg);
arg_tup[i] = STABLE(arg)->type_cache_id | (IS_CONCRETE(arg) ? 1 : 0);
}
else {
return NULL;
}
}
else {
arg_tup[i] = (pc_positionals[i].type << 1) | 1;
}
}
/* Look through entries. */
entries = cache->arity_caches[num_args - 1].num_entries;
t_pos = 0;
for (i = 0; i < entries; i++) {
INTVAL match = 1;
for (j = 0; j < num_args; j++) {
if (cache->arity_caches[num_args - 1].type_ids[t_pos + j] != arg_tup[j]) {
match = 0;
break;
}
}
if (match)
return cache->arity_caches[num_args - 1].results[i];
t_pos += num_args;
}
return NULL;
}
/*
=item C<static void add_to_cache(PARROT_INTERP, Rakudo_md_cache *cache, PMC *capture, INTVAL num_args)>
Adds an entry to the multi-dispatch cache.
=cut
*/
static void
add_to_cache(PARROT_INTERP, Rakudo_md_cache *cache, PMC *capture, INTVAL num_args, PMC *result) {
INTVAL arg_tup[MD_CACHE_MAX_ARITY];
INTVAL i, entries, ins_type;
struct Pcc_cell * pc_positionals;
/* If it's zero arity, just stick it in that slot. */
if (num_args == 0) {
cache->zero_arity = result;
return;
}
/* If the cache is saturated, don't do anything (we could instead do a random
* replacement). */
entries = cache->arity_caches[num_args - 1].num_entries;
if (entries == MD_CACHE_MAX_ENTRIES)
return;
/* Create arg tuple. */
if (capture->vtable->base_type == enum_class_CallContext)
GETATTR_CallContext_positionals(interp, capture, pc_positionals);
else
return;
for (i = 0; i < num_args; i++) {
if (pc_positionals[i].type == BIND_VAL_OBJ) {
if (pc_positionals[i].u.p->vtable->base_type != Rakudo_smo_id()) {
return;
}
else {
PMC *arg = Rakudo_cont_decontainerize(interp, pc_positionals[i].u.p);
arg_tup[i] = STABLE(arg)->type_cache_id | (IS_CONCRETE(arg) ? 1 : 0);
}
}
else {
arg_tup[i] = (pc_positionals[i].type << 1) | 1;
}
}
/* If there's no entries yet, need to do some allocation. */
if (entries == 0) {
cache->arity_caches[num_args - 1].type_ids = (INTVAL *)mem_sys_allocate(num_args * sizeof(INTVAL) * MD_CACHE_MAX_ENTRIES);
cache->arity_caches[num_args - 1].results = (PMC **)mem_sys_allocate(sizeof(PMC *) * MD_CACHE_MAX_ENTRIES);
}
/* Add entry. */
ins_type = entries * num_args;
for (i = 0; i < num_args; i++)
cache->arity_caches[num_args - 1].type_ids[ins_type + i] = arg_tup[i];
cache->arity_caches[num_args - 1].results[entries] = result;
cache->arity_caches[num_args - 1].num_entries = entries + 1;
}
/*
=item C<static INTVAL has_junctional_args(PARROT_INTERP, INTVAL num_args, struct Pcc_cell * pc_positionals)>
Checks if any of the args are junctional.
=cut
*/
static INTVAL has_junctional_args(PARROT_INTERP, INTVAL num_args, struct Pcc_cell * pc_positionals) {
INTVAL i;
for (i = 0; i < num_args; i++) {
if (pc_positionals[i].type == BIND_VAL_OBJ) {
if (pc_positionals[i].u.p->vtable->base_type == Rakudo_smo_id()) {
PMC * const arg = Rakudo_cont_decontainerize(interp, pc_positionals[i].u.p);
if (STABLE(arg)->WHAT == Rakudo_types_junction_get())
return 1;
}
}
}
return 0;
}
/*
=item C<static STRING* dump_signature(PARROT_INTERP, STRING *so_far, PMC *sub)>
Utility for getting hold of the signature dump for a sub, which aids us in
producing awesomer errors.
=cut
*/
static STRING* dump_signature(PARROT_INTERP, STRING *so_far, PMC *sub) {
STRING * const sig_name = Parrot_str_new(interp, "signature", 0);
STRING * const perl_name = Parrot_str_new(interp, "perl", 0);
STRING * const newline = Parrot_str_new(interp, "\n", 0);
PMC * sig_meth, *sig_obj, *perl_meth, * sig_perl;
sig_meth = VTABLE_find_method(interp, sub, sig_name);
Parrot_ext_call(interp, sig_meth, "Pi->P", sub, &sig_obj);
perl_meth = VTABLE_find_method(interp, sig_obj, perl_name);
Parrot_ext_call(interp, perl_meth, "Pi->P", sig_obj, &sig_perl);
so_far = Parrot_str_concat(interp, so_far,
REPR(sig_perl)->box_funcs->get_str(interp, STABLE(sig_perl), OBJECT_BODY(sig_perl)));
so_far = Parrot_str_concat(interp, so_far, newline);
return so_far;
}
/*
=item C<static PMC* find_best_candidate(PARROT_INTERP, Rakudo_md_candidate_info **candidates,
INTVAL num_candidates, PMC *capture, opcode_t *next
PMC *dispatcher)>
Runs the Perl 6 MMD algorithm. Returns either the one winning unambiguous
candidate or throws an error saying that the dispatch failed if there were no
candidates or that it was ambiguous if there were tied candidates.
=cut
*/
static PMC* find_best_candidate(PARROT_INTERP, Rakudo_md_candidate_info **candidates,
INTVAL num_candidates, PMC *capture, opcode_t *next,
PMC *dispatcher, INTVAL many) {
Rakudo_md_candidate_info **cur_candidate = candidates;
Rakudo_md_candidate_info **possibles = mem_allocate_n_typed(num_candidates + 1, Rakudo_md_candidate_info *);
PMC *junctional_res = PMCNULL;
PMC *many_res = many ? Parrot_pmc_new(interp, enum_class_ResizablePMCArray) : PMCNULL;
const INTVAL num_args = VTABLE_elements(interp, capture);
INTVAL possibles_count = 0;
INTVAL pure_type_result = 1;
INTVAL type_check_count;
INTVAL type_mismatch;
/* We expect a Parrot capture in the multi-dispatcher, always. */
struct Pcc_cell * pc_positionals = NULL;
if (capture->vtable->base_type == enum_class_CallContext) {
GETATTR_CallContext_positionals(interp, capture, pc_positionals);
}
else {
mem_sys_free(possibles);
Parrot_ex_throw_from_c_args(interp, next, 1,
"INTERNAL ERROR: multi-dispatcher must be given a low level capture");
}
/* Iterate over the candidates and collect best ones; terminate
* when we see two nulls (may break out earlier). */
while (1) {
INTVAL i;
if (*cur_candidate == NULL) {
/* We've hit the end of a tied group now. If any of them have a
* bindability check requirement, we'll do any of those now. */
if (possibles_count) {
Rakudo_md_candidate_info **new_possibles = NULL;
INTVAL new_possibles_count = 0;
INTVAL i;
for (i = 0; i < possibles_count; i++) {
Parrot_pcc_set_signature(interp, CURRENT_CONTEXT(interp), NULL);
/* First, if there's a required named parameter and it was
* not passed, we can very quickly eliminate this candidate
* without doing a full bindability check. */
if (possibles[i]->req_named) {
if (!VTABLE_exists_keyed_str(interp, capture, possibles[i]->req_named)) {
/* Required named arg not passed, so we eliminate
* it right here. Flag that we've built a list of
* new possibles, and that this was not a pure
* type-based result that we can cache. */
if (!new_possibles)
new_possibles = mem_allocate_n_typed(num_candidates, Rakudo_md_candidate_info *);
pure_type_result = 0;
continue;
}
}
/* Otherwise, may need full bind check. */
if (possibles[i]->bind_check) {
/* We'll invoke the sub (but not re-enter the runloop)
* and then attempt to bind the signature. */
PMC *cthunk, *lexpad, *sig;
opcode_t *where;
INTVAL bind_check_result;
Rakudo_Code *code_obj = (Rakudo_Code *)PMC_data(possibles[i]->sub);
cthunk = Parrot_pmc_getprop(interp, code_obj->_do,
Parrot_str_new(interp, "COMPILER_THUNK", 0));
if (!PMC_IS_NULL(cthunk)) {
/* We need to do the tie-break on something not yet compiled.
* Get it compiled. */
Parrot_ext_call(interp, cthunk, "->");
}
Parrot_pcc_reuse_continuation(interp, CURRENT_CONTEXT(interp), next);
where = VTABLE_invoke(interp, possibles[i]->sub, next);
lexpad = Parrot_pcc_get_lex_pad(interp, CURRENT_CONTEXT(interp));
sig = possibles[i]->signature;
bind_check_result = Rakudo_binding_bind(interp, lexpad,
sig, capture, 0, NULL);
where = VTABLE_invoke(interp, Parrot_pcc_get_continuation(interp, CURRENT_CONTEXT(interp)), where);
/* If we haven't got a possibles storage space, allocate it now. */
if (!new_possibles)
new_possibles = mem_allocate_n_typed(num_candidates, Rakudo_md_candidate_info *);
/* Since we had to do a bindability check, this is not
* a result we can cache on nominal type. */
pure_type_result = 0;
/* If we don't fail, need to put this one onto the list
* (note that needing a junction dispatch is OK). */
if (bind_check_result != BIND_RESULT_FAIL) {
new_possibles[new_possibles_count] = possibles[i];
new_possibles_count++;
if (!many)
break;
}
}
/* Otherwise, it's just nominal; accept it. */
else {
if (!new_possibles)
new_possibles = mem_allocate_n_typed(num_candidates, Rakudo_md_candidate_info *);
new_possibles[new_possibles_count] = possibles[i];
new_possibles_count++;
}
}
/* If we have an updated list of possibles, free old one and use this
* new one from here on in. */
if (new_possibles) {
mem_sys_free(possibles);
possibles = new_possibles;
possibles_count = new_possibles_count;
}
}
/* Now we have eliminated any that fail the bindability check.
* See if we need to push it onto the many list and continue.
* Otherwise, we have the result we were looking for. */
if (many) {
for (i = 0; i < possibles_count; i++)
VTABLE_push_pmc(interp, many_res, possibles[i]->sub);
possibles_count = 0;
}
else if (possibles_count) {
break;
}
/* Keep looping and looking, unless we really hit the end. */
if (cur_candidate[1]) {
cur_candidate++;
continue;
}
else {
break;
}
}
/* Check if it's admissable by arity. */
if (num_args < (*cur_candidate)->min_arity
|| num_args > (*cur_candidate)->max_arity) {
cur_candidate++;
continue;
}
/* Check if it's admissable by type. */
type_check_count = (*cur_candidate)->num_types > num_args ?
num_args :
(*cur_candidate)->num_types;
type_mismatch = 0;
for (i = 0; i < type_check_count; i++) {
PMC * const type_obj = (*cur_candidate)->types[i];
INTVAL type_flags = (*cur_candidate)->type_flags[i];
INTVAL got_prim = pc_positionals[i].type;
if (type_flags & TYPE_NATIVE_MASK) {
/* Looking for a natively typed value. Did we get one? */
if (got_prim == BIND_VAL_OBJ) {
/* Object; won't do. */
type_mismatch = 1;
break;
}
if (((type_flags & TYPE_NATIVE_INT) && got_prim != BIND_VAL_INT) ||
((type_flags & TYPE_NATIVE_NUM) && got_prim != BIND_VAL_NUM) ||
((type_flags & TYPE_NATIVE_STR) && got_prim != BIND_VAL_STR)) {
/* Mismatch. */
type_mismatch = 1;
break;
}
}
else {
PMC *param;
if (got_prim == BIND_VAL_OBJ) {
param = pc_positionals[i].u.p;
if (param->vtable->base_type == Rakudo_smo_id()) {
param = Rakudo_cont_decontainerize(interp, param);
}
else {
param = Rakudo_types_parrot_map(interp, param);
if (param->vtable->base_type != Rakudo_smo_id()) {
type_mismatch = 1;
break;
}
}
}
else {
param = got_prim == BIND_VAL_INT ? Rakudo_types_int_get() :
got_prim == BIND_VAL_NUM ? Rakudo_types_num_get() :
Rakudo_types_str_get();
}
if (type_obj != Rakudo_types_mu_get() &&
!STABLE(param)->type_check(interp, param, type_obj)) {
type_mismatch = 1;
break;
}
else if ((*cur_candidate)->type_flags[i] & DEFCON_MASK) {
INTVAL defined = got_prim != BIND_VAL_OBJ || IS_CONCRETE(param);
INTVAL desired = (*cur_candidate)->type_flags[i] & DEFCON_MASK;
if ((defined && desired == DEFCON_UNDEFINED) ||
(!defined && desired == DEFCON_DEFINED)) {
type_mismatch = 1;
break;
}
}
}
}
if (type_mismatch) {
cur_candidate++;
continue;
}
/* If we get here, it's an admissable candidate; add to list. */
possibles[possibles_count] = *cur_candidate;
possibles_count++;
cur_candidate++;
}
/* If we were looking for many candidates, we're done now. */
if (many) {
mem_sys_free(possibles);
return many_res;
}
/* Check is default trait if we still have multiple options and we want one. */
if (possibles_count > 1) {
/* Locate any default candidates; if we find multiple defaults, this is
* no help, so we'll not bother collection just which ones are good. */
Rakudo_md_candidate_info *default_cand = NULL;
INTVAL i;
for (i = 0; i < possibles_count; i++) {
PMC * const default_meth = VTABLE_find_method(interp, possibles[i]->sub,
Parrot_str_new(interp, "default", 0));
if (!PMC_IS_NULL(default_meth)) {
PMC *result = PMCNULL;;
Parrot_ext_call(interp, default_meth, "Pi->P", possibles[i]->sub, &result);
if (VTABLE_get_bool(interp, result)) {
if (default_cand == NULL) {
default_cand = possibles[i];
}
else {
default_cand = NULL;
break;
}
}
}
}
if (default_cand) {
possibles[0] = default_cand;
possibles_count = 1;
}
}
/* If we're at a single candidate here, and we also know there's no
* type constraints that follow, we can cache the result. */
if (possibles_count == 1 && pure_type_result && num_args <= MD_CACHE_MAX_ARITY) {
Rakudo_Code *code_obj = (Rakudo_Code *)PMC_data(dispatcher);
Rakudo_md_cache *cache = (Rakudo_md_cache *)VTABLE_get_pointer(interp,
code_obj->dispatcher_cache);
add_to_cache(interp, cache, capture, num_args, possibles[0]->sub);
}
/* Perhaps we found nothing but have junctional arguments? */
if (possibles_count == 0 && has_junctional_args(interp, num_args, pc_positionals)) {
/* Unshift the proto onto the start of the args and hand back
* the threader. */
VTABLE_unshift_pmc(interp, capture, dispatcher);
junctional_res = Rakudo_types_junction_threader_get();
}
/* Need a unique candidate. */
if (possibles_count == 1) {
PMC *result = possibles[0]->sub;
mem_sys_free(possibles);
return result;
}
else if (!PMC_IS_NULL(junctional_res)) {
mem_sys_free(possibles);
return junctional_res;
}
else if (possibles_count == 0) {
/* Get signatures of all possible candidates. We dump them in the
* order in which we search for them. */
STRING *signatures = Parrot_str_new(interp, "", 0);
cur_candidate = candidates;
while (1) {
if (!cur_candidate[0] && !cur_candidate[1])
break;
if (cur_candidate[0])
signatures = dump_signature(interp, signatures, (*cur_candidate)->sub);
cur_candidate++;
}
mem_sys_free(possibles);
Parrot_ex_throw_from_c_args(interp, next, 1,
"Cannot call '%Ss'; none of these signatures match:\n%Ss",
(candidates[0] ? VTABLE_get_string(interp, candidates[0]->sub) : STRINGNULL),
signatures);
return PMCNULL;
}
else {
/* Get signatures of ambiguous candidates. */
STRING *signatures = Parrot_str_new(interp, "", 0);
INTVAL i;
for (i = 0; i < possibles_count; i++)
signatures = dump_signature(interp, signatures, possibles[i]->sub);
mem_sys_free(possibles);
Parrot_ex_throw_from_c_args(interp, next, 1,
"Ambiguous call to '%Ss'; these signatures all match:\n%Ss",
VTABLE_get_string(interp, candidates[0]->sub), signatures);
return PMCNULL;
}
}
/*
=item C<static Rakudo_md_candidate_info ** obtain_candidate_list(PARROT_INTERP,
INTVAL has_cache, Rakudo_Code *code_obj)>
Gets the sorted candiate list (either from cache, or by producing it).
=cut
*/
static Rakudo_md_candidate_info ** obtain_candidate_list(PARROT_INTERP,
INTVAL has_cache, PMC *dispatcher, Rakudo_Code *code_obj) {
if (has_cache) {
return ((Rakudo_md_cache *)VTABLE_get_pointer(interp,
code_obj->dispatcher_cache))->candidates;
}
else {
Rakudo_md_cache *cache = mem_allocate_zeroed_typed(Rakudo_md_cache);
cache->candidates = sort_candidates(interp, code_obj->dispatchees);
code_obj->dispatcher_cache = Parrot_pmc_new(interp, enum_class_Pointer);
VTABLE_set_pointer(interp, code_obj->dispatcher_cache, cache);
PARROT_GC_WRITE_BARRIER(interp, dispatcher);
return cache->candidates;
}
}
/*
=item C<PMC * Rakudo_md_dispatch(PARROT_INTERP, PMC *dispatcher, opcode_t *next)>
Gets the candidate list, does sorting if we didn't already do so, and
enters the multi dispatcher.
=cut
*/
PMC *
Rakudo_md_dispatch(PARROT_INTERP, PMC *dispatcher, PMC *capture, opcode_t *next) {
INTVAL num_cands;
Rakudo_md_candidate_info **cands;
/* Sane to look in the cache? */
Rakudo_Code *code_obj = (Rakudo_Code *)PMC_data(dispatcher);
INTVAL num_args = VTABLE_elements(interp, capture);
INTVAL has_cache = !PMC_IS_NULL(code_obj->dispatcher_cache);
if (num_args <= MD_CACHE_MAX_ARITY && has_cache) {
Rakudo_md_cache *cache = (Rakudo_md_cache *)VTABLE_get_pointer(interp,
code_obj->dispatcher_cache);
if (num_args == 0 || cache->arity_caches[num_args - 1].num_entries) {
PMC *cache_result = find_in_cache(interp, cache, capture, num_args);
if (cache_result)
return cache_result;
}
}
/* No cache hit, so we need to do a full dispatch. */
num_cands = VTABLE_elements(interp, code_obj->dispatchees);
cands = obtain_candidate_list(interp, has_cache, dispatcher, code_obj);
return find_best_candidate(interp, cands, num_cands, capture, next, dispatcher, 0);
}
/*
=item C<PMC * Rakudo_md_get_all_matches(PARROT_INTERP, PMC *dispatcher, opcode_t *next)>
Gets the candidate list, does sorting if we didn't already do so, and
enters the multi dispatcher.
=cut
*/
PMC *
Rakudo_md_get_all_matches(PARROT_INTERP, PMC *dispatcher, PMC *capture) {
Rakudo_Code *code_obj = (Rakudo_Code *)PMC_data(dispatcher);
INTVAL num_cands = VTABLE_elements(interp, code_obj->dispatchees);
INTVAL has_cache = !PMC_IS_NULL(code_obj->dispatcher_cache);
Rakudo_md_candidate_info **cands = obtain_candidate_list(interp, has_cache,
dispatcher, code_obj);
return find_best_candidate(interp, cands, num_cands, capture, NULL, dispatcher, 1);
}
/*
=item C<PMC * Rakudo_md_ct_dispatch(PARROT_INTERP, PMC *dispatcher, PMC *capture, PMC **result)>
Tries to resolve a multi-dispatch at compile time. Returns a flag
and, if a dispatch is possible, sets the result.
=cut
*/
INTVAL
Rakudo_md_ct_dispatch(PARROT_INTERP, PMC *dispatcher, PMC *capture, PMC **result) {
/* Get hold of the candidates. */
Rakudo_Code *code_obj = (Rakudo_Code *)PMC_data(dispatcher);
INTVAL has_cache = !PMC_IS_NULL(code_obj->dispatcher_cache);
Rakudo_md_candidate_info **cands = obtain_candidate_list(interp, has_cache,
dispatcher, code_obj);
/* Current dispatch state. */
Rakudo_md_candidate_info **cur_candidate = cands;
INTVAL type_mismatch, type_check_count, type_match_possible;
INTVAL all_native = 1;
INTVAL seen_all = 0;
INTVAL arity_possible = 0;
INTVAL type_possible = 0;
PMC *cur_result = PMCNULL;
/* Grab positionals. */
struct Pcc_cell * pc_positionals;
INTVAL num_args = VTABLE_elements(interp, capture);
if (capture->vtable->base_type == enum_class_CallContext)
GETATTR_CallContext_positionals(interp, capture, pc_positionals);
else
return MD_CT_NOT_SURE;
/* Look through the candidates. If we see anything that needs a bind
* check or a definedness check, we can't decide it at compile time,
* so bail out immediately. */
while (1) {
INTVAL used_defcon = 0;
INTVAL i;
/* Did we reach the end of a tied group? If so, note we can only
* consider the narrowest group, *unless* they are all natively
* typed candidates in which case we can look a bit further.
* We also exit if we found something. */
if (*cur_candidate == NULL) {
if (cur_candidate[1] && all_native && PMC_IS_NULL(cur_result)) {
cur_candidate++;
continue;
}
else {
seen_all = cur_candidate[1] == NULL;
break;
}
}
/* Check if it's admissable by arity. */
if (num_args < (*cur_candidate)->min_arity
|| num_args > (*cur_candidate)->max_arity) {
cur_candidate++;
continue;
}
/* If we got this far, something at least matched on arity. */
arity_possible = 1;
/* Check if it's admissable by type. */
type_check_count = (*cur_candidate)->num_types > num_args ?
num_args :
(*cur_candidate)->num_types;
type_mismatch = 0;
type_match_possible = 1;
for (i = 0; i < type_check_count; i++) {
PMC * const type_obj = (*cur_candidate)->types[i];
INTVAL type_flags = (*cur_candidate)->type_flags[i];
INTVAL got_prim = pc_positionals[i].type;
if (type_flags & TYPE_NATIVE_MASK) {
/* Looking for a natively typed value. Did we get one? */
if (got_prim == BIND_VAL_OBJ) {
/* Object; won't do. */
type_mismatch = 1;
break;
}
if (((type_flags & TYPE_NATIVE_INT) && got_prim != BIND_VAL_INT) ||
((type_flags & TYPE_NATIVE_NUM) && got_prim != BIND_VAL_NUM) ||
((type_flags & TYPE_NATIVE_STR) && got_prim != BIND_VAL_STR)) {
/* Mismatch. */
type_mismatch = 1;
type_match_possible = 0;
break;
}
}
else {
/* Work out parameter. */
PMC * const param =
got_prim == BIND_VAL_OBJ ? pc_positionals[i].u.p :
got_prim == BIND_VAL_INT ? Rakudo_types_int_get() :
got_prim == BIND_VAL_NUM ? Rakudo_types_num_get() :
Rakudo_types_str_get();
/* If we're here, it's a non-native. */
all_native = 0;
/* Check type. If that doesn't rule it out, then check if it's
* got definedness constraints. If it does, note that; if we
* match but depend on definedness constraints we can't do
* any more. */
if (type_obj != Rakudo_types_mu_get() &&
!STABLE(param)->type_check(interp, param, type_obj)) {
type_mismatch = 1;
/* We didn't match, but that doesn't mean we cannot at
* runtime (e.g. the most we know about the type could
* be that it's Any, but at runtime that feasibly could
* be Int). In some cases we never could though (Str
* passed to an Int parameter). */
if (!STABLE(type_obj)->type_check(interp, type_obj, param))
type_match_possible = 0;
}
else if ((*cur_candidate)->type_flags[i] & DEFCON_MASK) {
used_defcon = 1;
}
}
}
if (type_match_possible)
type_possible = 1;
if (type_mismatch) {
cur_candidate++;
continue;
}
if (used_defcon)
return MD_CT_NOT_SURE;
/* If it's possible but needs a bind check, we're not going to be
* able to decide it. */
if ((*cur_candidate)->bind_check)
return MD_CT_NOT_SURE;
/* If we get here, it's the result. Well, unless we already had one,
* in which case we're in bother 'cus we don't know how to disambiguate
* at compile time. */
if (PMC_IS_NULL(cur_result)) {
cur_result = (*cur_candidate)->sub;
cur_candidate++;
}
else {
return MD_CT_NOT_SURE;
}
}
/* If we saw all the candidates, and got no result, and the arity never
* matched or when it did there was no way any candidates could get
* passed matching types, then we know it would never work. */
if (seen_all && (!arity_possible || !type_possible) && PMC_IS_NULL(cur_result)) {
/* Ensure no junctional args before we flag the failure. */
return has_junctional_args(interp, num_args, pc_positionals) ?
MD_CT_NOT_SURE :
MD_CT_NO_WAY;
}
/* If we got a result, return it. */
if (!PMC_IS_NULL(cur_result)) {
*result = cur_result;
return MD_CT_DECIDED;
}
/* Otherwise, dunno...we'll have to find out at runtime. */
return MD_CT_NOT_SURE;
}
/*
=back
=cut
*/
/*
* Local variables:
* c-file-style: "parrot"
* End:
* vim: expandtab shiftwidth=4:
*/
|
687778.c | /*-------------------------------------------------------------------------
*
* createplan.c
* Routines to create the desired plan for processing a query.
* Planning is complete, we just need to convert the selected
* Path into a Plan.
*
* Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/optimizer/plan/createplan.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/stratnum.h"
#include "access/sysattr.h"
#include "catalog/pg_class.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/extensible.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/predtest.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
/*
* Flag bits that can appear in the flags argument of create_plan_recurse().
* These can be OR-ed together.
*
* CP_EXACT_TLIST specifies that the generated plan node must return exactly
* the tlist specified by the path's pathtarget (this overrides both
* CP_SMALL_TLIST and CP_LABEL_TLIST, if those are set). Otherwise, the
* plan node is allowed to return just the Vars and PlaceHolderVars needed
* to evaluate the pathtarget.
*
* CP_SMALL_TLIST specifies that a narrower tlist is preferred. This is
* passed down by parent nodes such as Sort and Hash, which will have to
* store the returned tuples.
*
* CP_LABEL_TLIST specifies that the plan node must return columns matching
* any sortgrouprefs specified in its pathtarget, with appropriate
* ressortgroupref labels. This is passed down by parent nodes such as Sort
* and Group, which need these values to be available in their inputs.
*/
#define CP_EXACT_TLIST 0x0001 /* Plan must return specified tlist */
#define CP_SMALL_TLIST 0x0002 /* Prefer narrower tlists */
#define CP_LABEL_TLIST 0x0004 /* tlist must contain sortgrouprefs */
static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
int flags);
static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
int flags);
static List *build_path_tlist(PlannerInfo *root, Path *path);
static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
static List *get_gating_quals(PlannerInfo *root, List *quals);
static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
List *gating_quals);
static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
static ProjectSet *create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path);
static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
int flags);
static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path,
int flags);
static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
static Plan *create_projection_plan(PlannerInfo *root, ProjectionPath *best_path);
static Plan *inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe);
static Sort *create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags);
static Group *create_group_plan(PlannerInfo *root, GroupPath *best_path);
static Unique *create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path,
int flags);
static Agg *create_agg_plan(PlannerInfo *root, AggPath *best_path);
static Plan *create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path);
static Result *create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path);
static WindowAgg *create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path);
static SetOp *create_setop_plan(PlannerInfo *root, SetOpPath *best_path,
int flags);
static RecursiveUnion *create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path);
static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
List *tlist,
int numSortCols, AttrNumber *sortColIdx,
int *partNumCols,
AttrNumber **partColIdx,
Oid **partOperators,
int *ordNumCols,
AttrNumber **ordColIdx,
Oid **ordOperators);
static LockRows *create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
int flags);
static ModifyTable *create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path);
static Limit *create_limit_plan(PlannerInfo *root, LimitPath *best_path,
int flags);
static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
List *tlist, List *scan_clauses, bool indexonly);
static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
BitmapHeapPath *best_path,
List *tlist, List *scan_clauses);
static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
List **qual, List **indexqual, List **indexECs);
static void bitmap_subplan_mark_shared(Plan *plan);
static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
List *tlist, List *scan_clauses);
static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root,
SubqueryScanPath *best_path,
List *tlist, List *scan_clauses);
static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static TableFuncScan *create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static NamedTuplestoreScan *create_namedtuplestorescan_plan(PlannerInfo *root,
Path *best_path, List *tlist, List *scan_clauses);
static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses);
static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
List *tlist, List *scan_clauses);
static CustomScan *create_customscan_plan(PlannerInfo *root,
CustomPath *best_path,
List *tlist, List *scan_clauses);
static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path);
static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path);
static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
static void process_subquery_nestloop_params(PlannerInfo *root,
List *subplan_params);
static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
static List *get_switched_clauses(List *clauses, Relids outerrelids);
static List *order_qual_clauses(PlannerInfo *root, List *clauses);
static void copy_generic_path_info(Plan *dest, Path *src);
static void copy_plan_costsize(Plan *dest, Plan *src);
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
double limit_tuples);
static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
TableSampleClause *tsc);
static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
Oid indexid, List *indexqual, List *indexqualorig,
List *indexorderby, List *indexorderbyorig,
List *indexorderbyops,
ScanDirection indexscandir);
static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
Index scanrelid, Oid indexid,
List *indexqual, List *indexorderby,
List *indextlist,
ScanDirection indexscandir);
static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
List *indexqual,
List *indexqualorig);
static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
List *qpqual,
Plan *lefttree,
List *bitmapqualorig,
Index scanrelid);
static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
List *tidquals);
static SubqueryScan *make_subqueryscan(List *qptlist,
List *qpqual,
Index scanrelid,
Plan *subplan);
static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
Index scanrelid, List *functions, bool funcordinality);
static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
Index scanrelid, List *values_lists);
static TableFuncScan *make_tablefuncscan(List *qptlist, List *qpqual,
Index scanrelid, TableFunc *tablefunc);
static CteScan *make_ctescan(List *qptlist, List *qpqual,
Index scanrelid, int ctePlanId, int cteParam);
static NamedTuplestoreScan *make_namedtuplestorescan(List *qptlist, List *qpqual,
Index scanrelid, char *enrname);
static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
Index scanrelid, int wtParam);
static Append *make_append(List *appendplans, List *tlist, List *partitioned_rels);
static RecursiveUnion *make_recursive_union(List *tlist,
Plan *lefttree,
Plan *righttree,
int wtParam,
List *distinctList,
long numGroups);
static BitmapAnd *make_bitmap_and(List *bitmapplans);
static BitmapOr *make_bitmap_or(List *bitmapplans);
static NestLoop *make_nestloop(List *tlist,
List *joinclauses, List *otherclauses, List *nestParams,
Plan *lefttree, Plan *righttree,
JoinType jointype, bool inner_unique);
static HashJoin *make_hashjoin(List *tlist,
List *joinclauses, List *otherclauses,
List *hashclauses,
Plan *lefttree, Plan *righttree,
JoinType jointype, bool inner_unique);
static Hash *make_hash(Plan *lefttree,
Oid skewTable,
AttrNumber skewColumn,
bool skewInherit);
static MergeJoin *make_mergejoin(List *tlist,
List *joinclauses, List *otherclauses,
List *mergeclauses,
Oid *mergefamilies,
Oid *mergecollations,
int *mergestrategies,
bool *mergenullsfirst,
Plan *lefttree, Plan *righttree,
JoinType jointype, bool inner_unique,
bool skip_mark_restore);
static Sort *make_sort(Plan *lefttree, int numCols,
AttrNumber *sortColIdx, Oid *sortOperators,
Oid *collations, bool *nullsFirst);
static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
Relids relids,
const AttrNumber *reqColIdx,
bool adjust_tlist_in_place,
int *p_numsortkeys,
AttrNumber **p_sortColIdx,
Oid **p_sortOperators,
Oid **p_collations,
bool **p_nullsFirst);
static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
TargetEntry *tle,
Relids relids);
static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys);
static Sort *make_sort_from_groupcols(List *groupcls,
AttrNumber *grpColIdx,
Plan *lefttree);
static Material *make_material(Plan *lefttree);
static WindowAgg *make_windowagg(List *tlist, Index winref,
int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
int frameOptions, Node *startOffset, Node *endOffset,
Plan *lefttree);
static Group *make_group(List *tlist, List *qual, int numGroupCols,
AttrNumber *grpColIdx, Oid *grpOperators,
Plan *lefttree);
static Unique *make_unique_from_sortclauses(Plan *lefttree, List *distinctList);
static Unique *make_unique_from_pathkeys(Plan *lefttree,
List *pathkeys, int numCols);
static Gather *make_gather(List *qptlist, List *qpqual,
int nworkers, bool single_copy, Plan *subplan);
static SetOp *make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
List *distinctList, AttrNumber flagColIdx, int firstFlag,
long numGroups);
static LockRows *make_lockrows(Plan *lefttree, List *rowMarks, int epqParam);
static Result *make_result(List *tlist, Node *resconstantqual, Plan *subplan);
static ProjectSet *make_project_set(List *tlist, Plan *subplan);
static ModifyTable *make_modifytable(PlannerInfo *root,
CmdType operation, bool canSetTag,
Index nominalRelation, List *partitioned_rels,
List *resultRelations, List *subplans,
List *withCheckOptionLists, List *returningLists,
List *rowMarks, OnConflictExpr *onconflict, int epqParam);
static GatherMerge *create_gather_merge_plan(PlannerInfo *root,
GatherMergePath *best_path);
/*
* create_plan
* Creates the access plan for a query by recursively processing the
* desired tree of pathnodes, starting at the node 'best_path'. For
* every pathnode found, we create a corresponding plan node containing
* appropriate id, target list, and qualification information.
*
* The tlists and quals in the plan tree are still in planner format,
* ie, Vars still correspond to the parser's numbering. This will be
* fixed later by setrefs.c.
*
* best_path is the best access path
*
* Returns a Plan tree.
*/
Plan *
create_plan(PlannerInfo *root, Path *best_path)
{
Plan *plan;
/* plan_params should not be in use in current query level */
Assert(root->plan_params == NIL);
/* Initialize this module's private workspace in PlannerInfo */
root->curOuterRels = NULL;
root->curOuterParams = NIL;
/* Recursively process the path tree, demanding the correct tlist result */
plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
/*
* Make sure the topmost plan node's targetlist exposes the original
* column names and other decorative info. Targetlists generated within
* the planner don't bother with that stuff, but we must have it on the
* top-level tlist seen at execution time. However, ModifyTable plan
* nodes don't have a tlist matching the querytree targetlist.
*/
if (!IsA(plan, ModifyTable))
apply_tlist_labeling(plan->targetlist, root->processed_tlist);
/*
* Attach any initPlans created in this query level to the topmost plan
* node. (In principle the initplans could go in any plan node at or
* above where they're referenced, but there seems no reason to put them
* any lower than the topmost node for the query level. Also, see
* comments for SS_finalize_plan before you try to change this.)
*/
SS_attach_initplans(root, plan);
/* Check we successfully assigned all NestLoopParams to plan nodes */
if (root->curOuterParams != NIL)
elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
/*
* Reset plan_params to ensure param IDs used for nestloop params are not
* re-used later
*/
root->plan_params = NIL;
return plan;
}
/*
* create_plan_recurse
* Recursive guts of create_plan().
*/
static Plan *
create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
{
Plan *plan;
switch (best_path->pathtype)
{
case T_SeqScan:
case T_SampleScan:
case T_IndexScan:
case T_IndexOnlyScan:
case T_BitmapHeapScan:
case T_TidScan:
case T_SubqueryScan:
case T_FunctionScan:
case T_TableFuncScan:
case T_ValuesScan:
case T_CteScan:
case T_WorkTableScan:
case T_NamedTuplestoreScan:
case T_ForeignScan:
case T_CustomScan:
plan = create_scan_plan(root, best_path, flags);
break;
case T_HashJoin:
case T_MergeJoin:
case T_NestLoop:
plan = create_join_plan(root,
(JoinPath *) best_path);
break;
case T_Append:
plan = create_append_plan(root,
(AppendPath *) best_path);
break;
case T_MergeAppend:
plan = create_merge_append_plan(root,
(MergeAppendPath *) best_path);
break;
case T_Result:
if (IsA(best_path, ProjectionPath))
{
plan = create_projection_plan(root,
(ProjectionPath *) best_path);
}
else if (IsA(best_path, MinMaxAggPath))
{
plan = (Plan *) create_minmaxagg_plan(root,
(MinMaxAggPath *) best_path);
}
else
{
Assert(IsA(best_path, ResultPath));
plan = (Plan *) create_result_plan(root,
(ResultPath *) best_path);
}
break;
case T_ProjectSet:
plan = (Plan *) create_project_set_plan(root,
(ProjectSetPath *) best_path);
break;
case T_Material:
plan = (Plan *) create_material_plan(root,
(MaterialPath *) best_path,
flags);
break;
case T_Unique:
if (IsA(best_path, UpperUniquePath))
{
plan = (Plan *) create_upper_unique_plan(root,
(UpperUniquePath *) best_path,
flags);
}
else
{
Assert(IsA(best_path, UniquePath));
plan = create_unique_plan(root,
(UniquePath *) best_path,
flags);
}
break;
case T_Gather:
plan = (Plan *) create_gather_plan(root,
(GatherPath *) best_path);
break;
case T_Sort:
plan = (Plan *) create_sort_plan(root,
(SortPath *) best_path,
flags);
break;
case T_Group:
plan = (Plan *) create_group_plan(root,
(GroupPath *) best_path);
break;
case T_Agg:
if (IsA(best_path, GroupingSetsPath))
plan = create_groupingsets_plan(root,
(GroupingSetsPath *) best_path);
else
{
Assert(IsA(best_path, AggPath));
plan = (Plan *) create_agg_plan(root,
(AggPath *) best_path);
}
break;
case T_WindowAgg:
plan = (Plan *) create_windowagg_plan(root,
(WindowAggPath *) best_path);
break;
case T_SetOp:
plan = (Plan *) create_setop_plan(root,
(SetOpPath *) best_path,
flags);
break;
case T_RecursiveUnion:
plan = (Plan *) create_recursiveunion_plan(root,
(RecursiveUnionPath *) best_path);
break;
case T_LockRows:
plan = (Plan *) create_lockrows_plan(root,
(LockRowsPath *) best_path,
flags);
break;
case T_ModifyTable:
plan = (Plan *) create_modifytable_plan(root,
(ModifyTablePath *) best_path);
break;
case T_Limit:
plan = (Plan *) create_limit_plan(root,
(LimitPath *) best_path,
flags);
break;
case T_GatherMerge:
plan = (Plan *) create_gather_merge_plan(root,
(GatherMergePath *) best_path);
break;
default:
elog(ERROR, "unrecognized node type: %d",
(int) best_path->pathtype);
plan = NULL; /* keep compiler quiet */
break;
}
return plan;
}
/*
* create_scan_plan
* Create a scan plan for the parent relation of 'best_path'.
*/
static Plan *
create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
{
RelOptInfo *rel = best_path->parent;
List *scan_clauses;
List *gating_clauses;
List *tlist;
Plan *plan;
/*
* Extract the relevant restriction clauses from the parent relation. The
* executor must apply all these restrictions during the scan, except for
* pseudoconstants which we'll take care of below.
*
* If this is a plain indexscan or index-only scan, we need not consider
* restriction clauses that are implied by the index's predicate, so use
* indrestrictinfo not baserestrictinfo. Note that we can't do that for
* bitmap indexscans, since there's not necessarily a single index
* involved; but it doesn't matter since create_bitmap_scan_plan() will be
* able to get rid of such clauses anyway via predicate proof.
*/
switch (best_path->pathtype)
{
case T_IndexScan:
case T_IndexOnlyScan:
scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
break;
default:
scan_clauses = rel->baserestrictinfo;
break;
}
/*
* If this is a parameterized scan, we also need to enforce all the join
* clauses available from the outer relation(s).
*
* For paranoia's sake, don't modify the stored baserestrictinfo list.
*/
if (best_path->param_info)
scan_clauses = list_concat(list_copy(scan_clauses),
best_path->param_info->ppi_clauses);
/*
* Detect whether we have any pseudoconstant quals to deal with. Then, if
* we'll need a gating Result node, it will be able to project, so there
* are no requirements on the child's tlist.
*/
gating_clauses = get_gating_quals(root, scan_clauses);
if (gating_clauses)
flags = 0;
/*
* For table scans, rather than using the relation targetlist (which is
* only those Vars actually needed by the query), we prefer to generate a
* tlist containing all Vars in order. This will allow the executor to
* optimize away projection of the table tuples, if possible.
*/
if (use_physical_tlist(root, best_path, flags))
{
if (best_path->pathtype == T_IndexOnlyScan)
{
/* For index-only scan, the preferred tlist is the index's */
tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
/*
* Transfer any sortgroupref data to the replacement tlist, unless
* we don't care because the gating Result will handle it.
*/
if (!gating_clauses)
apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
}
else
{
tlist = build_physical_tlist(root, rel);
if (tlist == NIL)
{
/* Failed because of dropped cols, so use regular method */
tlist = build_path_tlist(root, best_path);
}
else
{
/* As above, transfer sortgroupref data to replacement tlist */
if (!gating_clauses)
apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
}
}
}
else
{
tlist = build_path_tlist(root, best_path);
}
switch (best_path->pathtype)
{
case T_SeqScan:
plan = (Plan *) create_seqscan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_SampleScan:
plan = (Plan *) create_samplescan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_IndexScan:
plan = (Plan *) create_indexscan_plan(root,
(IndexPath *) best_path,
tlist,
scan_clauses,
false);
break;
case T_IndexOnlyScan:
plan = (Plan *) create_indexscan_plan(root,
(IndexPath *) best_path,
tlist,
scan_clauses,
true);
break;
case T_BitmapHeapScan:
plan = (Plan *) create_bitmap_scan_plan(root,
(BitmapHeapPath *) best_path,
tlist,
scan_clauses);
break;
case T_TidScan:
plan = (Plan *) create_tidscan_plan(root,
(TidPath *) best_path,
tlist,
scan_clauses);
break;
case T_SubqueryScan:
plan = (Plan *) create_subqueryscan_plan(root,
(SubqueryScanPath *) best_path,
tlist,
scan_clauses);
break;
case T_FunctionScan:
plan = (Plan *) create_functionscan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_TableFuncScan:
plan = (Plan *) create_tablefuncscan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_ValuesScan:
plan = (Plan *) create_valuesscan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_CteScan:
plan = (Plan *) create_ctescan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_NamedTuplestoreScan:
plan = (Plan *) create_namedtuplestorescan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_WorkTableScan:
plan = (Plan *) create_worktablescan_plan(root,
best_path,
tlist,
scan_clauses);
break;
case T_ForeignScan:
plan = (Plan *) create_foreignscan_plan(root,
(ForeignPath *) best_path,
tlist,
scan_clauses);
break;
case T_CustomScan:
plan = (Plan *) create_customscan_plan(root,
(CustomPath *) best_path,
tlist,
scan_clauses);
break;
default:
elog(ERROR, "unrecognized node type: %d",
(int) best_path->pathtype);
plan = NULL; /* keep compiler quiet */
break;
}
/*
* If there are any pseudoconstant clauses attached to this node, insert a
* gating Result node that evaluates the pseudoconstants as one-time
* quals.
*/
if (gating_clauses)
plan = create_gating_plan(root, best_path, plan, gating_clauses);
return plan;
}
/*
* Build a target list (ie, a list of TargetEntry) for the Path's output.
*
* This is almost just make_tlist_from_pathtarget(), but we also have to
* deal with replacing nestloop params.
*/
static List *
build_path_tlist(PlannerInfo *root, Path *path)
{
List *tlist = NIL;
Index *sortgrouprefs = path->pathtarget->sortgrouprefs;
int resno = 1;
ListCell *v;
foreach(v, path->pathtarget->exprs)
{
Node *node = (Node *) lfirst(v);
TargetEntry *tle;
/*
* If it's a parameterized path, there might be lateral references in
* the tlist, which need to be replaced with Params. There's no need
* to remake the TargetEntry nodes, so apply this to each list item
* separately.
*/
if (path->param_info)
node = replace_nestloop_params(root, node);
tle = makeTargetEntry((Expr *) node,
resno,
NULL,
false);
if (sortgrouprefs)
tle->ressortgroupref = sortgrouprefs[resno - 1];
tlist = lappend(tlist, tle);
resno++;
}
return tlist;
}
/*
* use_physical_tlist
* Decide whether to use a tlist matching relation structure,
* rather than only those Vars actually referenced.
*/
static bool
use_physical_tlist(PlannerInfo *root, Path *path, int flags)
{
RelOptInfo *rel = path->parent;
int i;
ListCell *lc;
/*
* Forget it if either exact tlist or small tlist is demanded.
*/
if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
return false;
/*
* We can do this for real relation scans, subquery scans, function scans,
* tablefunc scans, values scans, and CTE scans (but not for, eg, joins).
*/
if (rel->rtekind != RTE_RELATION &&
rel->rtekind != RTE_SUBQUERY &&
rel->rtekind != RTE_FUNCTION &&
rel->rtekind != RTE_TABLEFUNC &&
rel->rtekind != RTE_VALUES &&
rel->rtekind != RTE_CTE)
return false;
/*
* Can't do it with inheritance cases either (mainly because Append
* doesn't project; this test may be unnecessary now that
* create_append_plan instructs its children to return an exact tlist).
*/
if (rel->reloptkind != RELOPT_BASEREL)
return false;
/*
* Also, don't do it to a CustomPath; the premise that we're extracting
* columns from a simple physical tuple is unlikely to hold for those.
* (When it does make sense, the custom path creator can set up the path's
* pathtarget that way.)
*/
if (IsA(path, CustomPath))
return false;
/*
* Can't do it if any system columns or whole-row Vars are requested.
* (This could possibly be fixed but would take some fragile assumptions
* in setrefs.c, I think.)
*/
for (i = rel->min_attr; i <= 0; i++)
{
if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
return false;
}
/*
* Can't do it if the rel is required to emit any placeholder expressions,
* either.
*/
foreach(lc, root->placeholder_list)
{
PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
bms_is_subset(phinfo->ph_eval_at, rel->relids))
return false;
}
/*
* Also, can't do it if CP_LABEL_TLIST is specified and path is requested
* to emit any sort/group columns that are not simple Vars. (If they are
* simple Vars, they should appear in the physical tlist, and
* apply_pathtarget_labeling_to_tlist will take care of getting them
* labeled again.) We also have to check that no two sort/group columns
* are the same Var, else that element of the physical tlist would need
* conflicting ressortgroupref labels.
*/
if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
{
Bitmapset *sortgroupatts = NULL;
i = 0;
foreach(lc, path->pathtarget->exprs)
{
Expr *expr = (Expr *) lfirst(lc);
if (path->pathtarget->sortgrouprefs[i])
{
if (expr && IsA(expr, Var))
{
int attno = ((Var *) expr)->varattno;
attno -= FirstLowInvalidHeapAttributeNumber;
if (bms_is_member(attno, sortgroupatts))
return false;
sortgroupatts = bms_add_member(sortgroupatts, attno);
}
else
return false;
}
i++;
}
}
return true;
}
/*
* get_gating_quals
* See if there are pseudoconstant quals in a node's quals list
*
* If the node's quals list includes any pseudoconstant quals,
* return just those quals.
*/
static List *
get_gating_quals(PlannerInfo *root, List *quals)
{
/* No need to look if we know there are no pseudoconstants */
if (!root->hasPseudoConstantQuals)
return NIL;
/* Sort into desirable execution order while still in RestrictInfo form */
quals = order_qual_clauses(root, quals);
/* Pull out any pseudoconstant quals from the RestrictInfo list */
return extract_actual_clauses(quals, true);
}
/*
* create_gating_plan
* Deal with pseudoconstant qual clauses
*
* Add a gating Result node atop the already-built plan.
*/
static Plan *
create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
List *gating_quals)
{
Plan *gplan;
Assert(gating_quals);
/*
* Since we need a Result node anyway, always return the path's requested
* tlist; that's never a wrong choice, even if the parent node didn't ask
* for CP_EXACT_TLIST.
*/
gplan = (Plan *) make_result(build_path_tlist(root, path),
(Node *) gating_quals,
plan);
/*
* Notice that we don't change cost or size estimates when doing gating.
* The costs of qual eval were already included in the subplan's cost.
* Leaving the size alone amounts to assuming that the gating qual will
* succeed, which is the conservative estimate for planning upper queries.
* We certainly don't want to assume the output size is zero (unless the
* gating qual is actually constant FALSE, and that case is dealt with in
* clausesel.c). Interpolating between the two cases is silly, because it
* doesn't reflect what will really happen at runtime, and besides which
* in most cases we have only a very bad idea of the probability of the
* gating qual being true.
*/
copy_plan_costsize(gplan, plan);
/* Gating quals could be unsafe, so better use the Path's safety flag */
gplan->parallel_safe = path->parallel_safe;
return gplan;
}
/*
* create_join_plan
* Create a join plan for 'best_path' and (recursively) plans for its
* inner and outer paths.
*/
static Plan *
create_join_plan(PlannerInfo *root, JoinPath *best_path)
{
Plan *plan;
List *gating_clauses;
switch (best_path->path.pathtype)
{
case T_MergeJoin:
plan = (Plan *) create_mergejoin_plan(root,
(MergePath *) best_path);
break;
case T_HashJoin:
plan = (Plan *) create_hashjoin_plan(root,
(HashPath *) best_path);
break;
case T_NestLoop:
plan = (Plan *) create_nestloop_plan(root,
(NestPath *) best_path);
break;
default:
elog(ERROR, "unrecognized node type: %d",
(int) best_path->path.pathtype);
plan = NULL; /* keep compiler quiet */
break;
}
/*
* If there are any pseudoconstant clauses attached to this node, insert a
* gating Result node that evaluates the pseudoconstants as one-time
* quals.
*/
gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
if (gating_clauses)
plan = create_gating_plan(root, (Path *) best_path, plan,
gating_clauses);
#ifdef NOT_USED
/*
* * Expensive function pullups may have pulled local predicates * into
* this path node. Put them in the qpqual of the plan node. * JMH,
* 6/15/92
*/
if (get_loc_restrictinfo(best_path) != NIL)
set_qpqual((Plan) plan,
list_concat(get_qpqual((Plan) plan),
get_actual_clauses(get_loc_restrictinfo(best_path))));
#endif
return plan;
}
/*
* create_append_plan
* Create an Append plan for 'best_path' and (recursively) plans
* for its subpaths.
*
* Returns a Plan node.
*/
static Plan *
create_append_plan(PlannerInfo *root, AppendPath *best_path)
{
Append *plan;
List *tlist = build_path_tlist(root, &best_path->path);
List *subplans = NIL;
ListCell *subpaths;
/*
* The subpaths list could be empty, if every child was proven empty by
* constraint exclusion. In that case generate a dummy plan that returns
* no rows.
*
* Note that an AppendPath with no members is also generated in certain
* cases where there was no appending construct at all, but we know the
* relation is empty (see set_dummy_rel_pathlist).
*/
if (best_path->subpaths == NIL)
{
/* Generate a Result plan with constant-FALSE gating qual */
Plan *plan;
plan = (Plan *) make_result(tlist,
(Node *) list_make1(makeBoolConst(false,
false)),
NULL);
copy_generic_path_info(plan, (Path *) best_path);
return plan;
}
/* Build the plan for each child */
foreach(subpaths, best_path->subpaths)
{
Path *subpath = (Path *) lfirst(subpaths);
Plan *subplan;
/* Must insist that all children return the same tlist */
subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
subplans = lappend(subplans, subplan);
}
/*
* XXX ideally, if there's just one child, we'd not bother to generate an
* Append node but just return the single child. At the moment this does
* not work because the varno of the child scan plan won't match the
* parent-rel Vars it'll be asked to emit.
*/
plan = make_append(subplans, tlist, best_path->partitioned_rels);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return (Plan *) plan;
}
/*
* create_merge_append_plan
* Create a MergeAppend plan for 'best_path' and (recursively) plans
* for its subpaths.
*
* Returns a Plan node.
*/
static Plan *
create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
{
MergeAppend *node = makeNode(MergeAppend);
Plan *plan = &node->plan;
List *tlist = build_path_tlist(root, &best_path->path);
List *pathkeys = best_path->path.pathkeys;
List *subplans = NIL;
ListCell *subpaths;
/*
* We don't have the actual creation of the MergeAppend node split out
* into a separate make_xxx function. This is because we want to run
* prepare_sort_from_pathkeys on it before we do so on the individual
* child plans, to make cross-checking the sort info easier.
*/
copy_generic_path_info(plan, (Path *) best_path);
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = NULL;
plan->righttree = NULL;
/* Compute sort column info, and adjust MergeAppend's tlist as needed */
(void) prepare_sort_from_pathkeys(plan, pathkeys,
best_path->path.parent->relids,
NULL,
true,
&node->numCols,
&node->sortColIdx,
&node->sortOperators,
&node->collations,
&node->nullsFirst);
/*
* Now prepare the child plans. We must apply prepare_sort_from_pathkeys
* even to subplans that don't need an explicit sort, to make sure they
* are returning the same sort key columns the MergeAppend expects.
*/
foreach(subpaths, best_path->subpaths)
{
Path *subpath = (Path *) lfirst(subpaths);
Plan *subplan;
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
/* Build the child plan */
/* Must insist that all children return the same tlist */
subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
/* Compute sort column info, and adjust subplan's tlist as needed */
subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
subpath->parent->relids,
node->sortColIdx,
false,
&numsortkeys,
&sortColIdx,
&sortOperators,
&collations,
&nullsFirst);
/*
* Check that we got the same sort key information. We just Assert
* that the sortops match, since those depend only on the pathkeys;
* but it seems like a good idea to check the sort column numbers
* explicitly, to ensure the tlists really do match up.
*/
Assert(numsortkeys == node->numCols);
if (memcmp(sortColIdx, node->sortColIdx,
numsortkeys * sizeof(AttrNumber)) != 0)
elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
Assert(memcmp(sortOperators, node->sortOperators,
numsortkeys * sizeof(Oid)) == 0);
Assert(memcmp(collations, node->collations,
numsortkeys * sizeof(Oid)) == 0);
Assert(memcmp(nullsFirst, node->nullsFirst,
numsortkeys * sizeof(bool)) == 0);
/* Now, insert a Sort node if subplan isn't sufficiently ordered */
if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
{
Sort *sort = make_sort(subplan, numsortkeys,
sortColIdx, sortOperators,
collations, nullsFirst);
label_sort_with_costsize(root, sort, best_path->limit_tuples);
subplan = (Plan *) sort;
}
subplans = lappend(subplans, subplan);
}
node->partitioned_rels = best_path->partitioned_rels;
node->mergeplans = subplans;
return (Plan *) node;
}
/*
* create_result_plan
* Create a Result plan for 'best_path'.
* This is only used for degenerate cases, such as a query with an empty
* jointree.
*
* Returns a Plan node.
*/
static Result *
create_result_plan(PlannerInfo *root, ResultPath *best_path)
{
Result *plan;
List *tlist;
List *quals;
tlist = build_path_tlist(root, &best_path->path);
/* best_path->quals is just bare clauses */
quals = order_qual_clauses(root, best_path->quals);
plan = make_result(tlist, (Node *) quals, NULL);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_project_set_plan
* Create a ProjectSet plan for 'best_path'.
*
* Returns a Plan node.
*/
static ProjectSet *
create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path)
{
ProjectSet *plan;
Plan *subplan;
List *tlist;
/* Since we intend to project, we don't need to constrain child tlist */
subplan = create_plan_recurse(root, best_path->subpath, 0);
tlist = build_path_tlist(root, &best_path->path);
plan = make_project_set(tlist, subplan);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_material_plan
* Create a Material plan for 'best_path' and (recursively) plans
* for its subpaths.
*
* Returns a Plan node.
*/
static Material *
create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
{
Material *plan;
Plan *subplan;
/*
* We don't want any excess columns in the materialized tuples, so request
* a smaller tlist. Otherwise, since Material doesn't project, tlist
* requirements pass through.
*/
subplan = create_plan_recurse(root, best_path->subpath,
flags | CP_SMALL_TLIST);
plan = make_material(subplan);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_unique_plan
* Create a Unique plan for 'best_path' and (recursively) plans
* for its subpaths.
*
* Returns a Plan node.
*/
static Plan *
create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
{
Plan *plan;
Plan *subplan;
List *in_operators;
List *uniq_exprs;
List *newtlist;
int nextresno;
bool newitems;
int numGroupCols;
AttrNumber *groupColIdx;
int groupColPos;
ListCell *l;
/* Unique doesn't project, so tlist requirements pass through */
subplan = create_plan_recurse(root, best_path->subpath, flags);
/* Done if we don't need to do any actual unique-ifying */
if (best_path->umethod == UNIQUE_PATH_NOOP)
return subplan;
/*
* As constructed, the subplan has a "flat" tlist containing just the Vars
* needed here and at upper levels. The values we are supposed to
* unique-ify may be expressions in these variables. We have to add any
* such expressions to the subplan's tlist.
*
* The subplan may have a "physical" tlist if it is a simple scan plan. If
* we're going to sort, this should be reduced to the regular tlist, so
* that we don't sort more data than we need to. For hashing, the tlist
* should be left as-is if we don't need to add any expressions; but if we
* do have to add expressions, then a projection step will be needed at
* runtime anyway, so we may as well remove unneeded items. Therefore
* newtlist starts from build_path_tlist() not just a copy of the
* subplan's tlist; and we don't install it into the subplan unless we are
* sorting or stuff has to be added.
*/
in_operators = best_path->in_operators;
uniq_exprs = best_path->uniq_exprs;
/* initialize modified subplan tlist as just the "required" vars */
newtlist = build_path_tlist(root, &best_path->path);
nextresno = list_length(newtlist) + 1;
newitems = false;
foreach(l, uniq_exprs)
{
Expr *uniqexpr = lfirst(l);
TargetEntry *tle;
tle = tlist_member(uniqexpr, newtlist);
if (!tle)
{
tle = makeTargetEntry((Expr *) uniqexpr,
nextresno,
NULL,
false);
newtlist = lappend(newtlist, tle);
nextresno++;
newitems = true;
}
}
if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
{
/*
* If the top plan node can't do projections and its existing target
* list isn't already what we need, we need to add a Result node to
* help it along.
*/
if (!is_projection_capable_plan(subplan) &&
!tlist_same_exprs(newtlist, subplan->targetlist))
subplan = inject_projection_plan(subplan, newtlist,
best_path->path.parallel_safe);
else
subplan->targetlist = newtlist;
}
/*
* Build control information showing which subplan output columns are to
* be examined by the grouping step. Unfortunately we can't merge this
* with the previous loop, since we didn't then know which version of the
* subplan tlist we'd end up using.
*/
newtlist = subplan->targetlist;
numGroupCols = list_length(uniq_exprs);
groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
groupColPos = 0;
foreach(l, uniq_exprs)
{
Expr *uniqexpr = lfirst(l);
TargetEntry *tle;
tle = tlist_member(uniqexpr, newtlist);
if (!tle) /* shouldn't happen */
elog(ERROR, "failed to find unique expression in subplan tlist");
groupColIdx[groupColPos++] = tle->resno;
}
if (best_path->umethod == UNIQUE_PATH_HASH)
{
Oid *groupOperators;
/*
* Get the hashable equality operators for the Agg node to use.
* Normally these are the same as the IN clause operators, but if
* those are cross-type operators then the equality operators are the
* ones for the IN clause operators' RHS datatype.
*/
groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
groupColPos = 0;
foreach(l, in_operators)
{
Oid in_oper = lfirst_oid(l);
Oid eq_oper;
if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
elog(ERROR, "could not find compatible hash operator for operator %u",
in_oper);
groupOperators[groupColPos++] = eq_oper;
}
/*
* Since the Agg node is going to project anyway, we can give it the
* minimum output tlist, without any stuff we might have added to the
* subplan tlist.
*/
plan = (Plan *) make_agg(build_path_tlist(root, &best_path->path),
NIL,
AGG_HASHED,
AGGSPLIT_SIMPLE,
numGroupCols,
groupColIdx,
groupOperators,
NIL,
NIL,
best_path->path.rows,
subplan);
}
else
{
List *sortList = NIL;
Sort *sort;
/* Create an ORDER BY list to sort the input compatibly */
groupColPos = 0;
foreach(l, in_operators)
{
Oid in_oper = lfirst_oid(l);
Oid sortop;
Oid eqop;
TargetEntry *tle;
SortGroupClause *sortcl;
sortop = get_ordering_op_for_equality_op(in_oper, false);
if (!OidIsValid(sortop)) /* shouldn't happen */
elog(ERROR, "could not find ordering operator for equality operator %u",
in_oper);
/*
* The Unique node will need equality operators. Normally these
* are the same as the IN clause operators, but if those are
* cross-type operators then the equality operators are the ones
* for the IN clause operators' RHS datatype.
*/
eqop = get_equality_op_for_ordering_op(sortop, NULL);
if (!OidIsValid(eqop)) /* shouldn't happen */
elog(ERROR, "could not find equality operator for ordering operator %u",
sortop);
tle = get_tle_by_resno(subplan->targetlist,
groupColIdx[groupColPos]);
Assert(tle != NULL);
sortcl = makeNode(SortGroupClause);
sortcl->tleSortGroupRef = assignSortGroupRef(tle,
subplan->targetlist);
sortcl->eqop = eqop;
sortcl->sortop = sortop;
sortcl->nulls_first = false;
sortcl->hashable = false; /* no need to make this accurate */
sortList = lappend(sortList, sortcl);
groupColPos++;
}
sort = make_sort_from_sortclauses(sortList, subplan);
label_sort_with_costsize(root, sort, -1.0);
plan = (Plan *) make_unique_from_sortclauses((Plan *) sort, sortList);
}
/* Copy cost data from Path to Plan */
copy_generic_path_info(plan, &best_path->path);
return plan;
}
/*
* create_gather_plan
*
* Create a Gather plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Gather *
create_gather_plan(PlannerInfo *root, GatherPath *best_path)
{
Gather *gather_plan;
Plan *subplan;
List *tlist;
/*
* Although the Gather node can project, we prefer to push down such work
* to its child node, so demand an exact tlist from the child.
*/
subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
tlist = build_path_tlist(root, &best_path->path);
gather_plan = make_gather(tlist,
NIL,
best_path->num_workers,
best_path->single_copy,
subplan);
copy_generic_path_info(&gather_plan->plan, &best_path->path);
/* use parallel mode for parallel plans. */
root->glob->parallelModeNeeded = true;
return gather_plan;
}
/*
* create_gather_merge_plan
*
* Create a Gather Merge plan for 'best_path' and (recursively)
* plans for its subpaths.
*/
static GatherMerge *
create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
{
GatherMerge *gm_plan;
Plan *subplan;
List *pathkeys = best_path->path.pathkeys;
List *tlist = build_path_tlist(root, &best_path->path);
/* As with Gather, it's best to project away columns in the workers. */
subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
/* Create a shell for a GatherMerge plan. */
gm_plan = makeNode(GatherMerge);
gm_plan->plan.targetlist = tlist;
gm_plan->num_workers = best_path->num_workers;
copy_generic_path_info(&gm_plan->plan, &best_path->path);
/* Gather Merge is pointless with no pathkeys; use Gather instead. */
Assert(pathkeys != NIL);
/* Compute sort column info, and adjust subplan's tlist as needed */
subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
best_path->subpath->parent->relids,
gm_plan->sortColIdx,
false,
&gm_plan->numCols,
&gm_plan->sortColIdx,
&gm_plan->sortOperators,
&gm_plan->collations,
&gm_plan->nullsFirst);
/* Now, insert a Sort node if subplan isn't sufficiently ordered */
if (!pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys))
subplan = (Plan *) make_sort(subplan, gm_plan->numCols,
gm_plan->sortColIdx,
gm_plan->sortOperators,
gm_plan->collations,
gm_plan->nullsFirst);
/* Now insert the subplan under GatherMerge. */
gm_plan->plan.lefttree = subplan;
/* use parallel mode for parallel plans. */
root->glob->parallelModeNeeded = true;
return gm_plan;
}
/*
* create_projection_plan
*
* Create a plan tree to do a projection step and (recursively) plans
* for its subpaths. We may need a Result node for the projection,
* but sometimes we can just let the subplan do the work.
*/
static Plan *
create_projection_plan(PlannerInfo *root, ProjectionPath *best_path)
{
Plan *plan;
Plan *subplan;
List *tlist;
/* Since we intend to project, we don't need to constrain child tlist */
subplan = create_plan_recurse(root, best_path->subpath, 0);
tlist = build_path_tlist(root, &best_path->path);
/*
* We might not really need a Result node here, either because the subplan
* can project or because it's returning the right list of expressions
* anyway. Usually create_projection_path will have detected that and set
* dummypp if we don't need a Result; but its decision can't be final,
* because some createplan.c routines change the tlists of their nodes.
* (An example is that create_merge_append_plan might add resjunk sort
* columns to a MergeAppend.) So we have to recheck here. If we do
* arrive at a different answer than create_projection_path did, we'll
* have made slightly wrong cost estimates; but label the plan with the
* cost estimates we actually used, not "corrected" ones. (XXX this could
* be cleaned up if we moved more of the sortcolumn setup logic into Path
* creation, but that would add expense to creating Paths we might end up
* not using.)
*/
if (is_projection_capable_path(best_path->subpath) ||
tlist_same_exprs(tlist, subplan->targetlist))
{
/* Don't need a separate Result, just assign tlist to subplan */
plan = subplan;
plan->targetlist = tlist;
/* Label plan with the estimated costs we actually used */
plan->startup_cost = best_path->path.startup_cost;
plan->total_cost = best_path->path.total_cost;
plan->plan_rows = best_path->path.rows;
plan->plan_width = best_path->path.pathtarget->width;
plan->parallel_safe = best_path->path.parallel_safe;
/* ... but don't change subplan's parallel_aware flag */
}
else
{
/* We need a Result node */
plan = (Plan *) make_result(tlist, NULL, subplan);
copy_generic_path_info(plan, (Path *) best_path);
}
return plan;
}
/*
* inject_projection_plan
* Insert a Result node to do a projection step.
*
* This is used in a few places where we decide on-the-fly that we need a
* projection step as part of the tree generated for some Path node.
* We should try to get rid of this in favor of doing it more honestly.
*
* One reason it's ugly is we have to be told the right parallel_safe marking
* to apply (since the tlist might be unsafe even if the child plan is safe).
*/
static Plan *
inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
{
Plan *plan;
plan = (Plan *) make_result(tlist, NULL, subplan);
/*
* In principle, we should charge tlist eval cost plus cpu_per_tuple per
* row for the Result node. But the former has probably been factored in
* already and the latter was not accounted for during Path construction,
* so being formally correct might just make the EXPLAIN output look less
* consistent not more so. Hence, just copy the subplan's cost.
*/
copy_plan_costsize(plan, subplan);
plan->parallel_safe = parallel_safe;
return plan;
}
/*
* create_sort_plan
*
* Create a Sort plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Sort *
create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
{
Sort *plan;
Plan *subplan;
/*
* We don't want any excess columns in the sorted tuples, so request a
* smaller tlist. Otherwise, since Sort doesn't project, tlist
* requirements pass through.
*/
subplan = create_plan_recurse(root, best_path->subpath,
flags | CP_SMALL_TLIST);
plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_group_plan
*
* Create a Group plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Group *
create_group_plan(PlannerInfo *root, GroupPath *best_path)
{
Group *plan;
Plan *subplan;
List *tlist;
List *quals;
/*
* Group can project, so no need to be terribly picky about child tlist,
* but we do need grouping columns to be available
*/
subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
tlist = build_path_tlist(root, &best_path->path);
quals = order_qual_clauses(root, best_path->qual);
plan = make_group(tlist,
quals,
list_length(best_path->groupClause),
extract_grouping_cols(best_path->groupClause,
subplan->targetlist),
extract_grouping_ops(best_path->groupClause),
subplan);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_upper_unique_plan
*
* Create a Unique plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Unique *
create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path, int flags)
{
Unique *plan;
Plan *subplan;
/*
* Unique doesn't project, so tlist requirements pass through; moreover we
* need grouping columns to be labeled.
*/
subplan = create_plan_recurse(root, best_path->subpath,
flags | CP_LABEL_TLIST);
plan = make_unique_from_pathkeys(subplan,
best_path->path.pathkeys,
best_path->numkeys);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_agg_plan
*
* Create an Agg plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Agg *
create_agg_plan(PlannerInfo *root, AggPath *best_path)
{
Agg *plan;
Plan *subplan;
List *tlist;
List *quals;
/*
* Agg can project, so no need to be terribly picky about child tlist, but
* we do need grouping columns to be available
*/
subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
tlist = build_path_tlist(root, &best_path->path);
quals = order_qual_clauses(root, best_path->qual);
plan = make_agg(tlist, quals,
best_path->aggstrategy,
best_path->aggsplit,
list_length(best_path->groupClause),
extract_grouping_cols(best_path->groupClause,
subplan->targetlist),
extract_grouping_ops(best_path->groupClause),
NIL,
NIL,
best_path->numGroups,
subplan);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* Given a groupclause for a collection of grouping sets, produce the
* corresponding groupColIdx.
*
* root->grouping_map maps the tleSortGroupRef to the actual column position in
* the input tuple. So we get the ref from the entries in the groupclause and
* look them up there.
*/
static AttrNumber *
remap_groupColIdx(PlannerInfo *root, List *groupClause)
{
AttrNumber *grouping_map = root->grouping_map;
AttrNumber *new_grpColIdx;
ListCell *lc;
int i;
Assert(grouping_map);
new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
i = 0;
foreach(lc, groupClause)
{
SortGroupClause *clause = lfirst(lc);
new_grpColIdx[i++] = grouping_map[clause->tleSortGroupRef];
}
return new_grpColIdx;
}
/*
* create_groupingsets_plan
* Create a plan for 'best_path' and (recursively) plans
* for its subpaths.
*
* What we emit is an Agg plan with some vestigial Agg and Sort nodes
* hanging off the side. The top Agg implements the last grouping set
* specified in the GroupingSetsPath, and any additional grouping sets
* each give rise to a subsidiary Agg and Sort node in the top Agg's
* "chain" list. These nodes don't participate in the plan directly,
* but they are a convenient way to represent the required data for
* the extra steps.
*
* Returns a Plan node.
*/
static Plan *
create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
{
Agg *plan;
Plan *subplan;
List *rollups = best_path->rollups;
AttrNumber *grouping_map;
int maxref;
List *chain;
ListCell *lc;
/* Shouldn't get here without grouping sets */
Assert(root->parse->groupingSets);
Assert(rollups != NIL);
/*
* Agg can project, so no need to be terribly picky about child tlist, but
* we do need grouping columns to be available
*/
subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
/*
* Compute the mapping from tleSortGroupRef to column index in the child's
* tlist. First, identify max SortGroupRef in groupClause, for array
* sizing.
*/
maxref = 0;
foreach(lc, root->parse->groupClause)
{
SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
if (gc->tleSortGroupRef > maxref)
maxref = gc->tleSortGroupRef;
}
grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
/* Now look up the column numbers in the child's tlist */
foreach(lc, root->parse->groupClause)
{
SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
grouping_map[gc->tleSortGroupRef] = tle->resno;
}
/*
* During setrefs.c, we'll need the grouping_map to fix up the cols lists
* in GroupingFunc nodes. Save it for setrefs.c to use.
*
* This doesn't work if we're in an inheritance subtree (see notes in
* create_modifytable_plan). Fortunately we can't be because there would
* never be grouping in an UPDATE/DELETE; but let's Assert that.
*/
Assert(!root->hasInheritedTarget);
Assert(root->grouping_map == NULL);
root->grouping_map = grouping_map;
/*
* Generate the side nodes that describe the other sort and group
* operations besides the top one. Note that we don't worry about putting
* accurate cost estimates in the side nodes; only the topmost Agg node's
* costs will be shown by EXPLAIN.
*/
chain = NIL;
if (list_length(rollups) > 1)
{
ListCell *lc2 = lnext(list_head(rollups));
bool is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
for_each_cell(lc, lc2)
{
RollupData *rollup = lfirst(lc);
AttrNumber *new_grpColIdx;
Plan *sort_plan = NULL;
Plan *agg_plan;
AggStrategy strat;
new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
if (!rollup->is_hashed && !is_first_sort)
{
sort_plan = (Plan *)
make_sort_from_groupcols(rollup->groupClause,
new_grpColIdx,
subplan);
}
if (!rollup->is_hashed)
is_first_sort = false;
if (rollup->is_hashed)
strat = AGG_HASHED;
else if (list_length(linitial(rollup->gsets)) == 0)
strat = AGG_PLAIN;
else
strat = AGG_SORTED;
agg_plan = (Plan *) make_agg(NIL,
NIL,
strat,
AGGSPLIT_SIMPLE,
list_length((List *) linitial(rollup->gsets)),
new_grpColIdx,
extract_grouping_ops(rollup->groupClause),
rollup->gsets,
NIL,
rollup->numGroups,
sort_plan);
/*
* Remove stuff we don't need to avoid bloating debug output.
*/
if (sort_plan)
{
sort_plan->targetlist = NIL;
sort_plan->lefttree = NULL;
}
chain = lappend(chain, agg_plan);
}
}
/*
* Now make the real Agg node
*/
{
RollupData *rollup = linitial(rollups);
AttrNumber *top_grpColIdx;
int numGroupCols;
top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
numGroupCols = list_length((List *) linitial(rollup->gsets));
plan = make_agg(build_path_tlist(root, &best_path->path),
best_path->qual,
best_path->aggstrategy,
AGGSPLIT_SIMPLE,
numGroupCols,
top_grpColIdx,
extract_grouping_ops(rollup->groupClause),
rollup->gsets,
chain,
rollup->numGroups,
subplan);
/* Copy cost data from Path to Plan */
copy_generic_path_info(&plan->plan, &best_path->path);
}
return (Plan *) plan;
}
/*
* create_minmaxagg_plan
*
* Create a Result plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Result *
create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
{
Result *plan;
List *tlist;
ListCell *lc;
/* Prepare an InitPlan for each aggregate's subquery. */
foreach(lc, best_path->mmaggregates)
{
MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
PlannerInfo *subroot = mminfo->subroot;
Query *subparse = subroot->parse;
Plan *plan;
/*
* Generate the plan for the subquery. We already have a Path, but we
* have to convert it to a Plan and attach a LIMIT node above it.
* Since we are entering a different planner context (subroot),
* recurse to create_plan not create_plan_recurse.
*/
plan = create_plan(subroot, mminfo->path);
plan = (Plan *) make_limit(plan,
subparse->limitOffset,
subparse->limitCount);
/* Must apply correct cost/width data to Limit node */
plan->startup_cost = mminfo->path->startup_cost;
plan->total_cost = mminfo->pathcost;
plan->plan_rows = 1;
plan->plan_width = mminfo->path->pathtarget->width;
plan->parallel_aware = false;
plan->parallel_safe = mminfo->path->parallel_safe;
/* Convert the plan into an InitPlan in the outer query. */
SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
}
/* Generate the output plan --- basically just a Result */
tlist = build_path_tlist(root, &best_path->path);
plan = make_result(tlist, (Node *) best_path->quals, NULL);
copy_generic_path_info(&plan->plan, (Path *) best_path);
/*
* During setrefs.c, we'll need to replace references to the Agg nodes
* with InitPlan output params. (We can't just do that locally in the
* MinMaxAgg node, because path nodes above here may have Agg references
* as well.) Save the mmaggregates list to tell setrefs.c to do that.
*
* This doesn't work if we're in an inheritance subtree (see notes in
* create_modifytable_plan). Fortunately we can't be because there would
* never be aggregates in an UPDATE/DELETE; but let's Assert that.
*/
Assert(!root->hasInheritedTarget);
Assert(root->minmax_aggs == NIL);
root->minmax_aggs = best_path->mmaggregates;
return plan;
}
/*
* create_windowagg_plan
*
* Create a WindowAgg plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static WindowAgg *
create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
{
WindowAgg *plan;
WindowClause *wc = best_path->winclause;
Plan *subplan;
List *tlist;
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
int partNumCols;
AttrNumber *partColIdx;
Oid *partOperators;
int ordNumCols;
AttrNumber *ordColIdx;
Oid *ordOperators;
/*
* WindowAgg can project, so no need to be terribly picky about child
* tlist, but we do need grouping columns to be available
*/
subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
tlist = build_path_tlist(root, &best_path->path);
/*
* We shouldn't need to actually sort, but it's convenient to use
* prepare_sort_from_pathkeys to identify the input's sort columns.
*/
subplan = prepare_sort_from_pathkeys(subplan,
best_path->winpathkeys,
NULL,
NULL,
false,
&numsortkeys,
&sortColIdx,
&sortOperators,
&collations,
&nullsFirst);
/* Now deconstruct that into partition and ordering portions */
get_column_info_for_window(root,
wc,
subplan->targetlist,
numsortkeys,
sortColIdx,
&partNumCols,
&partColIdx,
&partOperators,
&ordNumCols,
&ordColIdx,
&ordOperators);
/* And finally we can make the WindowAgg node */
plan = make_windowagg(tlist,
wc->winref,
partNumCols,
partColIdx,
partOperators,
ordNumCols,
ordColIdx,
ordOperators,
wc->frameOptions,
wc->startOffset,
wc->endOffset,
subplan);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* get_column_info_for_window
* Get the partitioning/ordering column numbers and equality operators
* for a WindowAgg node.
*
* This depends on the behavior of planner.c's make_pathkeys_for_window!
*
* We are given the target WindowClause and an array of the input column
* numbers associated with the resulting pathkeys. In the easy case, there
* are the same number of pathkey columns as partitioning + ordering columns
* and we just have to copy some data around. However, it's possible that
* some of the original partitioning + ordering columns were eliminated as
* redundant during the transformation to pathkeys. (This can happen even
* though the parser gets rid of obvious duplicates. A typical scenario is a
* window specification "PARTITION BY x ORDER BY y" coupled with a clause
* "WHERE x = y" that causes the two sort columns to be recognized as
* redundant.) In that unusual case, we have to work a lot harder to
* determine which keys are significant.
*
* The method used here is a bit brute-force: add the sort columns to a list
* one at a time and note when the resulting pathkey list gets longer. But
* it's a sufficiently uncommon case that a faster way doesn't seem worth
* the amount of code refactoring that'd be needed.
*/
static void
get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
int numSortCols, AttrNumber *sortColIdx,
int *partNumCols,
AttrNumber **partColIdx,
Oid **partOperators,
int *ordNumCols,
AttrNumber **ordColIdx,
Oid **ordOperators)
{
int numPart = list_length(wc->partitionClause);
int numOrder = list_length(wc->orderClause);
if (numSortCols == numPart + numOrder)
{
/* easy case */
*partNumCols = numPart;
*partColIdx = sortColIdx;
*partOperators = extract_grouping_ops(wc->partitionClause);
*ordNumCols = numOrder;
*ordColIdx = sortColIdx + numPart;
*ordOperators = extract_grouping_ops(wc->orderClause);
}
else
{
List *sortclauses;
List *pathkeys;
int scidx;
ListCell *lc;
/* first, allocate what's certainly enough space for the arrays */
*partNumCols = 0;
*partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
*partOperators = (Oid *) palloc(numPart * sizeof(Oid));
*ordNumCols = 0;
*ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
*ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
sortclauses = NIL;
pathkeys = NIL;
scidx = 0;
foreach(lc, wc->partitionClause)
{
SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
List *new_pathkeys;
sortclauses = lappend(sortclauses, sgc);
new_pathkeys = make_pathkeys_for_sortclauses(root,
sortclauses,
tlist);
if (list_length(new_pathkeys) > list_length(pathkeys))
{
/* this sort clause is actually significant */
(*partColIdx)[*partNumCols] = sortColIdx[scidx++];
(*partOperators)[*partNumCols] = sgc->eqop;
(*partNumCols)++;
pathkeys = new_pathkeys;
}
}
foreach(lc, wc->orderClause)
{
SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
List *new_pathkeys;
sortclauses = lappend(sortclauses, sgc);
new_pathkeys = make_pathkeys_for_sortclauses(root,
sortclauses,
tlist);
if (list_length(new_pathkeys) > list_length(pathkeys))
{
/* this sort clause is actually significant */
(*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
(*ordOperators)[*ordNumCols] = sgc->eqop;
(*ordNumCols)++;
pathkeys = new_pathkeys;
}
}
/* complain if we didn't eat exactly the right number of sort cols */
if (scidx != numSortCols)
elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
}
}
/*
* create_setop_plan
*
* Create a SetOp plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static SetOp *
create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
{
SetOp *plan;
Plan *subplan;
long numGroups;
/*
* SetOp doesn't project, so tlist requirements pass through; moreover we
* need grouping columns to be labeled.
*/
subplan = create_plan_recurse(root, best_path->subpath,
flags | CP_LABEL_TLIST);
/* Convert numGroups to long int --- but 'ware overflow! */
numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
plan = make_setop(best_path->cmd,
best_path->strategy,
subplan,
best_path->distinctList,
best_path->flagColIdx,
best_path->firstFlag,
numGroups);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_recursiveunion_plan
*
* Create a RecursiveUnion plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static RecursiveUnion *
create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
{
RecursiveUnion *plan;
Plan *leftplan;
Plan *rightplan;
List *tlist;
long numGroups;
/* Need both children to produce same tlist, so force it */
leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
tlist = build_path_tlist(root, &best_path->path);
/* Convert numGroups to long int --- but 'ware overflow! */
numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
plan = make_recursive_union(tlist,
leftplan,
rightplan,
best_path->wtParam,
best_path->distinctList,
numGroups);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_lockrows_plan
*
* Create a LockRows plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static LockRows *
create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
int flags)
{
LockRows *plan;
Plan *subplan;
/* LockRows doesn't project, so tlist requirements pass through */
subplan = create_plan_recurse(root, best_path->subpath, flags);
plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*
* create_modifytable_plan
* Create a ModifyTable plan for 'best_path'.
*
* Returns a Plan node.
*/
static ModifyTable *
create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
{
ModifyTable *plan;
List *subplans = NIL;
ListCell *subpaths,
*subroots;
/* Build the plan for each input path */
forboth(subpaths, best_path->subpaths,
subroots, best_path->subroots)
{
Path *subpath = (Path *) lfirst(subpaths);
PlannerInfo *subroot = (PlannerInfo *) lfirst(subroots);
Plan *subplan;
/*
* In an inherited UPDATE/DELETE, reference the per-child modified
* subroot while creating Plans from Paths for the child rel. This is
* a kluge, but otherwise it's too hard to ensure that Plan creation
* functions (particularly in FDWs) don't depend on the contents of
* "root" matching what they saw at Path creation time. The main
* downside is that creation functions for Plans that might appear
* below a ModifyTable cannot expect to modify the contents of "root"
* and have it "stick" for subsequent processing such as setrefs.c.
* That's not great, but it seems better than the alternative.
*/
subplan = create_plan_recurse(subroot, subpath, CP_EXACT_TLIST);
/* Transfer resname/resjunk labeling, too, to keep executor happy */
apply_tlist_labeling(subplan->targetlist, subroot->processed_tlist);
subplans = lappend(subplans, subplan);
}
plan = make_modifytable(root,
best_path->operation,
best_path->canSetTag,
best_path->nominalRelation,
best_path->partitioned_rels,
best_path->resultRelations,
subplans,
best_path->withCheckOptionLists,
best_path->returningLists,
best_path->rowMarks,
best_path->onconflict,
best_path->epqParam);
copy_generic_path_info(&plan->plan, &best_path->path);
return plan;
}
/*
* create_limit_plan
*
* Create a Limit plan for 'best_path' and (recursively) plans
* for its subpaths.
*/
static Limit *
create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
{
Limit *plan;
Plan *subplan;
/* Limit doesn't project, so tlist requirements pass through */
subplan = create_plan_recurse(root, best_path->subpath, flags);
plan = make_limit(subplan,
best_path->limitOffset,
best_path->limitCount);
copy_generic_path_info(&plan->plan, (Path *) best_path);
return plan;
}
/*****************************************************************************
*
* BASE-RELATION SCAN METHODS
*
*****************************************************************************/
/*
* create_seqscan_plan
* Returns a seqscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static SeqScan *
create_seqscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
SeqScan *scan_plan;
Index scan_relid = best_path->parent->relid;
/* it should be a base rel... */
Assert(scan_relid > 0);
Assert(best_path->parent->rtekind == RTE_RELATION);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
}
scan_plan = make_seqscan(tlist,
scan_clauses,
scan_relid);
copy_generic_path_info(&scan_plan->plan, best_path);
return scan_plan;
}
/*
* create_samplescan_plan
* Returns a samplescan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static SampleScan *
create_samplescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
SampleScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
TableSampleClause *tsc;
/* it should be a base rel with a tablesample clause... */
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_RELATION);
tsc = rte->tablesample;
Assert(tsc != NULL);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
tsc = (TableSampleClause *)
replace_nestloop_params(root, (Node *) tsc);
}
scan_plan = make_samplescan(tlist,
scan_clauses,
scan_relid,
tsc);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_indexscan_plan
* Returns an indexscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*
* We use this for both plain IndexScans and IndexOnlyScans, because the
* qual preprocessing work is the same for both. Note that the caller tells
* us which to build --- we don't look at best_path->path.pathtype, because
* create_bitmap_subplan needs to be able to override the prior decision.
*/
static Scan *
create_indexscan_plan(PlannerInfo *root,
IndexPath *best_path,
List *tlist,
List *scan_clauses,
bool indexonly)
{
Scan *scan_plan;
List *indexquals = best_path->indexquals;
List *indexorderbys = best_path->indexorderbys;
Index baserelid = best_path->path.parent->relid;
Oid indexoid = best_path->indexinfo->indexoid;
List *qpqual;
List *stripped_indexquals;
List *fixed_indexquals;
List *fixed_indexorderbys;
List *indexorderbyops = NIL;
ListCell *l;
/* it should be a base rel... */
Assert(baserelid > 0);
Assert(best_path->path.parent->rtekind == RTE_RELATION);
/*
* Build "stripped" indexquals structure (no RestrictInfos) to pass to
* executor as indexqualorig
*/
stripped_indexquals = get_actual_clauses(indexquals);
/*
* The executor needs a copy with the indexkey on the left of each clause
* and with index Vars substituted for table ones.
*/
fixed_indexquals = fix_indexqual_references(root, best_path);
/*
* Likewise fix up index attr references in the ORDER BY expressions.
*/
fixed_indexorderbys = fix_indexorderby_references(root, best_path);
/*
* The qpqual list must contain all restrictions not automatically handled
* by the index, other than pseudoconstant clauses which will be handled
* by a separate gating plan node. All the predicates in the indexquals
* will be checked (either by the index itself, or by nodeIndexscan.c),
* but if there are any "special" operators involved then they must be
* included in qpqual. The upshot is that qpqual must contain
* scan_clauses minus whatever appears in indexquals.
*
* In normal cases simple pointer equality checks will be enough to spot
* duplicate RestrictInfos, so we try that first.
*
* Another common case is that a scan_clauses entry is generated from the
* same EquivalenceClass as some indexqual, and is therefore redundant
* with it, though not equal. (This happens when indxpath.c prefers a
* different derived equality than what generate_join_implied_equalities
* picked for a parameterized scan's ppi_clauses.)
*
* In some situations (particularly with OR'd index conditions) we may
* have scan_clauses that are not equal to, but are logically implied by,
* the index quals; so we also try a predicate_implied_by() check to see
* if we can discard quals that way. (predicate_implied_by assumes its
* first input contains only immutable functions, so we have to check
* that.)
*
* Note: if you change this bit of code you should also look at
* extract_nonindex_conditions() in costsize.c.
*/
qpqual = NIL;
foreach(l, scan_clauses)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
if (rinfo->pseudoconstant)
continue; /* we may drop pseudoconstants here */
if (list_member_ptr(indexquals, rinfo))
continue; /* simple duplicate */
if (is_redundant_derived_clause(rinfo, indexquals))
continue; /* derived from same EquivalenceClass */
if (!contain_mutable_functions((Node *) rinfo->clause) &&
predicate_implied_by(list_make1(rinfo->clause), indexquals, false))
continue; /* provably implied by indexquals */
qpqual = lappend(qpqual, rinfo);
}
/* Sort clauses into best execution order */
qpqual = order_qual_clauses(root, qpqual);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
qpqual = extract_actual_clauses(qpqual, false);
/*
* We have to replace any outer-relation variables with nestloop params in
* the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
* annoying to have to do this separately from the processing in
* fix_indexqual_references --- rethink this when generalizing the inner
* indexscan support. But note we can't really do this earlier because
* it'd break the comparisons to predicates above ... (or would it? Those
* wouldn't have outer refs)
*/
if (best_path->path.param_info)
{
stripped_indexquals = (List *)
replace_nestloop_params(root, (Node *) stripped_indexquals);
qpqual = (List *)
replace_nestloop_params(root, (Node *) qpqual);
indexorderbys = (List *)
replace_nestloop_params(root, (Node *) indexorderbys);
}
/*
* If there are ORDER BY expressions, look up the sort operators for their
* result datatypes.
*/
if (indexorderbys)
{
ListCell *pathkeyCell,
*exprCell;
/*
* PathKey contains OID of the btree opfamily we're sorting by, but
* that's not quite enough because we need the expression's datatype
* to look up the sort operator in the operator family.
*/
Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
{
PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
Node *expr = (Node *) lfirst(exprCell);
Oid exprtype = exprType(expr);
Oid sortop;
/* Get sort operator from opfamily */
sortop = get_opfamily_member(pathkey->pk_opfamily,
exprtype,
exprtype,
pathkey->pk_strategy);
if (!OidIsValid(sortop))
elog(ERROR, "failed to find sort operator for ORDER BY expression");
indexorderbyops = lappend_oid(indexorderbyops, sortop);
}
}
/* Finally ready to build the plan node */
if (indexonly)
scan_plan = (Scan *) make_indexonlyscan(tlist,
qpqual,
baserelid,
indexoid,
fixed_indexquals,
fixed_indexorderbys,
best_path->indexinfo->indextlist,
best_path->indexscandir);
else
scan_plan = (Scan *) make_indexscan(tlist,
qpqual,
baserelid,
indexoid,
fixed_indexquals,
stripped_indexquals,
fixed_indexorderbys,
indexorderbys,
indexorderbyops,
best_path->indexscandir);
copy_generic_path_info(&scan_plan->plan, &best_path->path);
return scan_plan;
}
/*
* create_bitmap_scan_plan
* Returns a bitmap scan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static BitmapHeapScan *
create_bitmap_scan_plan(PlannerInfo *root,
BitmapHeapPath *best_path,
List *tlist,
List *scan_clauses)
{
Index baserelid = best_path->path.parent->relid;
Plan *bitmapqualplan;
List *bitmapqualorig;
List *indexquals;
List *indexECs;
List *qpqual;
ListCell *l;
BitmapHeapScan *scan_plan;
/* it should be a base rel... */
Assert(baserelid > 0);
Assert(best_path->path.parent->rtekind == RTE_RELATION);
/* Process the bitmapqual tree into a Plan tree and qual lists */
bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
&bitmapqualorig, &indexquals,
&indexECs);
if (best_path->path.parallel_aware)
bitmap_subplan_mark_shared(bitmapqualplan);
/*
* The qpqual list must contain all restrictions not automatically handled
* by the index, other than pseudoconstant clauses which will be handled
* by a separate gating plan node. All the predicates in the indexquals
* will be checked (either by the index itself, or by
* nodeBitmapHeapscan.c), but if there are any "special" operators
* involved then they must be added to qpqual. The upshot is that qpqual
* must contain scan_clauses minus whatever appears in indexquals.
*
* This loop is similar to the comparable code in create_indexscan_plan(),
* but with some differences because it has to compare the scan clauses to
* stripped (no RestrictInfos) indexquals. See comments there for more
* info.
*
* In normal cases simple equal() checks will be enough to spot duplicate
* clauses, so we try that first. We next see if the scan clause is
* redundant with any top-level indexqual by virtue of being generated
* from the same EC. After that, try predicate_implied_by().
*
* Unlike create_indexscan_plan(), the predicate_implied_by() test here is
* useful for getting rid of qpquals that are implied by index predicates,
* because the predicate conditions are included in the "indexquals"
* returned by create_bitmap_subplan(). Bitmap scans have to do it that
* way because predicate conditions need to be rechecked if the scan
* becomes lossy, so they have to be included in bitmapqualorig.
*/
qpqual = NIL;
foreach(l, scan_clauses)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
Node *clause = (Node *) rinfo->clause;
if (rinfo->pseudoconstant)
continue; /* we may drop pseudoconstants here */
if (list_member(indexquals, clause))
continue; /* simple duplicate */
if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
continue; /* derived from same EquivalenceClass */
if (!contain_mutable_functions(clause) &&
predicate_implied_by(list_make1(clause), indexquals, false))
continue; /* provably implied by indexquals */
qpqual = lappend(qpqual, rinfo);
}
/* Sort clauses into best execution order */
qpqual = order_qual_clauses(root, qpqual);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
qpqual = extract_actual_clauses(qpqual, false);
/*
* When dealing with special operators, we will at this point have
* duplicate clauses in qpqual and bitmapqualorig. We may as well drop
* 'em from bitmapqualorig, since there's no point in making the tests
* twice.
*/
bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
/*
* We have to replace any outer-relation variables with nestloop params in
* the qpqual and bitmapqualorig expressions. (This was already done for
* expressions attached to plan nodes in the bitmapqualplan tree.)
*/
if (best_path->path.param_info)
{
qpqual = (List *)
replace_nestloop_params(root, (Node *) qpqual);
bitmapqualorig = (List *)
replace_nestloop_params(root, (Node *) bitmapqualorig);
}
/* Finally ready to build the plan node */
scan_plan = make_bitmap_heapscan(tlist,
qpqual,
bitmapqualplan,
bitmapqualorig,
baserelid);
copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
return scan_plan;
}
/*
* Given a bitmapqual tree, generate the Plan tree that implements it
*
* As byproducts, we also return in *qual and *indexqual the qual lists
* (in implicit-AND form, without RestrictInfos) describing the original index
* conditions and the generated indexqual conditions. (These are the same in
* simple cases, but when special index operators are involved, the former
* list includes the special conditions while the latter includes the actual
* indexable conditions derived from them.) Both lists include partial-index
* predicates, because we have to recheck predicates as well as index
* conditions if the bitmap scan becomes lossy.
*
* In addition, we return a list of EquivalenceClass pointers for all the
* top-level indexquals that were possibly-redundantly derived from ECs.
* This allows removal of scan_clauses that are redundant with such quals.
* (We do not attempt to detect such redundancies for quals that are within
* OR subtrees. This could be done in a less hacky way if we returned the
* indexquals in RestrictInfo form, but that would be slower and still pretty
* messy, since we'd have to build new RestrictInfos in many cases.)
*/
static Plan *
create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
List **qual, List **indexqual, List **indexECs)
{
Plan *plan;
if (IsA(bitmapqual, BitmapAndPath))
{
BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
List *subplans = NIL;
List *subquals = NIL;
List *subindexquals = NIL;
List *subindexECs = NIL;
ListCell *l;
/*
* There may well be redundant quals among the subplans, since a
* top-level WHERE qual might have gotten used to form several
* different index quals. We don't try exceedingly hard to eliminate
* redundancies, but we do eliminate obvious duplicates by using
* list_concat_unique.
*/
foreach(l, apath->bitmapquals)
{
Plan *subplan;
List *subqual;
List *subindexqual;
List *subindexEC;
subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
&subqual, &subindexqual,
&subindexEC);
subplans = lappend(subplans, subplan);
subquals = list_concat_unique(subquals, subqual);
subindexquals = list_concat_unique(subindexquals, subindexqual);
/* Duplicates in indexECs aren't worth getting rid of */
subindexECs = list_concat(subindexECs, subindexEC);
}
plan = (Plan *) make_bitmap_and(subplans);
plan->startup_cost = apath->path.startup_cost;
plan->total_cost = apath->path.total_cost;
plan->plan_rows =
clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
plan->plan_width = 0; /* meaningless */
plan->parallel_aware = false;
plan->parallel_safe = apath->path.parallel_safe;
*qual = subquals;
*indexqual = subindexquals;
*indexECs = subindexECs;
}
else if (IsA(bitmapqual, BitmapOrPath))
{
BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
List *subplans = NIL;
List *subquals = NIL;
List *subindexquals = NIL;
bool const_true_subqual = false;
bool const_true_subindexqual = false;
ListCell *l;
/*
* Here, we only detect qual-free subplans. A qual-free subplan would
* cause us to generate "... OR true ..." which we may as well reduce
* to just "true". We do not try to eliminate redundant subclauses
* because (a) it's not as likely as in the AND case, and (b) we might
* well be working with hundreds or even thousands of OR conditions,
* perhaps from a long IN list. The performance of list_append_unique
* would be unacceptable.
*/
foreach(l, opath->bitmapquals)
{
Plan *subplan;
List *subqual;
List *subindexqual;
List *subindexEC;
subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
&subqual, &subindexqual,
&subindexEC);
subplans = lappend(subplans, subplan);
if (subqual == NIL)
const_true_subqual = true;
else if (!const_true_subqual)
subquals = lappend(subquals,
make_ands_explicit(subqual));
if (subindexqual == NIL)
const_true_subindexqual = true;
else if (!const_true_subindexqual)
subindexquals = lappend(subindexquals,
make_ands_explicit(subindexqual));
}
/*
* In the presence of ScalarArrayOpExpr quals, we might have built
* BitmapOrPaths with just one subpath; don't add an OR step.
*/
if (list_length(subplans) == 1)
{
plan = (Plan *) linitial(subplans);
}
else
{
plan = (Plan *) make_bitmap_or(subplans);
plan->startup_cost = opath->path.startup_cost;
plan->total_cost = opath->path.total_cost;
plan->plan_rows =
clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
plan->plan_width = 0; /* meaningless */
plan->parallel_aware = false;
plan->parallel_safe = opath->path.parallel_safe;
}
/*
* If there were constant-TRUE subquals, the OR reduces to constant
* TRUE. Also, avoid generating one-element ORs, which could happen
* due to redundancy elimination or ScalarArrayOpExpr quals.
*/
if (const_true_subqual)
*qual = NIL;
else if (list_length(subquals) <= 1)
*qual = subquals;
else
*qual = list_make1(make_orclause(subquals));
if (const_true_subindexqual)
*indexqual = NIL;
else if (list_length(subindexquals) <= 1)
*indexqual = subindexquals;
else
*indexqual = list_make1(make_orclause(subindexquals));
*indexECs = NIL;
}
else if (IsA(bitmapqual, IndexPath))
{
IndexPath *ipath = (IndexPath *) bitmapqual;
IndexScan *iscan;
List *subindexECs;
ListCell *l;
/* Use the regular indexscan plan build machinery... */
iscan = castNode(IndexScan,
create_indexscan_plan(root, ipath,
NIL, NIL, false));
/* then convert to a bitmap indexscan */
plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
iscan->indexid,
iscan->indexqual,
iscan->indexqualorig);
/* and set its cost/width fields appropriately */
plan->startup_cost = 0.0;
plan->total_cost = ipath->indextotalcost;
plan->plan_rows =
clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
plan->plan_width = 0; /* meaningless */
plan->parallel_aware = false;
plan->parallel_safe = ipath->path.parallel_safe;
*qual = get_actual_clauses(ipath->indexclauses);
*indexqual = get_actual_clauses(ipath->indexquals);
foreach(l, ipath->indexinfo->indpred)
{
Expr *pred = (Expr *) lfirst(l);
/*
* We know that the index predicate must have been implied by the
* query condition as a whole, but it may or may not be implied by
* the conditions that got pushed into the bitmapqual. Avoid
* generating redundant conditions.
*/
if (!predicate_implied_by(list_make1(pred), ipath->indexclauses,
false))
{
*qual = lappend(*qual, pred);
*indexqual = lappend(*indexqual, pred);
}
}
subindexECs = NIL;
foreach(l, ipath->indexquals)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
if (rinfo->parent_ec)
subindexECs = lappend(subindexECs, rinfo->parent_ec);
}
*indexECs = subindexECs;
}
else
{
elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
plan = NULL; /* keep compiler quiet */
}
return plan;
}
/*
* create_tidscan_plan
* Returns a tidscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static TidScan *
create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
List *tlist, List *scan_clauses)
{
TidScan *scan_plan;
Index scan_relid = best_path->path.parent->relid;
List *tidquals = best_path->tidquals;
List *ortidquals;
/* it should be a base rel... */
Assert(scan_relid > 0);
Assert(best_path->path.parent->rtekind == RTE_RELATION);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->path.param_info)
{
tidquals = (List *)
replace_nestloop_params(root, (Node *) tidquals);
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
}
/*
* Remove any clauses that are TID quals. This is a bit tricky since the
* tidquals list has implicit OR semantics.
*/
ortidquals = tidquals;
if (list_length(ortidquals) > 1)
ortidquals = list_make1(make_orclause(ortidquals));
scan_clauses = list_difference(scan_clauses, ortidquals);
scan_plan = make_tidscan(tlist,
scan_clauses,
scan_relid,
tidquals);
copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
return scan_plan;
}
/*
* create_subqueryscan_plan
* Returns a subqueryscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static SubqueryScan *
create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path,
List *tlist, List *scan_clauses)
{
SubqueryScan *scan_plan;
RelOptInfo *rel = best_path->path.parent;
Index scan_relid = rel->relid;
Plan *subplan;
/* it should be a subquery base rel... */
Assert(scan_relid > 0);
Assert(rel->rtekind == RTE_SUBQUERY);
/*
* Recursively create Plan from Path for subquery. Since we are entering
* a different planner context (subroot), recurse to create_plan not
* create_plan_recurse.
*/
subplan = create_plan(rel->subroot, best_path->subpath);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->path.param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
process_subquery_nestloop_params(root,
rel->subplan_params);
}
scan_plan = make_subqueryscan(tlist,
scan_clauses,
scan_relid,
subplan);
copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
return scan_plan;
}
/*
* create_functionscan_plan
* Returns a functionscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static FunctionScan *
create_functionscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
FunctionScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
List *functions;
/* it should be a function base rel... */
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_FUNCTION);
functions = rte->functions;
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
/* The function expressions could contain nestloop params, too */
functions = (List *) replace_nestloop_params(root, (Node *) functions);
}
scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
functions, rte->funcordinality);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_tablefuncscan_plan
* Returns a tablefuncscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static TableFuncScan *
create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
TableFuncScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
TableFunc *tablefunc;
/* it should be a function base rel... */
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_TABLEFUNC);
tablefunc = rte->tablefunc;
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
/* The function expressions could contain nestloop params, too */
tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
}
scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
tablefunc);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_valuesscan_plan
* Returns a valuesscan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static ValuesScan *
create_valuesscan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
ValuesScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
List *values_lists;
/* it should be a values base rel... */
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_VALUES);
values_lists = rte->values_lists;
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
/* The values lists could contain nestloop params, too */
values_lists = (List *)
replace_nestloop_params(root, (Node *) values_lists);
}
scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
values_lists);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_ctescan_plan
* Returns a ctescan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static CteScan *
create_ctescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
CteScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
SubPlan *ctesplan = NULL;
int plan_id;
int cte_param_id;
PlannerInfo *cteroot;
Index levelsup;
int ndx;
ListCell *lc;
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_CTE);
Assert(!rte->self_reference);
/*
* Find the referenced CTE, and locate the SubPlan previously made for it.
*/
levelsup = rte->ctelevelsup;
cteroot = root;
while (levelsup-- > 0)
{
cteroot = cteroot->parent_root;
if (!cteroot) /* shouldn't happen */
elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
}
/*
* Note: cte_plan_ids can be shorter than cteList, if we are still working
* on planning the CTEs (ie, this is a side-reference from another CTE).
* So we mustn't use forboth here.
*/
ndx = 0;
foreach(lc, cteroot->parse->cteList)
{
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
if (strcmp(cte->ctename, rte->ctename) == 0)
break;
ndx++;
}
if (lc == NULL) /* shouldn't happen */
elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
if (ndx >= list_length(cteroot->cte_plan_ids))
elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
Assert(plan_id > 0);
foreach(lc, cteroot->init_plans)
{
ctesplan = (SubPlan *) lfirst(lc);
if (ctesplan->plan_id == plan_id)
break;
}
if (lc == NULL) /* shouldn't happen */
elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
/*
* We need the CTE param ID, which is the sole member of the SubPlan's
* setParam list.
*/
cte_param_id = linitial_int(ctesplan->setParam);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
}
scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
plan_id, cte_param_id);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_namedtuplestorescan_plan
* Returns a tuplestorescan plan for the base relation scanned by
* 'best_path' with restriction clauses 'scan_clauses' and targetlist
* 'tlist'.
*/
static NamedTuplestoreScan *
create_namedtuplestorescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
NamedTuplestoreScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
}
scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
rte->enrname);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_worktablescan_plan
* Returns a worktablescan plan for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static WorkTableScan *
create_worktablescan_plan(PlannerInfo *root, Path *best_path,
List *tlist, List *scan_clauses)
{
WorkTableScan *scan_plan;
Index scan_relid = best_path->parent->relid;
RangeTblEntry *rte;
Index levelsup;
PlannerInfo *cteroot;
Assert(scan_relid > 0);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_CTE);
Assert(rte->self_reference);
/*
* We need to find the worktable param ID, which is in the plan level
* that's processing the recursive UNION, which is one level *below* where
* the CTE comes from.
*/
levelsup = rte->ctelevelsup;
if (levelsup == 0) /* shouldn't happen */
elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
levelsup--;
cteroot = root;
while (levelsup-- > 0)
{
cteroot = cteroot->parent_root;
if (!cteroot) /* shouldn't happen */
elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
}
if (cteroot->wt_param_id < 0) /* shouldn't happen */
elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
/* Sort clauses into best execution order */
scan_clauses = order_qual_clauses(root, scan_clauses);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->param_info)
{
scan_clauses = (List *)
replace_nestloop_params(root, (Node *) scan_clauses);
}
scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
cteroot->wt_param_id);
copy_generic_path_info(&scan_plan->scan.plan, best_path);
return scan_plan;
}
/*
* create_foreignscan_plan
* Returns a foreignscan plan for the relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static ForeignScan *
create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
List *tlist, List *scan_clauses)
{
ForeignScan *scan_plan;
RelOptInfo *rel = best_path->path.parent;
Index scan_relid = rel->relid;
Oid rel_oid = InvalidOid;
Plan *outer_plan = NULL;
Assert(rel->fdwroutine != NULL);
/* transform the child path if any */
if (best_path->fdw_outerpath)
outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
CP_EXACT_TLIST);
/*
* If we're scanning a base relation, fetch its OID. (Irrelevant if
* scanning a join relation.)
*/
if (scan_relid > 0)
{
RangeTblEntry *rte;
Assert(rel->rtekind == RTE_RELATION);
rte = planner_rt_fetch(scan_relid, root);
Assert(rte->rtekind == RTE_RELATION);
rel_oid = rte->relid;
}
/*
* Sort clauses into best execution order. We do this first since the FDW
* might have more info than we do and wish to adjust the ordering.
*/
scan_clauses = order_qual_clauses(root, scan_clauses);
/*
* Let the FDW perform its processing on the restriction clauses and
* generate the plan node. Note that the FDW might remove restriction
* clauses that it intends to execute remotely, or even add more (if it
* has selected some join clauses for remote use but also wants them
* rechecked locally).
*/
scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
best_path,
tlist, scan_clauses,
outer_plan);
/* Copy cost data from Path to Plan; no need to make FDW do this */
copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
/* Copy foreign server OID; likewise, no need to make FDW do this */
scan_plan->fs_server = rel->serverid;
/*
* Likewise, copy the relids that are represented by this foreign scan. An
* upper rel doesn't have relids set, but it covers all the base relations
* participating in the underlying scan, so use root's all_baserels.
*/
if (IS_UPPER_REL(rel))
scan_plan->fs_relids = root->all_baserels;
else
scan_plan->fs_relids = best_path->path.parent->relids;
/*
* If this is a foreign join, and to make it valid to push down we had to
* assume that the current user is the same as some user explicitly named
* in the query, mark the finished plan as depending on the current user.
*/
if (rel->useridiscurrent)
root->glob->dependsOnRole = true;
/*
* Replace any outer-relation variables with nestloop params in the qual,
* fdw_exprs and fdw_recheck_quals expressions. We do this last so that
* the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
* fdw_recheck_quals could have come from join clauses, so doing this
* beforehand on the scan_clauses wouldn't work.) We assume
* fdw_scan_tlist contains no such variables.
*/
if (best_path->path.param_info)
{
scan_plan->scan.plan.qual = (List *)
replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
scan_plan->fdw_exprs = (List *)
replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
scan_plan->fdw_recheck_quals = (List *)
replace_nestloop_params(root,
(Node *) scan_plan->fdw_recheck_quals);
}
/*
* If rel is a base relation, detect whether any system columns are
* requested from the rel. (If rel is a join relation, rel->relid will be
* 0, but there can be no Var with relid 0 in the rel's targetlist or the
* restriction clauses, so we skip this in that case. Note that any such
* columns in base relations that were joined are assumed to be contained
* in fdw_scan_tlist.) This is a bit of a kluge and might go away
* someday, so we intentionally leave it out of the API presented to FDWs.
*/
scan_plan->fsSystemCol = false;
if (scan_relid > 0)
{
Bitmapset *attrs_used = NULL;
ListCell *lc;
int i;
/*
* First, examine all the attributes needed for joins or final output.
* Note: we must look at rel's targetlist, not the attr_needed data,
* because attr_needed isn't computed for inheritance child rels.
*/
pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
/* Add all the attributes used by restriction clauses. */
foreach(lc, rel->baserestrictinfo)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
}
/* Now, are any system columns requested from rel? */
for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
{
if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
{
scan_plan->fsSystemCol = true;
break;
}
}
bms_free(attrs_used);
}
return scan_plan;
}
/*
* create_custom_plan
*
* Transform a CustomPath into a Plan.
*/
static CustomScan *
create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
List *tlist, List *scan_clauses)
{
CustomScan *cplan;
RelOptInfo *rel = best_path->path.parent;
List *custom_plans = NIL;
ListCell *lc;
/* Recursively transform child paths. */
foreach(lc, best_path->custom_paths)
{
Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
CP_EXACT_TLIST);
custom_plans = lappend(custom_plans, plan);
}
/*
* Sort clauses into the best execution order, although custom-scan
* provider can reorder them again.
*/
scan_clauses = order_qual_clauses(root, scan_clauses);
/*
* Invoke custom plan provider to create the Plan node represented by the
* CustomPath.
*/
cplan = castNode(CustomScan,
best_path->methods->PlanCustomPath(root,
rel,
best_path,
tlist,
scan_clauses,
custom_plans));
/*
* Copy cost data from Path to Plan; no need to make custom-plan providers
* do this
*/
copy_generic_path_info(&cplan->scan.plan, &best_path->path);
/* Likewise, copy the relids that are represented by this custom scan */
cplan->custom_relids = best_path->path.parent->relids;
/*
* Replace any outer-relation variables with nestloop params in the qual
* and custom_exprs expressions. We do this last so that the custom-plan
* provider doesn't have to be involved. (Note that parts of custom_exprs
* could have come from join clauses, so doing this beforehand on the
* scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
* such variables.
*/
if (best_path->path.param_info)
{
cplan->scan.plan.qual = (List *)
replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
cplan->custom_exprs = (List *)
replace_nestloop_params(root, (Node *) cplan->custom_exprs);
}
return cplan;
}
/*****************************************************************************
*
* JOIN METHODS
*
*****************************************************************************/
static NestLoop *
create_nestloop_plan(PlannerInfo *root,
NestPath *best_path)
{
NestLoop *join_plan;
Plan *outer_plan;
Plan *inner_plan;
List *tlist = build_path_tlist(root, &best_path->path);
List *joinrestrictclauses = best_path->joinrestrictinfo;
List *joinclauses;
List *otherclauses;
Relids outerrelids;
List *nestParams;
Relids saveOuterRels = root->curOuterRels;
ListCell *cell;
ListCell *prev;
ListCell *next;
/* NestLoop can project, so no need to be picky about child tlists */
outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
/* For a nestloop, include outer relids in curOuterRels for inner side */
root->curOuterRels = bms_union(root->curOuterRels,
best_path->outerjoinpath->parent->relids);
inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
/* Restore curOuterRels */
bms_free(root->curOuterRels);
root->curOuterRels = saveOuterRels;
/* Sort join qual clauses into best execution order */
joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
/* Get the join qual clauses (in plain expression form) */
/* Any pseudoconstant clauses are ignored here */
if (IS_OUTER_JOIN(best_path->jointype))
{
extract_actual_join_clauses(joinrestrictclauses,
&joinclauses, &otherclauses);
}
else
{
/* We can treat all clauses alike for an inner join */
joinclauses = extract_actual_clauses(joinrestrictclauses, false);
otherclauses = NIL;
}
/* Replace any outer-relation variables with nestloop params */
if (best_path->path.param_info)
{
joinclauses = (List *)
replace_nestloop_params(root, (Node *) joinclauses);
otherclauses = (List *)
replace_nestloop_params(root, (Node *) otherclauses);
}
/*
* Identify any nestloop parameters that should be supplied by this join
* node, and move them from root->curOuterParams to the nestParams list.
*/
outerrelids = best_path->outerjoinpath->parent->relids;
nestParams = NIL;
prev = NULL;
for (cell = list_head(root->curOuterParams); cell; cell = next)
{
NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
next = lnext(cell);
if (IsA(nlp->paramval, Var) &&
bms_is_member(nlp->paramval->varno, outerrelids))
{
root->curOuterParams = list_delete_cell(root->curOuterParams,
cell, prev);
nestParams = lappend(nestParams, nlp);
}
else if (IsA(nlp->paramval, PlaceHolderVar) &&
bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
outerrelids) &&
bms_is_subset(find_placeholder_info(root,
(PlaceHolderVar *) nlp->paramval,
false)->ph_eval_at,
outerrelids))
{
root->curOuterParams = list_delete_cell(root->curOuterParams,
cell, prev);
nestParams = lappend(nestParams, nlp);
}
else
prev = cell;
}
join_plan = make_nestloop(tlist,
joinclauses,
otherclauses,
nestParams,
outer_plan,
inner_plan,
best_path->jointype,
best_path->inner_unique);
copy_generic_path_info(&join_plan->join.plan, &best_path->path);
return join_plan;
}
static MergeJoin *
create_mergejoin_plan(PlannerInfo *root,
MergePath *best_path)
{
MergeJoin *join_plan;
Plan *outer_plan;
Plan *inner_plan;
List *tlist = build_path_tlist(root, &best_path->jpath.path);
List *joinclauses;
List *otherclauses;
List *mergeclauses;
List *outerpathkeys;
List *innerpathkeys;
int nClauses;
Oid *mergefamilies;
Oid *mergecollations;
int *mergestrategies;
bool *mergenullsfirst;
int i;
ListCell *lc;
ListCell *lop;
ListCell *lip;
/*
* MergeJoin can project, so we don't have to demand exact tlists from the
* inputs. However, if we're intending to sort an input's result, it's
* best to request a small tlist so we aren't sorting more data than
* necessary.
*/
outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
(best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
(best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
/* Sort join qual clauses into best execution order */
/* NB: do NOT reorder the mergeclauses */
joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
/* Get the join qual clauses (in plain expression form) */
/* Any pseudoconstant clauses are ignored here */
if (IS_OUTER_JOIN(best_path->jpath.jointype))
{
extract_actual_join_clauses(joinclauses,
&joinclauses, &otherclauses);
}
else
{
/* We can treat all clauses alike for an inner join */
joinclauses = extract_actual_clauses(joinclauses, false);
otherclauses = NIL;
}
/*
* Remove the mergeclauses from the list of join qual clauses, leaving the
* list of quals that must be checked as qpquals.
*/
mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
joinclauses = list_difference(joinclauses, mergeclauses);
/*
* Replace any outer-relation variables with nestloop params. There
* should not be any in the mergeclauses.
*/
if (best_path->jpath.path.param_info)
{
joinclauses = (List *)
replace_nestloop_params(root, (Node *) joinclauses);
otherclauses = (List *)
replace_nestloop_params(root, (Node *) otherclauses);
}
/*
* Rearrange mergeclauses, if needed, so that the outer variable is always
* on the left; mark the mergeclause restrictinfos with correct
* outer_is_left status.
*/
mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
best_path->jpath.outerjoinpath->parent->relids);
/*
* Create explicit sort nodes for the outer and inner paths if necessary.
*/
if (best_path->outersortkeys)
{
Sort *sort = make_sort_from_pathkeys(outer_plan,
best_path->outersortkeys);
label_sort_with_costsize(root, sort, -1.0);
outer_plan = (Plan *) sort;
outerpathkeys = best_path->outersortkeys;
}
else
outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
if (best_path->innersortkeys)
{
Sort *sort = make_sort_from_pathkeys(inner_plan,
best_path->innersortkeys);
label_sort_with_costsize(root, sort, -1.0);
inner_plan = (Plan *) sort;
innerpathkeys = best_path->innersortkeys;
}
else
innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
/*
* If specified, add a materialize node to shield the inner plan from the
* need to handle mark/restore.
*/
if (best_path->materialize_inner)
{
Plan *matplan = (Plan *) make_material(inner_plan);
/*
* We assume the materialize will not spill to disk, and therefore
* charge just cpu_operator_cost per tuple. (Keep this estimate in
* sync with final_cost_mergejoin.)
*/
copy_plan_costsize(matplan, inner_plan);
matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
inner_plan = matplan;
}
/*
* Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
* executor. The information is in the pathkeys for the two inputs, but
* we need to be careful about the possibility of mergeclauses sharing a
* pathkey (compare find_mergeclauses_for_pathkeys()).
*/
nClauses = list_length(mergeclauses);
Assert(nClauses == list_length(best_path->path_mergeclauses));
mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
mergestrategies = (int *) palloc(nClauses * sizeof(int));
mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
lop = list_head(outerpathkeys);
lip = list_head(innerpathkeys);
i = 0;
foreach(lc, best_path->path_mergeclauses)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
EquivalenceClass *oeclass;
EquivalenceClass *ieclass;
PathKey *opathkey;
PathKey *ipathkey;
EquivalenceClass *opeclass;
EquivalenceClass *ipeclass;
ListCell *l2;
/* fetch outer/inner eclass from mergeclause */
if (rinfo->outer_is_left)
{
oeclass = rinfo->left_ec;
ieclass = rinfo->right_ec;
}
else
{
oeclass = rinfo->right_ec;
ieclass = rinfo->left_ec;
}
Assert(oeclass != NULL);
Assert(ieclass != NULL);
/*
* For debugging purposes, we check that the eclasses match the paths'
* pathkeys. In typical cases the merge clauses are one-to-one with
* the pathkeys, but when dealing with partially redundant query
* conditions, we might have clauses that re-reference earlier path
* keys. The case that we need to reject is where a pathkey is
* entirely skipped over.
*
* lop and lip reference the first as-yet-unused pathkey elements;
* it's okay to match them, or any element before them. If they're
* NULL then we have found all pathkey elements to be used.
*/
if (lop)
{
opathkey = (PathKey *) lfirst(lop);
opeclass = opathkey->pk_eclass;
if (oeclass == opeclass)
{
/* fast path for typical case */
lop = lnext(lop);
}
else
{
/* redundant clauses ... must match something before lop */
foreach(l2, outerpathkeys)
{
if (l2 == lop)
break;
opathkey = (PathKey *) lfirst(l2);
opeclass = opathkey->pk_eclass;
if (oeclass == opeclass)
break;
}
if (oeclass != opeclass)
elog(ERROR, "outer pathkeys do not match mergeclauses");
}
}
else
{
/* redundant clauses ... must match some already-used pathkey */
opathkey = NULL;
opeclass = NULL;
foreach(l2, outerpathkeys)
{
opathkey = (PathKey *) lfirst(l2);
opeclass = opathkey->pk_eclass;
if (oeclass == opeclass)
break;
}
if (l2 == NULL)
elog(ERROR, "outer pathkeys do not match mergeclauses");
}
if (lip)
{
ipathkey = (PathKey *) lfirst(lip);
ipeclass = ipathkey->pk_eclass;
if (ieclass == ipeclass)
{
/* fast path for typical case */
lip = lnext(lip);
}
else
{
/* redundant clauses ... must match something before lip */
foreach(l2, innerpathkeys)
{
if (l2 == lip)
break;
ipathkey = (PathKey *) lfirst(l2);
ipeclass = ipathkey->pk_eclass;
if (ieclass == ipeclass)
break;
}
if (ieclass != ipeclass)
elog(ERROR, "inner pathkeys do not match mergeclauses");
}
}
else
{
/* redundant clauses ... must match some already-used pathkey */
ipathkey = NULL;
ipeclass = NULL;
foreach(l2, innerpathkeys)
{
ipathkey = (PathKey *) lfirst(l2);
ipeclass = ipathkey->pk_eclass;
if (ieclass == ipeclass)
break;
}
if (l2 == NULL)
elog(ERROR, "inner pathkeys do not match mergeclauses");
}
/* pathkeys should match each other too (more debugging) */
if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
opathkey->pk_strategy != ipathkey->pk_strategy ||
opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
elog(ERROR, "left and right pathkeys do not match in mergejoin");
/* OK, save info for executor */
mergefamilies[i] = opathkey->pk_opfamily;
mergecollations[i] = opathkey->pk_eclass->ec_collation;
mergestrategies[i] = opathkey->pk_strategy;
mergenullsfirst[i] = opathkey->pk_nulls_first;
i++;
}
/*
* Note: it is not an error if we have additional pathkey elements (i.e.,
* lop or lip isn't NULL here). The input paths might be better-sorted
* than we need for the current mergejoin.
*/
/*
* Now we can build the mergejoin node.
*/
join_plan = make_mergejoin(tlist,
joinclauses,
otherclauses,
mergeclauses,
mergefamilies,
mergecollations,
mergestrategies,
mergenullsfirst,
outer_plan,
inner_plan,
best_path->jpath.jointype,
best_path->jpath.inner_unique,
best_path->skip_mark_restore);
/* Costs of sort and material steps are included in path cost already */
copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
return join_plan;
}
static HashJoin *
create_hashjoin_plan(PlannerInfo *root,
HashPath *best_path)
{
HashJoin *join_plan;
Hash *hash_plan;
Plan *outer_plan;
Plan *inner_plan;
List *tlist = build_path_tlist(root, &best_path->jpath.path);
List *joinclauses;
List *otherclauses;
List *hashclauses;
Oid skewTable = InvalidOid;
AttrNumber skewColumn = InvalidAttrNumber;
bool skewInherit = false;
/*
* HashJoin can project, so we don't have to demand exact tlists from the
* inputs. However, it's best to request a small tlist from the inner
* side, so that we aren't storing more data than necessary. Likewise, if
* we anticipate batching, request a small tlist from the outer side so
* that we don't put extra data in the outer batch files.
*/
outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
(best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
CP_SMALL_TLIST);
/* Sort join qual clauses into best execution order */
joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
/* There's no point in sorting the hash clauses ... */
/* Get the join qual clauses (in plain expression form) */
/* Any pseudoconstant clauses are ignored here */
if (IS_OUTER_JOIN(best_path->jpath.jointype))
{
extract_actual_join_clauses(joinclauses,
&joinclauses, &otherclauses);
}
else
{
/* We can treat all clauses alike for an inner join */
joinclauses = extract_actual_clauses(joinclauses, false);
otherclauses = NIL;
}
/*
* Remove the hashclauses from the list of join qual clauses, leaving the
* list of quals that must be checked as qpquals.
*/
hashclauses = get_actual_clauses(best_path->path_hashclauses);
joinclauses = list_difference(joinclauses, hashclauses);
/*
* Replace any outer-relation variables with nestloop params. There
* should not be any in the hashclauses.
*/
if (best_path->jpath.path.param_info)
{
joinclauses = (List *)
replace_nestloop_params(root, (Node *) joinclauses);
otherclauses = (List *)
replace_nestloop_params(root, (Node *) otherclauses);
}
/*
* Rearrange hashclauses, if needed, so that the outer variable is always
* on the left.
*/
hashclauses = get_switched_clauses(best_path->path_hashclauses,
best_path->jpath.outerjoinpath->parent->relids);
/*
* If there is a single join clause and we can identify the outer variable
* as a simple column reference, supply its identity for possible use in
* skew optimization. (Note: in principle we could do skew optimization
* with multiple join clauses, but we'd have to be able to determine the
* most common combinations of outer values, which we don't currently have
* enough stats for.)
*/
if (list_length(hashclauses) == 1)
{
OpExpr *clause = (OpExpr *) linitial(hashclauses);
Node *node;
Assert(is_opclause(clause));
node = (Node *) linitial(clause->args);
if (IsA(node, RelabelType))
node = (Node *) ((RelabelType *) node)->arg;
if (IsA(node, Var))
{
Var *var = (Var *) node;
RangeTblEntry *rte;
rte = root->simple_rte_array[var->varno];
if (rte->rtekind == RTE_RELATION)
{
skewTable = rte->relid;
skewColumn = var->varattno;
skewInherit = rte->inh;
}
}
}
/*
* Build the hash node and hash join node.
*/
hash_plan = make_hash(inner_plan,
skewTable,
skewColumn,
skewInherit);
/*
* Set Hash node's startup & total costs equal to total cost of input
* plan; this only affects EXPLAIN display not decisions.
*/
copy_plan_costsize(&hash_plan->plan, inner_plan);
hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
join_plan = make_hashjoin(tlist,
joinclauses,
otherclauses,
hashclauses,
outer_plan,
(Plan *) hash_plan,
best_path->jpath.jointype,
best_path->jpath.inner_unique);
copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
return join_plan;
}
/*****************************************************************************
*
* SUPPORTING ROUTINES
*
*****************************************************************************/
/*
* replace_nestloop_params
* Replace outer-relation Vars and PlaceHolderVars in the given expression
* with nestloop Params
*
* All Vars and PlaceHolderVars belonging to the relation(s) identified by
* root->curOuterRels are replaced by Params, and entries are added to
* root->curOuterParams if not already present.
*/
static Node *
replace_nestloop_params(PlannerInfo *root, Node *expr)
{
/* No setup needed for tree walk, so away we go */
return replace_nestloop_params_mutator(expr, root);
}
static Node *
replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
{
if (node == NULL)
return NULL;
if (IsA(node, Var))
{
Var *var = (Var *) node;
Param *param;
NestLoopParam *nlp;
ListCell *lc;
/* Upper-level Vars should be long gone at this point */
Assert(var->varlevelsup == 0);
/* If not to be replaced, we can just return the Var unmodified */
if (!bms_is_member(var->varno, root->curOuterRels))
return node;
/* Create a Param representing the Var */
param = assign_nestloop_param_var(root, var);
/* Is this param already listed in root->curOuterParams? */
foreach(lc, root->curOuterParams)
{
nlp = (NestLoopParam *) lfirst(lc);
if (nlp->paramno == param->paramid)
{
Assert(equal(var, nlp->paramval));
/* Present, so we can just return the Param */
return (Node *) param;
}
}
/* No, so add it */
nlp = makeNode(NestLoopParam);
nlp->paramno = param->paramid;
nlp->paramval = var;
root->curOuterParams = lappend(root->curOuterParams, nlp);
/* And return the replacement Param */
return (Node *) param;
}
if (IsA(node, PlaceHolderVar))
{
PlaceHolderVar *phv = (PlaceHolderVar *) node;
Param *param;
NestLoopParam *nlp;
ListCell *lc;
/* Upper-level PlaceHolderVars should be long gone at this point */
Assert(phv->phlevelsup == 0);
/*
* Check whether we need to replace the PHV. We use bms_overlap as a
* cheap/quick test to see if the PHV might be evaluated in the outer
* rels, and then grab its PlaceHolderInfo to tell for sure.
*/
if (!bms_overlap(phv->phrels, root->curOuterRels) ||
!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
root->curOuterRels))
{
/*
* We can't replace the whole PHV, but we might still need to
* replace Vars or PHVs within its expression, in case it ends up
* actually getting evaluated here. (It might get evaluated in
* this plan node, or some child node; in the latter case we don't
* really need to process the expression here, but we haven't got
* enough info to tell if that's the case.) Flat-copy the PHV
* node and then recurse on its expression.
*
* Note that after doing this, we might have different
* representations of the contents of the same PHV in different
* parts of the plan tree. This is OK because equal() will just
* match on phid/phlevelsup, so setrefs.c will still recognize an
* upper-level reference to a lower-level copy of the same PHV.
*/
PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
memcpy(newphv, phv, sizeof(PlaceHolderVar));
newphv->phexpr = (Expr *)
replace_nestloop_params_mutator((Node *) phv->phexpr,
root);
return (Node *) newphv;
}
/* Create a Param representing the PlaceHolderVar */
param = assign_nestloop_param_placeholdervar(root, phv);
/* Is this param already listed in root->curOuterParams? */
foreach(lc, root->curOuterParams)
{
nlp = (NestLoopParam *) lfirst(lc);
if (nlp->paramno == param->paramid)
{
Assert(equal(phv, nlp->paramval));
/* Present, so we can just return the Param */
return (Node *) param;
}
}
/* No, so add it */
nlp = makeNode(NestLoopParam);
nlp->paramno = param->paramid;
nlp->paramval = (Var *) phv;
root->curOuterParams = lappend(root->curOuterParams, nlp);
/* And return the replacement Param */
return (Node *) param;
}
return expression_tree_mutator(node,
replace_nestloop_params_mutator,
(void *) root);
}
/*
* process_subquery_nestloop_params
* Handle params of a parameterized subquery that need to be fed
* from an outer nestloop.
*
* Currently, that would be *all* params that a subquery in FROM has demanded
* from the current query level, since they must be LATERAL references.
*
* The subplan's references to the outer variables are already represented
* as PARAM_EXEC Params, so we need not modify the subplan here. What we
* do need to do is add entries to root->curOuterParams to signal the parent
* nestloop plan node that it must provide these values.
*/
static void
process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
{
ListCell *ppl;
foreach(ppl, subplan_params)
{
PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
if (IsA(pitem->item, Var))
{
Var *var = (Var *) pitem->item;
NestLoopParam *nlp;
ListCell *lc;
/* If not from a nestloop outer rel, complain */
if (!bms_is_member(var->varno, root->curOuterRels))
elog(ERROR, "non-LATERAL parameter required by subquery");
/* Is this param already listed in root->curOuterParams? */
foreach(lc, root->curOuterParams)
{
nlp = (NestLoopParam *) lfirst(lc);
if (nlp->paramno == pitem->paramId)
{
Assert(equal(var, nlp->paramval));
/* Present, so nothing to do */
break;
}
}
if (lc == NULL)
{
/* No, so add it */
nlp = makeNode(NestLoopParam);
nlp->paramno = pitem->paramId;
nlp->paramval = copyObject(var);
root->curOuterParams = lappend(root->curOuterParams, nlp);
}
}
else if (IsA(pitem->item, PlaceHolderVar))
{
PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
NestLoopParam *nlp;
ListCell *lc;
/* If not from a nestloop outer rel, complain */
if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
root->curOuterRels))
elog(ERROR, "non-LATERAL parameter required by subquery");
/* Is this param already listed in root->curOuterParams? */
foreach(lc, root->curOuterParams)
{
nlp = (NestLoopParam *) lfirst(lc);
if (nlp->paramno == pitem->paramId)
{
Assert(equal(phv, nlp->paramval));
/* Present, so nothing to do */
break;
}
}
if (lc == NULL)
{
/* No, so add it */
nlp = makeNode(NestLoopParam);
nlp->paramno = pitem->paramId;
nlp->paramval = (Var *) copyObject(phv);
root->curOuterParams = lappend(root->curOuterParams, nlp);
}
}
else
elog(ERROR, "unexpected type of subquery parameter");
}
}
/*
* fix_indexqual_references
* Adjust indexqual clauses to the form the executor's indexqual
* machinery needs.
*
* We have four tasks here:
* * Remove RestrictInfo nodes from the input clauses.
* * Replace any outer-relation Var or PHV nodes with nestloop Params.
* (XXX eventually, that responsibility should go elsewhere?)
* * Index keys must be represented by Var nodes with varattno set to the
* index's attribute number, not the attribute number in the original rel.
* * If the index key is on the right, commute the clause to put it on the
* left.
*
* The result is a modified copy of the path's indexquals list --- the
* original is not changed. Note also that the copy shares no substructure
* with the original; this is needed in case there is a subplan in it (we need
* two separate copies of the subplan tree, or things will go awry).
*/
static List *
fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
{
IndexOptInfo *index = index_path->indexinfo;
List *fixed_indexquals;
ListCell *lcc,
*lci;
fixed_indexquals = NIL;
forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
int indexcol = lfirst_int(lci);
Node *clause;
/*
* Replace any outer-relation variables with nestloop params.
*
* This also makes a copy of the clause, so it's safe to modify it
* in-place below.
*/
clause = replace_nestloop_params(root, (Node *) rinfo->clause);
if (IsA(clause, OpExpr))
{
OpExpr *op = (OpExpr *) clause;
if (list_length(op->args) != 2)
elog(ERROR, "indexqual clause is not binary opclause");
/*
* Check to see if the indexkey is on the right; if so, commute
* the clause. The indexkey should be the side that refers to
* (only) the base relation.
*/
if (!bms_equal(rinfo->left_relids, index->rel->relids))
CommuteOpExpr(op);
/*
* Now replace the indexkey expression with an index Var.
*/
linitial(op->args) = fix_indexqual_operand(linitial(op->args),
index,
indexcol);
}
else if (IsA(clause, RowCompareExpr))
{
RowCompareExpr *rc = (RowCompareExpr *) clause;
Expr *newrc;
List *indexcolnos;
bool var_on_left;
ListCell *lca,
*lcai;
/*
* Re-discover which index columns are used in the rowcompare.
*/
newrc = adjust_rowcompare_for_index(rc,
index,
indexcol,
&indexcolnos,
&var_on_left);
/*
* Trouble if adjust_rowcompare_for_index thought the
* RowCompareExpr didn't match the index as-is; the clause should
* have gone through that routine already.
*/
if (newrc != (Expr *) rc)
elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
/*
* Check to see if the indexkey is on the right; if so, commute
* the clause.
*/
if (!var_on_left)
CommuteRowCompareExpr(rc);
/*
* Now replace the indexkey expressions with index Vars.
*/
Assert(list_length(rc->largs) == list_length(indexcolnos));
forboth(lca, rc->largs, lcai, indexcolnos)
{
lfirst(lca) = fix_indexqual_operand(lfirst(lca),
index,
lfirst_int(lcai));
}
}
else if (IsA(clause, ScalarArrayOpExpr))
{
ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
/* Never need to commute... */
/* Replace the indexkey expression with an index Var. */
linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
index,
indexcol);
}
else if (IsA(clause, NullTest))
{
NullTest *nt = (NullTest *) clause;
/* Replace the indexkey expression with an index Var. */
nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
index,
indexcol);
}
else
elog(ERROR, "unsupported indexqual type: %d",
(int) nodeTag(clause));
fixed_indexquals = lappend(fixed_indexquals, clause);
}
return fixed_indexquals;
}
/*
* fix_indexorderby_references
* Adjust indexorderby clauses to the form the executor's index
* machinery needs.
*
* This is a simplified version of fix_indexqual_references. The input does
* not have RestrictInfo nodes, and we assume that indxpath.c already
* commuted the clauses to put the index keys on the left. Also, we don't
* bother to support any cases except simple OpExprs, since nothing else
* is allowed for ordering operators.
*/
static List *
fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
{
IndexOptInfo *index = index_path->indexinfo;
List *fixed_indexorderbys;
ListCell *lcc,
*lci;
fixed_indexorderbys = NIL;
forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
{
Node *clause = (Node *) lfirst(lcc);
int indexcol = lfirst_int(lci);
/*
* Replace any outer-relation variables with nestloop params.
*
* This also makes a copy of the clause, so it's safe to modify it
* in-place below.
*/
clause = replace_nestloop_params(root, clause);
if (IsA(clause, OpExpr))
{
OpExpr *op = (OpExpr *) clause;
if (list_length(op->args) != 2)
elog(ERROR, "indexorderby clause is not binary opclause");
/*
* Now replace the indexkey expression with an index Var.
*/
linitial(op->args) = fix_indexqual_operand(linitial(op->args),
index,
indexcol);
}
else
elog(ERROR, "unsupported indexorderby type: %d",
(int) nodeTag(clause));
fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
}
return fixed_indexorderbys;
}
/*
* fix_indexqual_operand
* Convert an indexqual expression to a Var referencing the index column.
*
* We represent index keys by Var nodes having varno == INDEX_VAR and varattno
* equal to the index's attribute number (index column position).
*
* Most of the code here is just for sanity cross-checking that the given
* expression actually matches the index column it's claimed to.
*/
static Node *
fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
{
Var *result;
int pos;
ListCell *indexpr_item;
/*
* Remove any binary-compatible relabeling of the indexkey
*/
if (IsA(node, RelabelType))
node = (Node *) ((RelabelType *) node)->arg;
Assert(indexcol >= 0 && indexcol < index->ncolumns);
if (index->indexkeys[indexcol] != 0)
{
/* It's a simple index column */
if (IsA(node, Var) &&
((Var *) node)->varno == index->rel->relid &&
((Var *) node)->varattno == index->indexkeys[indexcol])
{
result = (Var *) copyObject(node);
result->varno = INDEX_VAR;
result->varattno = indexcol + 1;
return (Node *) result;
}
else
elog(ERROR, "index key does not match expected index column");
}
/* It's an index expression, so find and cross-check the expression */
indexpr_item = list_head(index->indexprs);
for (pos = 0; pos < index->ncolumns; pos++)
{
if (index->indexkeys[pos] == 0)
{
if (indexpr_item == NULL)
elog(ERROR, "too few entries in indexprs list");
if (pos == indexcol)
{
Node *indexkey;
indexkey = (Node *) lfirst(indexpr_item);
if (indexkey && IsA(indexkey, RelabelType))
indexkey = (Node *) ((RelabelType *) indexkey)->arg;
if (equal(node, indexkey))
{
result = makeVar(INDEX_VAR, indexcol + 1,
exprType(lfirst(indexpr_item)), -1,
exprCollation(lfirst(indexpr_item)),
0);
return (Node *) result;
}
else
elog(ERROR, "index key does not match expected index column");
}
indexpr_item = lnext(indexpr_item);
}
}
/* Oops... */
elog(ERROR, "index key does not match expected index column");
return NULL; /* keep compiler quiet */
}
/*
* get_switched_clauses
* Given a list of merge or hash joinclauses (as RestrictInfo nodes),
* extract the bare clauses, and rearrange the elements within the
* clauses, if needed, so the outer join variable is on the left and
* the inner is on the right. The original clause data structure is not
* touched; a modified list is returned. We do, however, set the transient
* outer_is_left field in each RestrictInfo to show which side was which.
*/
static List *
get_switched_clauses(List *clauses, Relids outerrelids)
{
List *t_list = NIL;
ListCell *l;
foreach(l, clauses)
{
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
OpExpr *clause = (OpExpr *) restrictinfo->clause;
Assert(is_opclause(clause));
if (bms_is_subset(restrictinfo->right_relids, outerrelids))
{
/*
* Duplicate just enough of the structure to allow commuting the
* clause without changing the original list. Could use
* copyObject, but a complete deep copy is overkill.
*/
OpExpr *temp = makeNode(OpExpr);
temp->opno = clause->opno;
temp->opfuncid = InvalidOid;
temp->opresulttype = clause->opresulttype;
temp->opretset = clause->opretset;
temp->opcollid = clause->opcollid;
temp->inputcollid = clause->inputcollid;
temp->args = list_copy(clause->args);
temp->location = clause->location;
/* Commute it --- note this modifies the temp node in-place. */
CommuteOpExpr(temp);
t_list = lappend(t_list, temp);
restrictinfo->outer_is_left = false;
}
else
{
Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
t_list = lappend(t_list, clause);
restrictinfo->outer_is_left = true;
}
}
return t_list;
}
/*
* order_qual_clauses
* Given a list of qual clauses that will all be evaluated at the same
* plan node, sort the list into the order we want to check the quals
* in at runtime.
*
* When security barrier quals are used in the query, we may have quals with
* different security levels in the list. Quals of lower security_level
* must go before quals of higher security_level, except that we can grant
* exceptions to move up quals that are leakproof. When security level
* doesn't force the decision, we prefer to order clauses by estimated
* execution cost, cheapest first.
*
* Ideally the order should be driven by a combination of execution cost and
* selectivity, but it's not immediately clear how to account for both,
* and given the uncertainty of the estimates the reliability of the decisions
* would be doubtful anyway. So we just order by security level then
* estimated per-tuple cost, being careful not to change the order when
* (as is often the case) the estimates are identical.
*
* Although this will work on either bare clauses or RestrictInfos, it's
* much faster to apply it to RestrictInfos, since it can re-use cost
* information that is cached in RestrictInfos. XXX in the bare-clause
* case, we are also not able to apply security considerations. That is
* all right for the moment, because the bare-clause case doesn't occur
* anywhere that barrier quals could be present, but it would be better to
* get rid of it.
*
* Note: some callers pass lists that contain entries that will later be
* removed; this is the easiest way to let this routine see RestrictInfos
* instead of bare clauses. This is another reason why trying to consider
* selectivity in the ordering would likely do the wrong thing.
*/
static List *
order_qual_clauses(PlannerInfo *root, List *clauses)
{
typedef struct
{
Node *clause;
Cost cost;
Index security_level;
} QualItem;
int nitems = list_length(clauses);
QualItem *items;
ListCell *lc;
int i;
List *result;
/* No need to work hard for 0 or 1 clause */
if (nitems <= 1)
return clauses;
/*
* Collect the items and costs into an array. This is to avoid repeated
* cost_qual_eval work if the inputs aren't RestrictInfos.
*/
items = (QualItem *) palloc(nitems * sizeof(QualItem));
i = 0;
foreach(lc, clauses)
{
Node *clause = (Node *) lfirst(lc);
QualCost qcost;
cost_qual_eval_node(&qcost, clause, root);
items[i].clause = clause;
items[i].cost = qcost.per_tuple;
if (IsA(clause, RestrictInfo))
{
RestrictInfo *rinfo = (RestrictInfo *) clause;
/*
* If a clause is leakproof, it doesn't have to be constrained by
* its nominal security level. If it's also reasonably cheap
* (here defined as 10X cpu_operator_cost), pretend it has
* security_level 0, which will allow it to go in front of
* more-expensive quals of lower security levels. Of course, that
* will also force it to go in front of cheaper quals of its own
* security level, which is not so great, but we can alleviate
* that risk by applying the cost limit cutoff.
*/
if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
items[i].security_level = 0;
else
items[i].security_level = rinfo->security_level;
}
else
items[i].security_level = 0;
i++;
}
/*
* Sort. We don't use qsort() because it's not guaranteed stable for
* equal keys. The expected number of entries is small enough that a
* simple insertion sort should be good enough.
*/
for (i = 1; i < nitems; i++)
{
QualItem newitem = items[i];
int j;
/* insert newitem into the already-sorted subarray */
for (j = i; j > 0; j--)
{
QualItem *olditem = &items[j - 1];
if (newitem.security_level > olditem->security_level ||
(newitem.security_level == olditem->security_level &&
newitem.cost >= olditem->cost))
break;
items[j] = *olditem;
}
items[j] = newitem;
}
/* Convert back to a list */
result = NIL;
for (i = 0; i < nitems; i++)
result = lappend(result, items[i].clause);
return result;
}
/*
* Copy cost and size info from a Path node to the Plan node created from it.
* The executor usually won't use this info, but it's needed by EXPLAIN.
* Also copy the parallel-related flags, which the executor *will* use.
*/
static void
copy_generic_path_info(Plan *dest, Path *src)
{
dest->startup_cost = src->startup_cost;
dest->total_cost = src->total_cost;
dest->plan_rows = src->rows;
dest->plan_width = src->pathtarget->width;
dest->parallel_aware = src->parallel_aware;
dest->parallel_safe = src->parallel_safe;
}
/*
* Copy cost and size info from a lower plan node to an inserted node.
* (Most callers alter the info after copying it.)
*/
static void
copy_plan_costsize(Plan *dest, Plan *src)
{
dest->startup_cost = src->startup_cost;
dest->total_cost = src->total_cost;
dest->plan_rows = src->plan_rows;
dest->plan_width = src->plan_width;
/* Assume the inserted node is not parallel-aware. */
dest->parallel_aware = false;
/* Assume the inserted node is parallel-safe, if child plan is. */
dest->parallel_safe = src->parallel_safe;
}
/*
* Some places in this file build Sort nodes that don't have a directly
* corresponding Path node. The cost of the sort is, or should have been,
* included in the cost of the Path node we're working from, but since it's
* not split out, we have to re-figure it using cost_sort(). This is just
* to label the Sort node nicely for EXPLAIN.
*
* limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
*/
static void
label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
{
Plan *lefttree = plan->plan.lefttree;
Path sort_path; /* dummy for result of cost_sort */
cost_sort(&sort_path, root, NIL,
lefttree->total_cost,
lefttree->plan_rows,
lefttree->plan_width,
0.0,
work_mem,
limit_tuples);
plan->plan.startup_cost = sort_path.startup_cost;
plan->plan.total_cost = sort_path.total_cost;
plan->plan.plan_rows = lefttree->plan_rows;
plan->plan.plan_width = lefttree->plan_width;
plan->plan.parallel_aware = false;
plan->plan.parallel_safe = lefttree->parallel_safe;
}
/*
* bitmap_subplan_mark_shared
* Set isshared flag in bitmap subplan so that it will be created in
* shared memory.
*/
static void
bitmap_subplan_mark_shared(Plan *plan)
{
if (IsA(plan, BitmapAnd))
bitmap_subplan_mark_shared(
linitial(((BitmapAnd *) plan)->bitmapplans));
else if (IsA(plan, BitmapOr))
((BitmapOr *) plan)->isshared = true;
else if (IsA(plan, BitmapIndexScan))
((BitmapIndexScan *) plan)->isshared = true;
else
elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
}
/*****************************************************************************
*
* PLAN NODE BUILDING ROUTINES
*
* In general, these functions are not passed the original Path and therefore
* leave it to the caller to fill in the cost/width fields from the Path,
* typically by calling copy_generic_path_info(). This convention is
* somewhat historical, but it does support a few places above where we build
* a plan node without having an exactly corresponding Path node. Under no
* circumstances should one of these functions do its own cost calculations,
* as that would be redundant with calculations done while building Paths.
*
*****************************************************************************/
static SeqScan *
make_seqscan(List *qptlist,
List *qpqual,
Index scanrelid)
{
SeqScan *node = makeNode(SeqScan);
Plan *plan = &node->plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scanrelid = scanrelid;
return node;
}
static SampleScan *
make_samplescan(List *qptlist,
List *qpqual,
Index scanrelid,
TableSampleClause *tsc)
{
SampleScan *node = makeNode(SampleScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->tablesample = tsc;
return node;
}
static IndexScan *
make_indexscan(List *qptlist,
List *qpqual,
Index scanrelid,
Oid indexid,
List *indexqual,
List *indexqualorig,
List *indexorderby,
List *indexorderbyorig,
List *indexorderbyops,
ScanDirection indexscandir)
{
IndexScan *node = makeNode(IndexScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->indexid = indexid;
node->indexqual = indexqual;
node->indexqualorig = indexqualorig;
node->indexorderby = indexorderby;
node->indexorderbyorig = indexorderbyorig;
node->indexorderbyops = indexorderbyops;
node->indexorderdir = indexscandir;
return node;
}
static IndexOnlyScan *
make_indexonlyscan(List *qptlist,
List *qpqual,
Index scanrelid,
Oid indexid,
List *indexqual,
List *indexorderby,
List *indextlist,
ScanDirection indexscandir)
{
IndexOnlyScan *node = makeNode(IndexOnlyScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->indexid = indexid;
node->indexqual = indexqual;
node->indexorderby = indexorderby;
node->indextlist = indextlist;
node->indexorderdir = indexscandir;
return node;
}
static BitmapIndexScan *
make_bitmap_indexscan(Index scanrelid,
Oid indexid,
List *indexqual,
List *indexqualorig)
{
BitmapIndexScan *node = makeNode(BitmapIndexScan);
Plan *plan = &node->scan.plan;
plan->targetlist = NIL; /* not used */
plan->qual = NIL; /* not used */
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->indexid = indexid;
node->indexqual = indexqual;
node->indexqualorig = indexqualorig;
return node;
}
static BitmapHeapScan *
make_bitmap_heapscan(List *qptlist,
List *qpqual,
Plan *lefttree,
List *bitmapqualorig,
Index scanrelid)
{
BitmapHeapScan *node = makeNode(BitmapHeapScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->bitmapqualorig = bitmapqualorig;
return node;
}
static TidScan *
make_tidscan(List *qptlist,
List *qpqual,
Index scanrelid,
List *tidquals)
{
TidScan *node = makeNode(TidScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->tidquals = tidquals;
return node;
}
static SubqueryScan *
make_subqueryscan(List *qptlist,
List *qpqual,
Index scanrelid,
Plan *subplan)
{
SubqueryScan *node = makeNode(SubqueryScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->subplan = subplan;
return node;
}
static FunctionScan *
make_functionscan(List *qptlist,
List *qpqual,
Index scanrelid,
List *functions,
bool funcordinality)
{
FunctionScan *node = makeNode(FunctionScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->functions = functions;
node->funcordinality = funcordinality;
return node;
}
static TableFuncScan *
make_tablefuncscan(List *qptlist,
List *qpqual,
Index scanrelid,
TableFunc *tablefunc)
{
TableFuncScan *node = makeNode(TableFuncScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->tablefunc = tablefunc;
return node;
}
static ValuesScan *
make_valuesscan(List *qptlist,
List *qpqual,
Index scanrelid,
List *values_lists)
{
ValuesScan *node = makeNode(ValuesScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->values_lists = values_lists;
return node;
}
static CteScan *
make_ctescan(List *qptlist,
List *qpqual,
Index scanrelid,
int ctePlanId,
int cteParam)
{
CteScan *node = makeNode(CteScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->ctePlanId = ctePlanId;
node->cteParam = cteParam;
return node;
}
static NamedTuplestoreScan *
make_namedtuplestorescan(List *qptlist,
List *qpqual,
Index scanrelid,
char *enrname)
{
NamedTuplestoreScan *node = makeNode(NamedTuplestoreScan);
Plan *plan = &node->scan.plan;
/* cost should be inserted by caller */
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->enrname = enrname;
return node;
}
static WorkTableScan *
make_worktablescan(List *qptlist,
List *qpqual,
Index scanrelid,
int wtParam)
{
WorkTableScan *node = makeNode(WorkTableScan);
Plan *plan = &node->scan.plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->wtParam = wtParam;
return node;
}
ForeignScan *
make_foreignscan(List *qptlist,
List *qpqual,
Index scanrelid,
List *fdw_exprs,
List *fdw_private,
List *fdw_scan_tlist,
List *fdw_recheck_quals,
Plan *outer_plan)
{
ForeignScan *node = makeNode(ForeignScan);
Plan *plan = &node->scan.plan;
/* cost will be filled in by create_foreignscan_plan */
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = outer_plan;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->operation = CMD_SELECT;
/* fs_server will be filled in by create_foreignscan_plan */
node->fs_server = InvalidOid;
node->fdw_exprs = fdw_exprs;
node->fdw_private = fdw_private;
node->fdw_scan_tlist = fdw_scan_tlist;
node->fdw_recheck_quals = fdw_recheck_quals;
/* fs_relids will be filled in by create_foreignscan_plan */
node->fs_relids = NULL;
/* fsSystemCol will be filled in by create_foreignscan_plan */
node->fsSystemCol = false;
return node;
}
static Append *
make_append(List *appendplans, List *tlist, List *partitioned_rels)
{
Append *node = makeNode(Append);
Plan *plan = &node->plan;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = NULL;
plan->righttree = NULL;
node->partitioned_rels = partitioned_rels;
node->appendplans = appendplans;
return node;
}
static RecursiveUnion *
make_recursive_union(List *tlist,
Plan *lefttree,
Plan *righttree,
int wtParam,
List *distinctList,
long numGroups)
{
RecursiveUnion *node = makeNode(RecursiveUnion);
Plan *plan = &node->plan;
int numCols = list_length(distinctList);
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->wtParam = wtParam;
/*
* convert SortGroupClause list into arrays of attr indexes and equality
* operators, as wanted by executor
*/
node->numCols = numCols;
if (numCols > 0)
{
int keyno = 0;
AttrNumber *dupColIdx;
Oid *dupOperators;
ListCell *slitem;
dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
foreach(slitem, distinctList)
{
SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
TargetEntry *tle = get_sortgroupclause_tle(sortcl,
plan->targetlist);
dupColIdx[keyno] = tle->resno;
dupOperators[keyno] = sortcl->eqop;
Assert(OidIsValid(dupOperators[keyno]));
keyno++;
}
node->dupColIdx = dupColIdx;
node->dupOperators = dupOperators;
}
node->numGroups = numGroups;
return node;
}
static BitmapAnd *
make_bitmap_and(List *bitmapplans)
{
BitmapAnd *node = makeNode(BitmapAnd);
Plan *plan = &node->plan;
plan->targetlist = NIL;
plan->qual = NIL;
plan->lefttree = NULL;
plan->righttree = NULL;
node->bitmapplans = bitmapplans;
return node;
}
static BitmapOr *
make_bitmap_or(List *bitmapplans)
{
BitmapOr *node = makeNode(BitmapOr);
Plan *plan = &node->plan;
plan->targetlist = NIL;
plan->qual = NIL;
plan->lefttree = NULL;
plan->righttree = NULL;
node->bitmapplans = bitmapplans;
return node;
}
static NestLoop *
make_nestloop(List *tlist,
List *joinclauses,
List *otherclauses,
List *nestParams,
Plan *lefttree,
Plan *righttree,
JoinType jointype,
bool inner_unique)
{
NestLoop *node = makeNode(NestLoop);
Plan *plan = &node->join.plan;
plan->targetlist = tlist;
plan->qual = otherclauses;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->join.jointype = jointype;
node->join.inner_unique = inner_unique;
node->join.joinqual = joinclauses;
node->nestParams = nestParams;
return node;
}
static HashJoin *
make_hashjoin(List *tlist,
List *joinclauses,
List *otherclauses,
List *hashclauses,
Plan *lefttree,
Plan *righttree,
JoinType jointype,
bool inner_unique)
{
HashJoin *node = makeNode(HashJoin);
Plan *plan = &node->join.plan;
plan->targetlist = tlist;
plan->qual = otherclauses;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->hashclauses = hashclauses;
node->join.jointype = jointype;
node->join.inner_unique = inner_unique;
node->join.joinqual = joinclauses;
return node;
}
static Hash *
make_hash(Plan *lefttree,
Oid skewTable,
AttrNumber skewColumn,
bool skewInherit)
{
Hash *node = makeNode(Hash);
Plan *plan = &node->plan;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->skewTable = skewTable;
node->skewColumn = skewColumn;
node->skewInherit = skewInherit;
return node;
}
static MergeJoin *
make_mergejoin(List *tlist,
List *joinclauses,
List *otherclauses,
List *mergeclauses,
Oid *mergefamilies,
Oid *mergecollations,
int *mergestrategies,
bool *mergenullsfirst,
Plan *lefttree,
Plan *righttree,
JoinType jointype,
bool inner_unique,
bool skip_mark_restore)
{
MergeJoin *node = makeNode(MergeJoin);
Plan *plan = &node->join.plan;
plan->targetlist = tlist;
plan->qual = otherclauses;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->skip_mark_restore = skip_mark_restore;
node->mergeclauses = mergeclauses;
node->mergeFamilies = mergefamilies;
node->mergeCollations = mergecollations;
node->mergeStrategies = mergestrategies;
node->mergeNullsFirst = mergenullsfirst;
node->join.jointype = jointype;
node->join.inner_unique = inner_unique;
node->join.joinqual = joinclauses;
return node;
}
/*
* make_sort --- basic routine to build a Sort plan node
*
* Caller must have built the sortColIdx, sortOperators, collations, and
* nullsFirst arrays already.
*/
static Sort *
make_sort(Plan *lefttree, int numCols,
AttrNumber *sortColIdx, Oid *sortOperators,
Oid *collations, bool *nullsFirst)
{
Sort *node = makeNode(Sort);
Plan *plan = &node->plan;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->numCols = numCols;
node->sortColIdx = sortColIdx;
node->sortOperators = sortOperators;
node->collations = collations;
node->nullsFirst = nullsFirst;
return node;
}
/*
* prepare_sort_from_pathkeys
* Prepare to sort according to given pathkeys
*
* This is used to set up for Sort, MergeAppend, and Gather Merge nodes. It
* calculates the executor's representation of the sort key information, and
* adjusts the plan targetlist if needed to add resjunk sort columns.
*
* Input parameters:
* 'lefttree' is the plan node which yields input tuples
* 'pathkeys' is the list of pathkeys by which the result is to be sorted
* 'relids' identifies the child relation being sorted, if any
* 'reqColIdx' is NULL or an array of required sort key column numbers
* 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
*
* We must convert the pathkey information into arrays of sort key column
* numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
* which is the representation the executor wants. These are returned into
* the output parameters *p_numsortkeys etc.
*
* When looking for matches to an EquivalenceClass's members, we will only
* consider child EC members if they match 'relids'. This protects against
* possible incorrect matches to child expressions that contain no Vars.
*
* If reqColIdx isn't NULL then it contains sort key column numbers that
* we should match. This is used when making child plans for a MergeAppend;
* it's an error if we can't match the columns.
*
* If the pathkeys include expressions that aren't simple Vars, we will
* usually need to add resjunk items to the input plan's targetlist to
* compute these expressions, since a Sort or MergeAppend node itself won't
* do any such calculations. If the input plan type isn't one that can do
* projections, this means adding a Result node just to do the projection.
* However, the caller can pass adjust_tlist_in_place = TRUE to force the
* lefttree tlist to be modified in-place regardless of whether the node type
* can project --- we use this for fixing the tlist of MergeAppend itself.
*
* Returns the node which is to be the input to the Sort (either lefttree,
* or a Result stacked atop lefttree).
*/
static Plan *
prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
Relids relids,
const AttrNumber *reqColIdx,
bool adjust_tlist_in_place,
int *p_numsortkeys,
AttrNumber **p_sortColIdx,
Oid **p_sortOperators,
Oid **p_collations,
bool **p_nullsFirst)
{
List *tlist = lefttree->targetlist;
ListCell *i;
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
/*
* We will need at most list_length(pathkeys) sort columns; possibly less
*/
numsortkeys = list_length(pathkeys);
sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
numsortkeys = 0;
foreach(i, pathkeys)
{
PathKey *pathkey = (PathKey *) lfirst(i);
EquivalenceClass *ec = pathkey->pk_eclass;
EquivalenceMember *em;
TargetEntry *tle = NULL;
Oid pk_datatype = InvalidOid;
Oid sortop;
ListCell *j;
if (ec->ec_has_volatile)
{
/*
* If the pathkey's EquivalenceClass is volatile, then it must
* have come from an ORDER BY clause, and we have to match it to
* that same targetlist entry.
*/
if (ec->ec_sortref == 0) /* can't happen */
elog(ERROR, "volatile EquivalenceClass has no sortref");
tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
Assert(tle);
Assert(list_length(ec->ec_members) == 1);
pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
}
else if (reqColIdx != NULL)
{
/*
* If we are given a sort column number to match, only consider
* the single TLE at that position. It's possible that there is
* no such TLE, in which case fall through and generate a resjunk
* targetentry (we assume this must have happened in the parent
* plan as well). If there is a TLE but it doesn't match the
* pathkey's EC, we do the same, which is probably the wrong thing
* but we'll leave it to caller to complain about the mismatch.
*/
tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
if (tle)
{
em = find_ec_member_for_tle(ec, tle, relids);
if (em)
{
/* found expr at right place in tlist */
pk_datatype = em->em_datatype;
}
else
tle = NULL;
}
}
else
{
/*
* Otherwise, we can sort by any non-constant expression listed in
* the pathkey's EquivalenceClass. For now, we take the first
* tlist item found in the EC. If there's no match, we'll generate
* a resjunk entry using the first EC member that is an expression
* in the input's vars. (The non-const restriction only matters
* if the EC is below_outer_join; but if it isn't, it won't
* contain consts anyway, else we'd have discarded the pathkey as
* redundant.)
*
* XXX if we have a choice, is there any way of figuring out which
* might be cheapest to execute? (For example, int4lt is likely
* much cheaper to execute than numericlt, but both might appear
* in the same equivalence class...) Not clear that we ever will
* have an interesting choice in practice, so it may not matter.
*/
foreach(j, tlist)
{
tle = (TargetEntry *) lfirst(j);
em = find_ec_member_for_tle(ec, tle, relids);
if (em)
{
/* found expr already in tlist */
pk_datatype = em->em_datatype;
break;
}
tle = NULL;
}
}
if (!tle)
{
/*
* No matching tlist item; look for a computable expression. Note
* that we treat Aggrefs as if they were variables; this is
* necessary when attempting to sort the output from an Agg node
* for use in a WindowFunc (since grouping_planner will have
* treated the Aggrefs as variables, too). Likewise, if we find a
* WindowFunc in a sort expression, treat it as a variable.
*/
Expr *sortexpr = NULL;
foreach(j, ec->ec_members)
{
EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
List *exprvars;
ListCell *k;
/*
* We shouldn't be trying to sort by an equivalence class that
* contains a constant, so no need to consider such cases any
* further.
*/
if (em->em_is_const)
continue;
/*
* Ignore child members unless they match the rel being
* sorted.
*/
if (em->em_is_child &&
!bms_equal(em->em_relids, relids))
continue;
sortexpr = em->em_expr;
exprvars = pull_var_clause((Node *) sortexpr,
PVC_INCLUDE_AGGREGATES |
PVC_INCLUDE_WINDOWFUNCS |
PVC_INCLUDE_PLACEHOLDERS);
foreach(k, exprvars)
{
if (!tlist_member_ignore_relabel(lfirst(k), tlist))
break;
}
list_free(exprvars);
if (!k)
{
pk_datatype = em->em_datatype;
break; /* found usable expression */
}
}
if (!j)
elog(ERROR, "could not find pathkey item to sort");
/*
* Do we need to insert a Result node?
*/
if (!adjust_tlist_in_place &&
!is_projection_capable_plan(lefttree))
{
/* copy needed so we don't modify input's tlist below */
tlist = copyObject(tlist);
lefttree = inject_projection_plan(lefttree, tlist,
lefttree->parallel_safe);
}
/* Don't bother testing is_projection_capable_plan again */
adjust_tlist_in_place = true;
/*
* Add resjunk entry to input's tlist
*/
tle = makeTargetEntry(sortexpr,
list_length(tlist) + 1,
NULL,
true);
tlist = lappend(tlist, tle);
lefttree->targetlist = tlist; /* just in case NIL before */
}
/*
* Look up the correct sort operator from the PathKey's slightly
* abstracted representation.
*/
sortop = get_opfamily_member(pathkey->pk_opfamily,
pk_datatype,
pk_datatype,
pathkey->pk_strategy);
if (!OidIsValid(sortop)) /* should not happen */
elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
pathkey->pk_strategy, pk_datatype, pk_datatype,
pathkey->pk_opfamily);
/* Add the column to the sort arrays */
sortColIdx[numsortkeys] = tle->resno;
sortOperators[numsortkeys] = sortop;
collations[numsortkeys] = ec->ec_collation;
nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
numsortkeys++;
}
/* Return results */
*p_numsortkeys = numsortkeys;
*p_sortColIdx = sortColIdx;
*p_sortOperators = sortOperators;
*p_collations = collations;
*p_nullsFirst = nullsFirst;
return lefttree;
}
/*
* find_ec_member_for_tle
* Locate an EquivalenceClass member matching the given TLE, if any
*
* Child EC members are ignored unless they match 'relids'.
*/
static EquivalenceMember *
find_ec_member_for_tle(EquivalenceClass *ec,
TargetEntry *tle,
Relids relids)
{
Expr *tlexpr;
ListCell *lc;
/* We ignore binary-compatible relabeling on both ends */
tlexpr = tle->expr;
while (tlexpr && IsA(tlexpr, RelabelType))
tlexpr = ((RelabelType *) tlexpr)->arg;
foreach(lc, ec->ec_members)
{
EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
Expr *emexpr;
/*
* We shouldn't be trying to sort by an equivalence class that
* contains a constant, so no need to consider such cases any further.
*/
if (em->em_is_const)
continue;
/*
* Ignore child members unless they match the rel being sorted.
*/
if (em->em_is_child &&
!bms_equal(em->em_relids, relids))
continue;
/* Match if same expression (after stripping relabel) */
emexpr = em->em_expr;
while (emexpr && IsA(emexpr, RelabelType))
emexpr = ((RelabelType *) emexpr)->arg;
if (equal(emexpr, tlexpr))
return em;
}
return NULL;
}
/*
* make_sort_from_pathkeys
* Create sort plan to sort according to given pathkeys
*
* 'lefttree' is the node which yields input tuples
* 'pathkeys' is the list of pathkeys by which the result is to be sorted
*/
static Sort *
make_sort_from_pathkeys(Plan *lefttree, List *pathkeys)
{
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
/* Compute sort column info, and adjust lefttree as needed */
lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
NULL,
NULL,
false,
&numsortkeys,
&sortColIdx,
&sortOperators,
&collations,
&nullsFirst);
/* Now build the Sort node */
return make_sort(lefttree, numsortkeys,
sortColIdx, sortOperators,
collations, nullsFirst);
}
/*
* make_sort_from_sortclauses
* Create sort plan to sort according to given sortclauses
*
* 'sortcls' is a list of SortGroupClauses
* 'lefttree' is the node which yields input tuples
*/
Sort *
make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
{
List *sub_tlist = lefttree->targetlist;
ListCell *l;
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
/* Convert list-ish representation to arrays wanted by executor */
numsortkeys = list_length(sortcls);
sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
numsortkeys = 0;
foreach(l, sortcls)
{
SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
sortColIdx[numsortkeys] = tle->resno;
sortOperators[numsortkeys] = sortcl->sortop;
collations[numsortkeys] = exprCollation((Node *) tle->expr);
nullsFirst[numsortkeys] = sortcl->nulls_first;
numsortkeys++;
}
return make_sort(lefttree, numsortkeys,
sortColIdx, sortOperators,
collations, nullsFirst);
}
/*
* make_sort_from_groupcols
* Create sort plan to sort based on grouping columns
*
* 'groupcls' is the list of SortGroupClauses
* 'grpColIdx' gives the column numbers to use
*
* This might look like it could be merged with make_sort_from_sortclauses,
* but presently we *must* use the grpColIdx[] array to locate sort columns,
* because the child plan's tlist is not marked with ressortgroupref info
* appropriate to the grouping node. So, only the sort ordering info
* is used from the SortGroupClause entries.
*/
static Sort *
make_sort_from_groupcols(List *groupcls,
AttrNumber *grpColIdx,
Plan *lefttree)
{
List *sub_tlist = lefttree->targetlist;
ListCell *l;
int numsortkeys;
AttrNumber *sortColIdx;
Oid *sortOperators;
Oid *collations;
bool *nullsFirst;
/* Convert list-ish representation to arrays wanted by executor */
numsortkeys = list_length(groupcls);
sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
numsortkeys = 0;
foreach(l, groupcls)
{
SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
if (!tle)
elog(ERROR, "could not retrieve tle for sort-from-groupcols");
sortColIdx[numsortkeys] = tle->resno;
sortOperators[numsortkeys] = grpcl->sortop;
collations[numsortkeys] = exprCollation((Node *) tle->expr);
nullsFirst[numsortkeys] = grpcl->nulls_first;
numsortkeys++;
}
return make_sort(lefttree, numsortkeys,
sortColIdx, sortOperators,
collations, nullsFirst);
}
static Material *
make_material(Plan *lefttree)
{
Material *node = makeNode(Material);
Plan *plan = &node->plan;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
return node;
}
/*
* materialize_finished_plan: stick a Material node atop a completed plan
*
* There are a couple of places where we want to attach a Material node
* after completion of create_plan(), without any MaterialPath path.
* Those places should probably be refactored someday to do this on the
* Path representation, but it's not worth the trouble yet.
*/
Plan *
materialize_finished_plan(Plan *subplan)
{
Plan *matplan;
Path matpath; /* dummy for result of cost_material */
matplan = (Plan *) make_material(subplan);
/*
* XXX horrid kluge: if there are any initPlans attached to the subplan,
* move them up to the Material node, which is now effectively the top
* plan node in its query level. This prevents failure in
* SS_finalize_plan(), which see for comments. We don't bother adjusting
* the subplan's cost estimate for this.
*/
matplan->initPlan = subplan->initPlan;
subplan->initPlan = NIL;
/* Set cost data */
cost_material(&matpath,
subplan->startup_cost,
subplan->total_cost,
subplan->plan_rows,
subplan->plan_width);
matplan->startup_cost = matpath.startup_cost;
matplan->total_cost = matpath.total_cost;
matplan->plan_rows = subplan->plan_rows;
matplan->plan_width = subplan->plan_width;
matplan->parallel_aware = false;
matplan->parallel_safe = subplan->parallel_safe;
return matplan;
}
Agg *
make_agg(List *tlist, List *qual,
AggStrategy aggstrategy, AggSplit aggsplit,
int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
List *groupingSets, List *chain,
double dNumGroups, Plan *lefttree)
{
Agg *node = makeNode(Agg);
Plan *plan = &node->plan;
long numGroups;
/* Reduce to long, but 'ware overflow! */
numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
node->aggstrategy = aggstrategy;
node->aggsplit = aggsplit;
node->numCols = numGroupCols;
node->grpColIdx = grpColIdx;
node->grpOperators = grpOperators;
node->numGroups = numGroups;
node->aggParams = NULL; /* SS_finalize_plan() will fill this */
node->groupingSets = groupingSets;
node->chain = chain;
plan->qual = qual;
plan->targetlist = tlist;
plan->lefttree = lefttree;
plan->righttree = NULL;
return node;
}
static WindowAgg *
make_windowagg(List *tlist, Index winref,
int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
int frameOptions, Node *startOffset, Node *endOffset,
Plan *lefttree)
{
WindowAgg *node = makeNode(WindowAgg);
Plan *plan = &node->plan;
node->winref = winref;
node->partNumCols = partNumCols;
node->partColIdx = partColIdx;
node->partOperators = partOperators;
node->ordNumCols = ordNumCols;
node->ordColIdx = ordColIdx;
node->ordOperators = ordOperators;
node->frameOptions = frameOptions;
node->startOffset = startOffset;
node->endOffset = endOffset;
plan->targetlist = tlist;
plan->lefttree = lefttree;
plan->righttree = NULL;
/* WindowAgg nodes never have a qual clause */
plan->qual = NIL;
return node;
}
static Group *
make_group(List *tlist,
List *qual,
int numGroupCols,
AttrNumber *grpColIdx,
Oid *grpOperators,
Plan *lefttree)
{
Group *node = makeNode(Group);
Plan *plan = &node->plan;
node->numCols = numGroupCols;
node->grpColIdx = grpColIdx;
node->grpOperators = grpOperators;
plan->qual = qual;
plan->targetlist = tlist;
plan->lefttree = lefttree;
plan->righttree = NULL;
return node;
}
/*
* distinctList is a list of SortGroupClauses, identifying the targetlist items
* that should be considered by the Unique filter. The input path must
* already be sorted accordingly.
*/
static Unique *
make_unique_from_sortclauses(Plan *lefttree, List *distinctList)
{
Unique *node = makeNode(Unique);
Plan *plan = &node->plan;
int numCols = list_length(distinctList);
int keyno = 0;
AttrNumber *uniqColIdx;
Oid *uniqOperators;
ListCell *slitem;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
/*
* convert SortGroupClause list into arrays of attr indexes and equality
* operators, as wanted by executor
*/
Assert(numCols > 0);
uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
foreach(slitem, distinctList)
{
SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
uniqColIdx[keyno] = tle->resno;
uniqOperators[keyno] = sortcl->eqop;
Assert(OidIsValid(uniqOperators[keyno]));
keyno++;
}
node->numCols = numCols;
node->uniqColIdx = uniqColIdx;
node->uniqOperators = uniqOperators;
return node;
}
/*
* as above, but use pathkeys to identify the sort columns and semantics
*/
static Unique *
make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols)
{
Unique *node = makeNode(Unique);
Plan *plan = &node->plan;
int keyno = 0;
AttrNumber *uniqColIdx;
Oid *uniqOperators;
ListCell *lc;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
/*
* Convert pathkeys list into arrays of attr indexes and equality
* operators, as wanted by executor. This has a lot in common with
* prepare_sort_from_pathkeys ... maybe unify sometime?
*/
Assert(numCols >= 0 && numCols <= list_length(pathkeys));
uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
foreach(lc, pathkeys)
{
PathKey *pathkey = (PathKey *) lfirst(lc);
EquivalenceClass *ec = pathkey->pk_eclass;
EquivalenceMember *em;
TargetEntry *tle = NULL;
Oid pk_datatype = InvalidOid;
Oid eqop;
ListCell *j;
/* Ignore pathkeys beyond the specified number of columns */
if (keyno >= numCols)
break;
if (ec->ec_has_volatile)
{
/*
* If the pathkey's EquivalenceClass is volatile, then it must
* have come from an ORDER BY clause, and we have to match it to
* that same targetlist entry.
*/
if (ec->ec_sortref == 0) /* can't happen */
elog(ERROR, "volatile EquivalenceClass has no sortref");
tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
Assert(tle);
Assert(list_length(ec->ec_members) == 1);
pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
}
else
{
/*
* Otherwise, we can use any non-constant expression listed in the
* pathkey's EquivalenceClass. For now, we take the first tlist
* item found in the EC.
*/
foreach(j, plan->targetlist)
{
tle = (TargetEntry *) lfirst(j);
em = find_ec_member_for_tle(ec, tle, NULL);
if (em)
{
/* found expr already in tlist */
pk_datatype = em->em_datatype;
break;
}
tle = NULL;
}
}
if (!tle)
elog(ERROR, "could not find pathkey item to sort");
/*
* Look up the correct equality operator from the PathKey's slightly
* abstracted representation.
*/
eqop = get_opfamily_member(pathkey->pk_opfamily,
pk_datatype,
pk_datatype,
BTEqualStrategyNumber);
if (!OidIsValid(eqop)) /* should not happen */
elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
BTEqualStrategyNumber, pk_datatype, pk_datatype,
pathkey->pk_opfamily);
uniqColIdx[keyno] = tle->resno;
uniqOperators[keyno] = eqop;
keyno++;
}
node->numCols = numCols;
node->uniqColIdx = uniqColIdx;
node->uniqOperators = uniqOperators;
return node;
}
static Gather *
make_gather(List *qptlist,
List *qpqual,
int nworkers,
bool single_copy,
Plan *subplan)
{
Gather *node = makeNode(Gather);
Plan *plan = &node->plan;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = subplan;
plan->righttree = NULL;
node->num_workers = nworkers;
node->single_copy = single_copy;
node->invisible = false;
return node;
}
/*
* distinctList is a list of SortGroupClauses, identifying the targetlist
* items that should be considered by the SetOp filter. The input path must
* already be sorted accordingly.
*/
static SetOp *
make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
List *distinctList, AttrNumber flagColIdx, int firstFlag,
long numGroups)
{
SetOp *node = makeNode(SetOp);
Plan *plan = &node->plan;
int numCols = list_length(distinctList);
int keyno = 0;
AttrNumber *dupColIdx;
Oid *dupOperators;
ListCell *slitem;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
/*
* convert SortGroupClause list into arrays of attr indexes and equality
* operators, as wanted by executor
*/
Assert(numCols > 0);
dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
foreach(slitem, distinctList)
{
SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
dupColIdx[keyno] = tle->resno;
dupOperators[keyno] = sortcl->eqop;
Assert(OidIsValid(dupOperators[keyno]));
keyno++;
}
node->cmd = cmd;
node->strategy = strategy;
node->numCols = numCols;
node->dupColIdx = dupColIdx;
node->dupOperators = dupOperators;
node->flagColIdx = flagColIdx;
node->firstFlag = firstFlag;
node->numGroups = numGroups;
return node;
}
/*
* make_lockrows
* Build a LockRows plan node
*/
static LockRows *
make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
{
LockRows *node = makeNode(LockRows);
Plan *plan = &node->plan;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->rowMarks = rowMarks;
node->epqParam = epqParam;
return node;
}
/*
* make_limit
* Build a Limit plan node
*/
Limit *
make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount)
{
Limit *node = makeNode(Limit);
Plan *plan = &node->plan;
plan->targetlist = lefttree->targetlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->limitOffset = limitOffset;
node->limitCount = limitCount;
return node;
}
/*
* make_result
* Build a Result plan node
*/
static Result *
make_result(List *tlist,
Node *resconstantqual,
Plan *subplan)
{
Result *node = makeNode(Result);
Plan *plan = &node->plan;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = subplan;
plan->righttree = NULL;
node->resconstantqual = resconstantqual;
return node;
}
/*
* make_project_set
* Build a ProjectSet plan node
*/
static ProjectSet *
make_project_set(List *tlist,
Plan *subplan)
{
ProjectSet *node = makeNode(ProjectSet);
Plan *plan = &node->plan;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = subplan;
plan->righttree = NULL;
return node;
}
/*
* make_modifytable
* Build a ModifyTable plan node
*/
static ModifyTable *
make_modifytable(PlannerInfo *root,
CmdType operation, bool canSetTag,
Index nominalRelation, List *partitioned_rels,
List *resultRelations, List *subplans,
List *withCheckOptionLists, List *returningLists,
List *rowMarks, OnConflictExpr *onconflict, int epqParam)
{
ModifyTable *node = makeNode(ModifyTable);
List *fdw_private_list;
Bitmapset *direct_modify_plans;
ListCell *lc;
int i;
Assert(list_length(resultRelations) == list_length(subplans));
Assert(withCheckOptionLists == NIL ||
list_length(resultRelations) == list_length(withCheckOptionLists));
Assert(returningLists == NIL ||
list_length(resultRelations) == list_length(returningLists));
node->plan.lefttree = NULL;
node->plan.righttree = NULL;
node->plan.qual = NIL;
/* setrefs.c will fill in the targetlist, if needed */
node->plan.targetlist = NIL;
node->operation = operation;
node->canSetTag = canSetTag;
node->nominalRelation = nominalRelation;
node->partitioned_rels = partitioned_rels;
node->resultRelations = resultRelations;
node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
node->rootResultRelIndex = -1; /* will be set correctly in setrefs.c */
node->plans = subplans;
if (!onconflict)
{
node->onConflictAction = ONCONFLICT_NONE;
node->onConflictSet = NIL;
node->onConflictWhere = NULL;
node->arbiterIndexes = NIL;
node->exclRelRTI = 0;
node->exclRelTlist = NIL;
}
else
{
node->onConflictAction = onconflict->action;
node->onConflictSet = onconflict->onConflictSet;
node->onConflictWhere = onconflict->onConflictWhere;
/*
* If a set of unique index inference elements was provided (an
* INSERT...ON CONFLICT "inference specification"), then infer
* appropriate unique indexes (or throw an error if none are
* available).
*/
node->arbiterIndexes = infer_arbiter_indexes(root);
node->exclRelRTI = onconflict->exclRelIndex;
node->exclRelTlist = onconflict->exclRelTlist;
}
node->withCheckOptionLists = withCheckOptionLists;
node->returningLists = returningLists;
node->rowMarks = rowMarks;
node->epqParam = epqParam;
/*
* For each result relation that is a foreign table, allow the FDW to
* construct private plan data, and accumulate it all into a list.
*/
fdw_private_list = NIL;
direct_modify_plans = NULL;
i = 0;
foreach(lc, resultRelations)
{
Index rti = lfirst_int(lc);
FdwRoutine *fdwroutine;
List *fdw_private;
bool direct_modify;
/*
* If possible, we want to get the FdwRoutine from our RelOptInfo for
* the table. But sometimes we don't have a RelOptInfo and must get
* it the hard way. (In INSERT, the target relation is not scanned,
* so it's not a baserel; and there are also corner cases for
* updatable views where the target rel isn't a baserel.)
*/
if (rti < root->simple_rel_array_size &&
root->simple_rel_array[rti] != NULL)
{
RelOptInfo *resultRel = root->simple_rel_array[rti];
fdwroutine = resultRel->fdwroutine;
}
else
{
RangeTblEntry *rte = planner_rt_fetch(rti, root);
Assert(rte->rtekind == RTE_RELATION);
if (rte->relkind == RELKIND_FOREIGN_TABLE)
fdwroutine = GetFdwRoutineByRelId(rte->relid);
else
fdwroutine = NULL;
}
/*
* If the target foreign table has any row-level triggers, we can't
* modify the foreign table directly.
*/
direct_modify = false;
if (fdwroutine != NULL &&
fdwroutine->PlanDirectModify != NULL &&
fdwroutine->BeginDirectModify != NULL &&
fdwroutine->IterateDirectModify != NULL &&
fdwroutine->EndDirectModify != NULL &&
!has_row_triggers(root, rti, operation))
direct_modify = fdwroutine->PlanDirectModify(root, node, rti, i);
if (direct_modify)
direct_modify_plans = bms_add_member(direct_modify_plans, i);
if (!direct_modify &&
fdwroutine != NULL &&
fdwroutine->PlanForeignModify != NULL)
fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
else
fdw_private = NIL;
fdw_private_list = lappend(fdw_private_list, fdw_private);
i++;
}
node->fdwPrivLists = fdw_private_list;
node->fdwDirectModifyPlans = direct_modify_plans;
return node;
}
/*
* is_projection_capable_path
* Check whether a given Path node is able to do projection.
*/
bool
is_projection_capable_path(Path *path)
{
/* Most plan types can project, so just list the ones that can't */
switch (path->pathtype)
{
case T_Hash:
case T_Material:
case T_Sort:
case T_Unique:
case T_SetOp:
case T_LockRows:
case T_Limit:
case T_ModifyTable:
case T_MergeAppend:
case T_RecursiveUnion:
return false;
case T_Append:
/*
* Append can't project, but if it's being used to represent a
* dummy path, claim that it can project. This prevents us from
* converting a rel from dummy to non-dummy status by applying a
* projection to its dummy path.
*/
return IS_DUMMY_PATH(path);
case T_ProjectSet:
/*
* Although ProjectSet certainly projects, say "no" because we
* don't want the planner to randomly replace its tlist with
* something else; the SRFs have to stay at top level. This might
* get relaxed later.
*/
return false;
default:
break;
}
return true;
}
/*
* is_projection_capable_plan
* Check whether a given Plan node is able to do projection.
*/
bool
is_projection_capable_plan(Plan *plan)
{
/* Most plan types can project, so just list the ones that can't */
switch (nodeTag(plan))
{
case T_Hash:
case T_Material:
case T_Sort:
case T_Unique:
case T_SetOp:
case T_LockRows:
case T_Limit:
case T_ModifyTable:
case T_Append:
case T_MergeAppend:
case T_RecursiveUnion:
return false;
case T_ProjectSet:
/*
* Although ProjectSet certainly projects, say "no" because we
* don't want the planner to randomly replace its tlist with
* something else; the SRFs have to stay at top level. This might
* get relaxed later.
*/
return false;
default:
break;
}
return true;
}
|
127831.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_fscanf_add_54a.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-54a.tmpl.c
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: add
* GoodSink: Ensure there will not be an overflow before adding 1 to data
* BadSink : Add 1 to data, which can cause an overflow
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include <inttypes.h>
#include "std_testcase.h"
#ifndef OMITBAD
/* bad function declaration */
void CWE190_Integer_Overflow__int64_t_fscanf_add_54b_badSink(int64_t data);
void CWE190_Integer_Overflow__int64_t_fscanf_add_54_bad()
{
int64_t data;
data = 0LL;
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
CWE190_Integer_Overflow__int64_t_fscanf_add_54b_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE190_Integer_Overflow__int64_t_fscanf_add_54b_goodG2BSink(int64_t data);
static void goodG2B()
{
int64_t data;
data = 0LL;
/* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
data = 2;
CWE190_Integer_Overflow__int64_t_fscanf_add_54b_goodG2BSink(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE190_Integer_Overflow__int64_t_fscanf_add_54b_goodB2GSink(int64_t data);
static void goodB2G()
{
int64_t data;
data = 0LL;
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
CWE190_Integer_Overflow__int64_t_fscanf_add_54b_goodB2GSink(data);
}
void CWE190_Integer_Overflow__int64_t_fscanf_add_54_good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE190_Integer_Overflow__int64_t_fscanf_add_54_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE190_Integer_Overflow__int64_t_fscanf_add_54_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
706809.c | /*
* Copyright (c) 2016 Cisco and/or its affiliates.
* 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 <vnet/fib/ip6_fib.h>
#include <vnet/fib/ip4_fib.h>
#include <vnet/fib/mpls_fib.h>
#include <vnet/adj/adj.h>
#include <vnet/dpo/load_balance.h>
#include <vnet/dpo/load_balance_map.h>
#include <vnet/dpo/mpls_label_dpo.h>
#include <vnet/dpo/lookup_dpo.h>
#include <vnet/dpo/drop_dpo.h>
#include <vnet/dpo/receive_dpo.h>
#include <vnet/dpo/ip_null_dpo.h>
#include <vnet/mpls/mpls.h>
#include <vnet/fib/fib_path_list.h>
#include <vnet/fib/fib_entry_src.h>
#include <vnet/fib/fib_walk.h>
#include <vnet/fib/fib_node_list.h>
#include <vnet/fib/fib_urpf_list.h>
#define FIB_TEST_I(_cond, _comment, _args...) \
({ \
int _evald = (_cond); \
if (!(_evald)) { \
fformat(stderr, "FAIL:%d: " _comment "\n", \
__LINE__, ##_args); \
} else { \
fformat(stderr, "PASS:%d: " _comment "\n", \
__LINE__, ##_args); \
} \
_evald; \
})
#define FIB_TEST(_cond, _comment, _args...) \
{ \
if (!FIB_TEST_I(_cond, _comment, ##_args)) { \
return 1; \
ASSERT(!("FAIL: " _comment)); \
} \
}
/**
* A 'i'm not fussed is this is not efficient' store of test data
*/
typedef struct test_main_t_ {
/**
* HW if indicies
*/
u32 hw_if_indicies[4];
/**
* HW interfaces
*/
vnet_hw_interface_t * hw[4];
} test_main_t;
static test_main_t test_main;
/* fake ethernet device class, distinct from "fake-ethX" */
static u8 * format_test_interface_name (u8 * s, va_list * args)
{
u32 dev_instance = va_arg (*args, u32);
return format (s, "test-eth%d", dev_instance);
}
static uword dummy_interface_tx (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
clib_warning ("you shouldn't be here, leaking buffers...");
return frame->n_vectors;
}
static clib_error_t *
test_interface_admin_up_down (vnet_main_t * vnm,
u32 hw_if_index,
u32 flags)
{
u32 hw_flags = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) ?
VNET_HW_INTERFACE_FLAG_LINK_UP : 0;
vnet_hw_interface_set_flags (vnm, hw_if_index, hw_flags);
return 0;
}
VNET_DEVICE_CLASS (test_interface_device_class,static) = {
.name = "Test interface",
.format_device_name = format_test_interface_name,
.tx_function = dummy_interface_tx,
.admin_up_down_function = test_interface_admin_up_down,
};
static u8 *hw_address;
static int
fib_test_mk_intf (u32 ninterfaces)
{
clib_error_t * error = NULL;
test_main_t *tm = &test_main;
u8 byte;
u32 i;
ASSERT(ninterfaces <= ARRAY_LEN(tm->hw_if_indicies));
for (i=0; i<6; i++)
{
byte = 0xd0+i;
vec_add1(hw_address, byte);
}
for (i = 0; i < ninterfaces; i++)
{
hw_address[5] = i;
error = ethernet_register_interface(vnet_get_main(),
test_interface_device_class.index,
i /* instance */,
hw_address,
&tm->hw_if_indicies[i],
/* flag change */ 0);
FIB_TEST((NULL == error), "ADD interface %d", i);
error = vnet_hw_interface_set_flags(vnet_get_main(),
tm->hw_if_indicies[i],
VNET_HW_INTERFACE_FLAG_LINK_UP);
tm->hw[i] = vnet_get_hw_interface(vnet_get_main(),
tm->hw_if_indicies[i]);
vec_validate (ip4_main.fib_index_by_sw_if_index,
tm->hw[i]->sw_if_index);
vec_validate (ip6_main.fib_index_by_sw_if_index,
tm->hw[i]->sw_if_index);
ip4_main.fib_index_by_sw_if_index[tm->hw[i]->sw_if_index] = 0;
ip6_main.fib_index_by_sw_if_index[tm->hw[i]->sw_if_index] = 0;
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[i]->sw_if_index,
VNET_SW_INTERFACE_FLAG_ADMIN_UP);
FIB_TEST((NULL == error), "UP interface %d", i);
}
/*
* re-eval after the inevitable realloc
*/
for (i = 0; i < ninterfaces; i++)
{
tm->hw[i] = vnet_get_hw_interface(vnet_get_main(),
tm->hw_if_indicies[i]);
}
return (0);
}
#define FIB_TEST_REC_FORW(_rec_prefix, _via_prefix, _bucket) \
{ \
const dpo_id_t *_rec_dpo = fib_entry_contribute_ip_forwarding( \
fib_table_lookup_exact_match(fib_index, (_rec_prefix))); \
const dpo_id_t *_via_dpo = fib_entry_contribute_ip_forwarding( \
fib_table_lookup(fib_index, (_via_prefix))); \
FIB_TEST(!dpo_cmp(_via_dpo, \
load_balance_get_bucket(_rec_dpo->dpoi_index, \
_bucket)), \
"%U is recursive via %U", \
format_fib_prefix, (_rec_prefix), \
format_fib_prefix, _via_prefix); \
}
#define FIB_TEST_LB_BUCKET_VIA_ADJ(_prefix, _bucket, _ai) \
{ \
const dpo_id_t *_dpo = fib_entry_contribute_ip_forwarding( \
fib_table_lookup_exact_match(fib_index, (_prefix))); \
const dpo_id_t *_dpo1 = \
load_balance_get_bucket(_dpo->dpoi_index, _bucket); \
FIB_TEST(DPO_ADJACENCY == _dpo1->dpoi_type, "type is %U", \
format_dpo_type, _dpo1->dpoi_type); \
FIB_TEST((_ai == _dpo1->dpoi_index), \
"%U bucket %d resolves via %U", \
format_fib_prefix, (_prefix), \
_bucket, \
format_dpo_id, _dpo1, 0); \
}
#define FIB_TEST_RPF(_cond, _comment, _args...) \
{ \
if (!FIB_TEST_I(_cond, _comment, ##_args)) { \
return (0); \
} \
}
static int
fib_test_urpf_is_equal (fib_node_index_t fei,
fib_forward_chain_type_t fct,
u32 num, ...)
{
dpo_id_t dpo = DPO_INVALID;
fib_urpf_list_t *urpf;
index_t ui;
va_list ap;
int ii;
va_start(ap, num);
fib_entry_contribute_forwarding(fei, fct, &dpo);
ui = load_balance_get_urpf(dpo.dpoi_index);
urpf = fib_urpf_list_get(ui);
FIB_TEST_RPF(num == vec_len(urpf->furpf_itfs),
"RPF:%U len %d == %d",
format_fib_urpf_list, ui,
num, vec_len(urpf->furpf_itfs));
FIB_TEST_RPF(num == fib_urpf_check_size(ui),
"RPF:%U check-size %d == %d",
format_fib_urpf_list, ui,
num, vec_len(urpf->furpf_itfs));
for (ii = 0; ii < num; ii++)
{
adj_index_t ai = va_arg(ap, adj_index_t);
FIB_TEST_RPF(ai == urpf->furpf_itfs[ii],
"RPF:%d item:%d - %d == %d",
ui, ii, ai, urpf->furpf_itfs[ii]);
FIB_TEST_RPF(fib_urpf_check(ui, ai),
"RPF:%d %d found",
ui, ai);
}
dpo_reset(&dpo);
va_end(ap);
return (1);
}
static u8*
fib_test_build_rewrite (u8 *eth_addr)
{
u8* rewrite = NULL;
vec_validate(rewrite, 13);
memcpy(rewrite, eth_addr, 6);
memcpy(rewrite+6, eth_addr, 6);
return (rewrite);
}
typedef enum fib_test_lb_bucket_type_t_ {
FT_LB_LABEL_O_ADJ,
FT_LB_LABEL_STACK_O_ADJ,
FT_LB_LABEL_O_LB,
FT_LB_O_LB,
FT_LB_SPECIAL,
FT_LB_ADJ,
} fib_test_lb_bucket_type_t;
typedef struct fib_test_lb_bucket_t_ {
fib_test_lb_bucket_type_t type;
union
{
struct
{
mpls_eos_bit_t eos;
mpls_label_t label;
u8 ttl;
adj_index_t adj;
} label_o_adj;
struct
{
mpls_eos_bit_t eos;
mpls_label_t label_stack[8];
u8 label_stack_size;
u8 ttl;
adj_index_t adj;
} label_stack_o_adj;
struct
{
mpls_eos_bit_t eos;
mpls_label_t label;
u8 ttl;
index_t lb;
} label_o_lb;
struct
{
index_t adj;
} adj;
struct
{
index_t lb;
} lb;
struct
{
index_t adj;
} special;
};
} fib_test_lb_bucket_t;
#define FIB_TEST_LB(_cond, _comment, _args...) \
{ \
if (!FIB_TEST_I(_cond, _comment, ##_args)) { \
return (0); \
} \
}
static int
fib_test_validate_lb_v (const load_balance_t *lb,
u16 n_buckets,
va_list ap)
{
const dpo_id_t *dpo;
int bucket;
FIB_TEST_LB((n_buckets == lb->lb_n_buckets), "n_buckets = %d", lb->lb_n_buckets);
for (bucket = 0; bucket < n_buckets; bucket++)
{
const fib_test_lb_bucket_t *exp;
exp = va_arg(ap, fib_test_lb_bucket_t*);
dpo = load_balance_get_bucket_i(lb, bucket);
switch (exp->type)
{
case FT_LB_LABEL_STACK_O_ADJ:
{
const mpls_label_dpo_t *mld;
mpls_label_t hdr;
u32 ii;
FIB_TEST_LB((DPO_MPLS_LABEL == dpo->dpoi_type),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
mld = mpls_label_dpo_get(dpo->dpoi_index);
FIB_TEST_LB(exp->label_stack_o_adj.label_stack_size == mld->mld_n_labels,
"label stack size",
mld->mld_n_labels);
for (ii = 0; ii < mld->mld_n_labels; ii++)
{
hdr = clib_net_to_host_u32(mld->mld_hdr[ii].label_exp_s_ttl);
FIB_TEST_LB((vnet_mpls_uc_get_label(hdr) ==
exp->label_stack_o_adj.label_stack[ii]),
"bucket %d stacks on label %d",
bucket,
exp->label_stack_o_adj.label_stack[ii]);
if (ii == mld->mld_n_labels-1)
{
FIB_TEST_LB((vnet_mpls_uc_get_s(hdr) ==
exp->label_o_adj.eos),
"bucket %d stacks on label %d %U!=%U",
bucket,
exp->label_stack_o_adj.label_stack[ii],
format_mpls_eos_bit, exp->label_o_adj.eos,
format_mpls_eos_bit, vnet_mpls_uc_get_s(hdr));
}
else
{
FIB_TEST_LB((vnet_mpls_uc_get_s(hdr) == MPLS_NON_EOS),
"bucket %d stacks on label %d %U",
bucket,
exp->label_stack_o_adj.label_stack[ii],
format_mpls_eos_bit, vnet_mpls_uc_get_s(hdr));
}
}
FIB_TEST_LB((DPO_ADJACENCY_INCOMPLETE == mld->mld_dpo.dpoi_type),
"bucket %d label stacks on %U",
bucket,
format_dpo_type, mld->mld_dpo.dpoi_type);
FIB_TEST_LB((exp->label_stack_o_adj.adj == mld->mld_dpo.dpoi_index),
"bucket %d label stacks on adj %d",
bucket,
exp->label_stack_o_adj.adj);
}
break;
case FT_LB_LABEL_O_ADJ:
{
const mpls_label_dpo_t *mld;
mpls_label_t hdr;
FIB_TEST_LB((DPO_MPLS_LABEL == dpo->dpoi_type),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
mld = mpls_label_dpo_get(dpo->dpoi_index);
hdr = clib_net_to_host_u32(mld->mld_hdr[0].label_exp_s_ttl);
FIB_TEST_LB((vnet_mpls_uc_get_label(hdr) ==
exp->label_o_adj.label),
"bucket %d stacks on label %d",
bucket,
exp->label_o_adj.label);
FIB_TEST_LB((vnet_mpls_uc_get_s(hdr) ==
exp->label_o_adj.eos),
"bucket %d stacks on label %d %U",
bucket,
exp->label_o_adj.label,
format_mpls_eos_bit, exp->label_o_adj.eos);
FIB_TEST_LB((DPO_ADJACENCY_INCOMPLETE == mld->mld_dpo.dpoi_type),
"bucket %d label stacks on %U",
bucket,
format_dpo_type, mld->mld_dpo.dpoi_type);
FIB_TEST_LB((exp->label_o_adj.adj == mld->mld_dpo.dpoi_index),
"bucket %d label stacks on adj %d",
bucket,
exp->label_o_adj.adj);
}
break;
case FT_LB_LABEL_O_LB:
{
const mpls_label_dpo_t *mld;
mpls_label_t hdr;
FIB_TEST_LB((DPO_MPLS_LABEL == dpo->dpoi_type),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
mld = mpls_label_dpo_get(dpo->dpoi_index);
hdr = clib_net_to_host_u32(mld->mld_hdr[0].label_exp_s_ttl);
FIB_TEST_LB(1 == mld->mld_n_labels, "label stack size",
mld->mld_n_labels);
FIB_TEST_LB((vnet_mpls_uc_get_label(hdr) ==
exp->label_o_lb.label),
"bucket %d stacks on label %d",
bucket,
exp->label_o_lb.label);
FIB_TEST_LB((vnet_mpls_uc_get_s(hdr) ==
exp->label_o_lb.eos),
"bucket %d stacks on label %d %U",
bucket,
exp->label_o_lb.label,
format_mpls_eos_bit, exp->label_o_lb.eos);
FIB_TEST_LB((DPO_LOAD_BALANCE == mld->mld_dpo.dpoi_type),
"bucket %d label stacks on %U",
bucket,
format_dpo_type, mld->mld_dpo.dpoi_type);
FIB_TEST_LB((exp->label_o_lb.lb == mld->mld_dpo.dpoi_index),
"bucket %d label stacks on LB %d",
bucket,
exp->label_o_lb.lb);
}
break;
case FT_LB_ADJ:
FIB_TEST_I(((DPO_ADJACENCY == dpo->dpoi_type) ||
(DPO_ADJACENCY_INCOMPLETE == dpo->dpoi_type)),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
FIB_TEST_LB((exp->adj.adj == dpo->dpoi_index),
"bucket %d stacks on adj %d",
bucket,
exp->adj.adj);
break;
case FT_LB_O_LB:
FIB_TEST_I((DPO_LOAD_BALANCE == dpo->dpoi_type),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
FIB_TEST_LB((exp->lb.lb == dpo->dpoi_index),
"bucket %d stacks on lb %d",
bucket,
exp->lb.lb);
break;
case FT_LB_SPECIAL:
FIB_TEST_I((DPO_DROP == dpo->dpoi_type),
"bucket %d stacks on %U",
bucket,
format_dpo_type, dpo->dpoi_type);
FIB_TEST_LB((exp->special.adj == dpo->dpoi_index),
"bucket %d stacks on drop %d",
bucket,
exp->special.adj);
break;
}
}
return (!0);
}
static int
fib_test_validate_entry (fib_node_index_t fei,
fib_forward_chain_type_t fct,
u16 n_buckets,
...)
{
dpo_id_t dpo = DPO_INVALID;
const load_balance_t *lb;
fib_prefix_t pfx;
index_t fw_lbi;
u32 fib_index;
va_list ap;
int res;
va_start(ap, n_buckets);
fib_entry_get_prefix(fei, &pfx);
fib_index = fib_entry_get_fib_index(fei);
fib_entry_contribute_forwarding(fei, fct, &dpo);
FIB_TEST_LB((DPO_LOAD_BALANCE == dpo.dpoi_type),
"Entry links to %U",
format_dpo_type, dpo.dpoi_type);
lb = load_balance_get(dpo.dpoi_index);
res = fib_test_validate_lb_v(lb, n_buckets, ap);
/*
* ensure that the LB contributed by the entry is the
* same as the LB in the forwarding tables
*/
if (fct == fib_entry_get_default_chain_type(fib_entry_get(fei)))
{
switch (pfx.fp_proto)
{
case FIB_PROTOCOL_IP4:
fw_lbi = ip4_fib_forwarding_lookup(fib_index, &pfx.fp_addr.ip4);
break;
case FIB_PROTOCOL_IP6:
fw_lbi = ip6_fib_table_fwding_lookup(&ip6_main, fib_index, &pfx.fp_addr.ip6);
break;
case FIB_PROTOCOL_MPLS:
{
mpls_unicast_header_t hdr = {
.label_exp_s_ttl = 0,
};
vnet_mpls_uc_set_label(&hdr.label_exp_s_ttl, pfx.fp_label);
vnet_mpls_uc_set_s(&hdr.label_exp_s_ttl, pfx.fp_eos);
hdr.label_exp_s_ttl = clib_host_to_net_u32(hdr.label_exp_s_ttl);
fw_lbi = mpls_fib_table_forwarding_lookup(fib_index, &hdr);
break;
}
default:
fw_lbi = 0;
}
FIB_TEST_LB((fw_lbi == dpo.dpoi_index),
"Contributed LB = FW LB: %U\n %U",
format_load_balance, fw_lbi, 0,
format_load_balance, dpo.dpoi_index, 0);
}
dpo_reset(&dpo);
va_end(ap);
return (res);
}
static int
fib_test_v4 (void)
{
/*
* In the default table check for the presence and correct forwarding
* of the special entries
*/
fib_node_index_t dfrt, fei, ai, ai2, locked_ai, ai_01, ai_02, ai_03;
const dpo_id_t *dpo, *dpo1, *dpo2, *dpo_drop;
const ip_adjacency_t *adj;
const load_balance_t *lb;
test_main_t *tm;
u32 fib_index;
int ii;
/* via 10.10.10.1 */
ip46_address_t nh_10_10_10_1 = {
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a01),
};
/* via 10.10.10.2 */
ip46_address_t nh_10_10_10_2 = {
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a02),
};
tm = &test_main;
/* Find or create FIB table 11 */
fib_index = fib_table_find_or_create_and_lock(FIB_PROTOCOL_IP4, 11);
for (ii = 0; ii < 4; ii++)
{
ip4_main.fib_index_by_sw_if_index[tm->hw[ii]->sw_if_index] = fib_index;
}
fib_prefix_t pfx_0_0_0_0_s_0 = {
.fp_len = 0,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
{0}
},
},
};
fib_prefix_t pfx = {
.fp_len = 0,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
{0}
},
},
};
dpo_drop = drop_dpo_get(DPO_PROTO_IP4);
dfrt = fib_table_lookup(fib_index, &pfx_0_0_0_0_s_0);
FIB_TEST((FIB_NODE_INDEX_INVALID != dfrt), "default route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(dfrt)),
"Default route is DROP");
pfx.fp_len = 32;
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "all zeros route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"all 0s route is DROP");
pfx.fp_addr.ip4.as_u32 = clib_host_to_net_u32(0xffffffff);
pfx.fp_len = 32;
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "all ones route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"all 1s route is DROP");
pfx.fp_addr.ip4.as_u32 = clib_host_to_net_u32(0xe0000000);
pfx.fp_len = 8;
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "all-mcast route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"all-mcast route is DROP");
pfx.fp_addr.ip4.as_u32 = clib_host_to_net_u32(0xf0000000);
pfx.fp_len = 8;
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "class-e route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"class-e route is DROP");
/*
* at this stage there are 5 entries in the test FIB (plus 5 in the default),
* all of which are special sourced and so none of which share path-lists.
* There are also 6 entries, and 6 non-shared path-lists, in the v6 default
* table
*/
#define NBR (5+5+6)
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* add interface routes.
* validate presence of /24 attached and /32 recieve.
* test for the presence of the receive address in the glean and local adj
*/
fib_prefix_t local_pfx = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
.as_u32 = clib_host_to_net_u32(0x0a0a0a0a),
},
},
};
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1, // weight
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached interface route present");
FIB_TEST(((FIB_ENTRY_FLAG_ATTACHED | FIB_ENTRY_FLAG_CONNECTED) ==
fib_entry_get_flags(fei)),
"Flags set on attached interface");
ai = fib_entry_get_adj(fei);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai), "attached interface route adj present");
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_GLEAN == adj->lookup_next_index),
"attached interface adj is glean");
FIB_TEST((0 == ip46_address_cmp(&local_pfx.fp_addr,
&adj->sub_type.glean.receive_addr)),
"attached interface adj is receive ok");
local_pfx.fp_len = 32;
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1, // weight
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &local_pfx);
FIB_TEST(((FIB_ENTRY_FLAG_LOCAL | FIB_ENTRY_FLAG_CONNECTED) ==
fib_entry_get_flags(fei)),
"Flags set on local interface");
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local interface route present");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 0),
"RPF list for local length 0");
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST((DPO_RECEIVE == dpo->dpoi_type),
"local interface adj is local");
receive_dpo_t *rd = receive_dpo_get(dpo->dpoi_index);
FIB_TEST((0 == ip46_address_cmp(&local_pfx.fp_addr,
&rd->rd_addr)),
"local interface adj is receive ok");
FIB_TEST((2 == fib_table_get_num_entries(fib_index,
FIB_PROTOCOL_IP4,
FIB_SOURCE_INTERFACE)),
"2 Interface Source'd prefixes");
/*
* +2 interface routes +2 non-shared path-lists
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+2 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NBR+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Modify the default route to be via an adj not yet known.
* this sources the defalut route with the API source, which is
* a higher preference to the DEFAULT_ROUTE source
*/
pfx.fp_addr.ip4.as_u32 = 0;
pfx.fp_len = 0;
fib_table_entry_path_add(fib_index, &pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((FIB_ENTRY_FLAG_NONE == fib_entry_get_flags(fei)),
"Flags set on API route");
FIB_TEST((fei == dfrt), "default route same index");
ai = fib_entry_get_adj(fei);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai), "default route adj present");
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&nh_10_10_10_1, &adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
FIB_TEST((1 == fib_table_get_num_entries(fib_index,
FIB_PROTOCOL_IP4,
FIB_SOURCE_API)),
"1 API Source'd prefixes");
/*
* find the adj in the shared db
*/
locked_ai = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index);
FIB_TEST((locked_ai == ai), "ADJ NBR DB find");
adj_unlock(locked_ai);
/*
* +1 shared path-list
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+3 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NBR+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* remove the API source from the default route. We expected
* the route to remain, sourced by DEFAULT_ROUTE, and hence a DROP
*/
pfx.fp_addr.ip4.as_u32 = 0;
pfx.fp_len = 0;
fib_table_entry_path_remove(fib_index, &pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // non-recursive path, so no FIB index
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx);
FIB_TEST((fei == dfrt), "default route same index");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"Default route is DROP");
/*
* -1 shared-path-list
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+2 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NBR+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add an 2 ARP entry => a complete ADJ plus adj-fib.
*/
fib_prefix_t pfx_10_10_10_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.10.10.1 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a01),
},
};
fib_prefix_t pfx_10_10_10_2_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.10.10.2 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a02),
},
};
fib_prefix_t pfx_11_11_11_11_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 11.11.11.11 */
.ip4.as_u32 = clib_host_to_net_u32(0x0b0b0b0b),
},
};
u8 eth_addr[] = {
0xde, 0xde, 0xde, 0xba, 0xba, 0xba,
};
ip46_address_t nh_12_12_12_12 = {
.ip4.as_u32 = clib_host_to_net_u32(0x0c0c0c0c),
};
adj_index_t ai_12_12_12_12;
/*
* Add a route via an incomplete ADJ. then complete the ADJ
* Expect the route LB is updated to use complete adj type.
*/
fei = fib_table_entry_update_one_path(fib_index,
&pfx_11_11_11_11_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo1 = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST(DPO_ADJACENCY_INCOMPLETE == dpo1->dpoi_type,
"11.11.11.11/32 via incomplete adj");
ai_01 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai_01), "adj created");
adj = adj_get(ai_01);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&pfx_10_10_10_1_s_32.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
adj_nbr_update_rewrite(ai_01, ADJ_NBR_REWRITE_FLAG_COMPLETE,
fib_test_build_rewrite(eth_addr));
FIB_TEST((IP_LOOKUP_NEXT_REWRITE == adj->lookup_next_index),
"adj is complete");
FIB_TEST((0 == ip46_address_cmp(&pfx_10_10_10_1_s_32.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "ADJ-FIB resolves via adj");
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo1 = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST(DPO_ADJACENCY == dpo1->dpoi_type,
"11.11.11.11/32 via complete adj");
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 1,
tm->hw[0]->sw_if_index),
"RPF list for adj-fib contains adj");
ai_12_12_12_12 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&nh_12_12_12_12,
tm->hw[1]->sw_if_index);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai_12_12_12_12), "adj created");
adj = adj_get(ai_12_12_12_12);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&nh_12_12_12_12,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
adj_nbr_update_rewrite(ai_12_12_12_12, ADJ_NBR_REWRITE_FLAG_COMPLETE,
fib_test_build_rewrite(eth_addr));
FIB_TEST((IP_LOOKUP_NEXT_REWRITE == adj->lookup_next_index),
"adj is complete");
/*
* add the adj fib
*/
fei = fib_table_entry_update_one_path(fib_index,
&pfx_10_10_10_1_s_32,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((FIB_ENTRY_FLAG_ATTACHED == fib_entry_get_flags(fei)),
"Flags set on adj-fib");
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "ADJ-FIB resolves via adj");
fib_table_entry_path_remove(fib_index,
&pfx_11_11_11_11_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
FIB_ROUTE_PATH_FLAG_NONE);
eth_addr[5] = 0xb2;
ai_02 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&pfx_10_10_10_2_s_32.fp_addr,
tm->hw[0]->sw_if_index);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai_02), "adj created");
adj = adj_get(ai_02);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&pfx_10_10_10_2_s_32.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
adj_nbr_update_rewrite(ai_02, ADJ_NBR_REWRITE_FLAG_COMPLETE,
fib_test_build_rewrite(eth_addr));
FIB_TEST((IP_LOOKUP_NEXT_REWRITE == adj->lookup_next_index),
"adj is complete");
FIB_TEST((0 == ip46_address_cmp(&pfx_10_10_10_2_s_32.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
FIB_TEST((ai_01 != ai_02), "ADJs are different");
fib_table_entry_update_one_path(fib_index,
&pfx_10_10_10_2_s_32,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_2_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_10_10_10_2_s_32);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_02 == ai), "ADJ-FIB resolves via adj");
/*
* +2 adj-fibs, and their non-shared path-lists
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+4 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+4 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add 2 routes via the first ADJ. ensure path-list sharing
*/
fib_prefix_t pfx_1_1_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 1.1.1.1/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x01010101),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.1.1 resolves via 10.10.10.1");
/*
* +1 entry and a shared path-list
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+5 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/* 1.1.2.0/24 */
fib_prefix_t pfx_1_1_2_0_s_24 = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010200),
}
};
fib_table_entry_path_add(fib_index,
&pfx_1_1_2_0_s_24,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_2_0_s_24);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.2.0/24 resolves via 10.10.10.1");
/*
* +1 entry only
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* modify 1.1.2.0/24 to use multipath.
*/
fib_table_entry_path_add(fib_index,
&pfx_1_1_2_0_s_24,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_2_0_s_24);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1, tm->hw[0]->sw_if_index),
"RPF list for 1.1.2.0/24 contains both adjs");
dpo1 = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST(DPO_ADJACENCY == dpo1->dpoi_type, "type is %d", dpo1->dpoi_type);
FIB_TEST((ai_01 == dpo1->dpoi_index),
"1.1.2.0/24 bucket 0 resolves via 10.10.10.1 (%d=%d)",
ai_01, dpo1->dpoi_index);
dpo1 = load_balance_get_bucket(dpo->dpoi_index, 1);
FIB_TEST(DPO_ADJACENCY == dpo1->dpoi_type, "type is %d", dpo1->dpoi_type);
FIB_TEST((ai_02 == dpo1->dpoi_index),
"1.1.2.0/24 bucket 1 resolves via 10.10.10.2");
/*
* +1 shared-pathlist
*/
FIB_TEST((2 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NBR+6 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* revert the modify
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_2_0_s_24,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_2_0_s_24);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1, tm->hw[0]->sw_if_index),
"RPF list for 1.1.2.0/24 contains one adj");
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.2.0/24 resolves via 10.10.10.1");
/*
* +1 shared-pathlist
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB is %d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add 2 recursive routes:
* 100.100.100.100/32 via 1.1.1.1/32 => the via entry is installed.
* 100.100.100.101/32 via 1.1.1.1/32 => the via entry is installed.
*/
fib_prefix_t bgp_100_pfx = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 100.100.100.100/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x64646464),
},
};
/* via 1.1.1.1 */
ip46_address_t nh_1_1_1_1 = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010101),
};
fei = fib_table_entry_path_add(fib_index,
&bgp_100_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_1_1_1_1,
~0, // no index provided.
fib_index, // nexthop in same fib as route
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&bgp_100_pfx, &pfx_1_1_1_1_s_32, 0);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 1,
tm->hw[0]->sw_if_index),
"RPF list for adj-fib contains adj");
/*
* +1 entry and +1 shared-path-list
*/
FIB_TEST((2 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+6 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
fib_prefix_t bgp_101_pfx = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 100.100.100.101/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x64646465),
},
};
fib_table_entry_path_add(fib_index,
&bgp_101_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_1_1_1_1,
~0, // no index provided.
fib_index, // nexthop in same fib as route
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&bgp_101_pfx, &pfx_1_1_1_1_s_32, 0);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 1,
tm->hw[0]->sw_if_index),
"RPF list for adj-fib contains adj");
/*
* +1 entry, but the recursive path-list is shared.
*/
FIB_TEST((2 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+6 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+8 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* An EXCLUSIVE route; one where the user (me) provides the exclusive
* adjacency through which the route will resovle
*/
fib_prefix_t ex_pfx = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 4.4.4.4/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x04040404),
},
};
fib_table_entry_special_add(fib_index,
&ex_pfx,
FIB_SOURCE_SPECIAL,
FIB_ENTRY_FLAG_EXCLUSIVE,
locked_ai);
fei = fib_table_lookup_exact_match(fib_index, &ex_pfx);
FIB_TEST((ai == fib_entry_get_adj(fei)),
"Exclusive route links to user adj");
fib_table_entry_special_remove(fib_index,
&ex_pfx,
FIB_SOURCE_SPECIAL);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &ex_pfx),
"Exclusive reoute removed");
/*
* An EXCLUSIVE route; one where the user (me) provides the exclusive
* adjacency through which the route will resovle
*/
dpo_id_t ex_dpo = DPO_INVALID;
lookup_dpo_add_or_lock_w_fib_index(fib_index,
DPO_PROTO_IP4,
LOOKUP_INPUT_DST_ADDR,
LOOKUP_TABLE_FROM_CONFIG,
&ex_dpo);
fib_table_entry_special_dpo_add(fib_index,
&ex_pfx,
FIB_SOURCE_SPECIAL,
FIB_ENTRY_FLAG_EXCLUSIVE,
&ex_dpo);
fei = fib_table_lookup_exact_match(fib_index, &ex_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(&ex_dpo, load_balance_get_bucket(dpo->dpoi_index, 0)),
"exclusive remote uses lookup DPO");
/*
* update the exclusive to use a different DPO
*/
ip_null_dpo_add_and_lock(DPO_PROTO_IP4,
IP_NULL_ACTION_SEND_ICMP_UNREACH,
&ex_dpo);
fib_table_entry_special_dpo_update(fib_index,
&ex_pfx,
FIB_SOURCE_SPECIAL,
FIB_ENTRY_FLAG_EXCLUSIVE,
&ex_dpo);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(&ex_dpo, load_balance_get_bucket(dpo->dpoi_index, 0)),
"exclusive remote uses now uses NULL DPO");
fib_table_entry_special_remove(fib_index,
&ex_pfx,
FIB_SOURCE_SPECIAL);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &ex_pfx),
"Exclusive reoute removed");
dpo_reset(&ex_dpo);
/*
* Add a recursive route:
* 200.200.200.200/32 via 1.1.1.2/32 => the via entry is NOT installed.
*/
fib_prefix_t bgp_200_pfx = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 200.200.200.200/32 */
.ip4.as_u32 = clib_host_to_net_u32(0xc8c8c8c8),
},
};
/* via 1.1.1.2 */
fib_prefix_t pfx_1_1_1_2_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010102),
},
};
fib_table_entry_path_add(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0, // no index provided.
fib_index, // nexthop in same fib as route
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
/*
* the adj should be recursive via drop, since the route resolves via
* the default route, which is itself a DROP
*/
fei = fib_table_lookup(fib_index, &pfx_1_1_1_2_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(load_balance_is_drop(dpo1), "1.1.1.2/32 is drop");
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 0),
"RPF list for 1.1.1.2/32 contains 0 adjs");
/*
* +2 entry and +1 shared-path-list
*/
FIB_TEST((3 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+7 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+10 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Unequal Cost load-balance. 3:1 ratio. fits in a 4 bucket LB
* The paths are sort by NH first. in this case the the path with greater
* weight is first in the set. This ordering is to test the RPF sort|uniq logic
*/
fib_prefix_t pfx_1_2_3_4_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01020304),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_2_3_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_entry_path_add(fib_index,
&pfx_1_2_3_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_12_12_12_12,
tm->hw[1]->sw_if_index,
~0,
3,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "1.2.3.4/32 presnet");
dpo = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 4),
"1.2.3.4/32 LB has %d bucket",
lb->lb_n_buckets);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_4_s_32, 0, ai_12_12_12_12);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_4_s_32, 1, ai_12_12_12_12);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_4_s_32, 2, ai_12_12_12_12);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_4_s_32, 3, ai_01);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 2,
tm->hw[0]->sw_if_index,
tm->hw[1]->sw_if_index),
"RPF list for 1.2.3.4/32 contains both adjs");
/*
* Unequal Cost load-balance. 4:1 ratio.
* fits in a 16 bucket LB with ratio 13:3
*/
fib_prefix_t pfx_1_2_3_5_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01020305),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_2_3_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_12_12_12_12,
tm->hw[1]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_entry_path_add(fib_index,
&pfx_1_2_3_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
4,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "1.2.3.5/32 presnet");
dpo = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 16),
"1.2.3.5/32 LB has %d bucket",
lb->lb_n_buckets);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 0, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 1, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 2, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 3, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 4, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 5, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 6, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 7, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 8, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 9, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 10, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 11, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 12, ai_01);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 13, ai_12_12_12_12);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 14, ai_12_12_12_12);
FIB_TEST_LB_BUCKET_VIA_ADJ(&pfx_1_2_3_5_s_32, 15, ai_12_12_12_12);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 2,
tm->hw[0]->sw_if_index,
tm->hw[1]->sw_if_index),
"RPF list for 1.2.3.4/32 contains both adjs");
/*
* Test UCMP with a large weight skew - this produces load-balance objects with large
* numbers of buckets to accommodate the skew. By updating said load-balances we are
* laso testing the LB in placce modify code when number of buckets is large.
*/
fib_prefix_t pfx_6_6_6_6_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 1.1.1.1/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x06060606),
},
};
fib_test_lb_bucket_t ip_6_6_6_6_o_10_10_10_1 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_01,
},
};
fib_test_lb_bucket_t ip_6_6_6_6_o_10_10_10_2 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_02,
},
};
fib_test_lb_bucket_t ip_6_6_6_6_o_12_12_12_12 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_12_12_12_12,
},
};
fib_table_entry_update_one_path(fib_index,
&pfx_6_6_6_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
0, // zero weigth
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_6_6_6_6_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_6_6_6_6_o_10_10_10_1),
"6.6.6.6/32 via 10.10.10.1");
fib_table_entry_path_add(fib_index,
&pfx_6_6_6_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
100,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_6_6_6_6_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
64,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_1),
"6.6.6.6/32 via 10.10.10.1 and 10.10.10.2 in 63:1 ratio");
fib_table_entry_path_add(fib_index,
&pfx_6_6_6_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_12_12_12_12,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
100,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_6_6_6_6_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
128,
&ip_6_6_6_6_o_10_10_10_1,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12,
&ip_6_6_6_6_o_12_12_12_12),
"6.6.6.6/32 via 10.10.10.1 and 10.10.10.2 in 63:1 ratio");
fib_table_entry_path_remove(fib_index,
&pfx_6_6_6_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_12_12_12_12,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
100,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_6_6_6_6_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
64,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_2,
&ip_6_6_6_6_o_10_10_10_1),
"6.6.6.6/32 via 10.10.10.1 and 10.10.10.2 in 63:1 ratio");
fib_table_entry_path_remove(fib_index,
&pfx_6_6_6_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
100,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_6_6_6_6_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_6_6_6_6_o_10_10_10_1),
"6.6.6.6/32 via 10.10.10.1");
fib_table_entry_delete(fib_index, &pfx_6_6_6_6_s_32, FIB_SOURCE_API);
/*
* A recursive via the two unequal cost entries
*/
fib_prefix_t bgp_44_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 200.200.200.201/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x44444444),
},
};
fei = fib_table_entry_path_add(fib_index,
&bgp_44_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_2_3_4_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_entry_path_add(fib_index,
&bgp_44_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_2_3_5_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&bgp_44_s_32, &pfx_1_2_3_4_s_32, 0);
FIB_TEST_REC_FORW(&bgp_44_s_32, &pfx_1_2_3_5_s_32, 1);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 2,
tm->hw[0]->sw_if_index,
tm->hw[1]->sw_if_index),
"RPF list for 1.2.3.4/32 contains both adjs");
/*
* test the uRPF check functions
*/
dpo_id_t dpo_44 = DPO_INVALID;
index_t urpfi;
fib_entry_contribute_forwarding(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, &dpo_44);
urpfi = load_balance_get_urpf(dpo_44.dpoi_index);
FIB_TEST(fib_urpf_check(urpfi, tm->hw[0]->sw_if_index),
"uRPF check for 68.68.68.68/32 on %d OK",
tm->hw[0]->sw_if_index);
FIB_TEST(fib_urpf_check(urpfi, tm->hw[1]->sw_if_index),
"uRPF check for 68.68.68.68/32 on %d OK",
tm->hw[1]->sw_if_index);
FIB_TEST(!fib_urpf_check(urpfi, 99),
"uRPF check for 68.68.68.68/32 on 99 not-OK",
99);
dpo_reset(&dpo_44);
fib_table_entry_delete(fib_index,
&bgp_44_s_32,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_1_2_3_5_s_32,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_1_2_3_4_s_32,
FIB_SOURCE_API);
/*
* Add a recursive route:
* 200.200.200.201/32 via 1.1.1.200/32 => the via entry is NOT installed.
*/
fib_prefix_t bgp_201_pfx = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 200.200.200.201/32 */
.ip4.as_u32 = clib_host_to_net_u32(0xc8c8c8c9),
},
};
/* via 1.1.1.200 */
fib_prefix_t pfx_1_1_1_200_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x010101c8),
},
};
fib_table_entry_path_add(fib_index,
&bgp_201_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_200_s_32.fp_addr,
~0, // no index provided.
fib_index, // nexthop in same fib as route
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_200_s_32);
FIB_TEST((FIB_ENTRY_FLAG_NONE == fib_entry_get_flags(fei)),
"Flags set on RR via non-attached");
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 0),
"RPF list for BGP route empty");
/*
* +2 entry (BGP & RR) and +1 shared-path-list
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+12 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* insert a route that covers the missing 1.1.1.2/32. we epxect
* 200.200.200.200/32 and 200.200.200.201/32 to resolve through it.
*/
fib_prefix_t pfx_1_1_1_0_s_24 = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 1.1.1.0/24 */
.ip4.as_u32 = clib_host_to_net_u32(0x01010100),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_0_s_24,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_0_s_24);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.1.0/24 resolves via 10.10.10.1");
fei = fib_table_lookup(fib_index, &pfx_1_1_1_2_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.1.2/32 resolves via 10.10.10.1");
fei = fib_table_lookup(fib_index, &pfx_1_1_1_200_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "1.1.1.200/24 resolves via 10.10.10.1");
/*
* +1 entry. 1.1.1.1/32 already uses 10.10.10.1 so no new pah-list
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+13 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* the recursive adj for 200.200.200.200 should be updated.
*/
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
fei = fib_table_lookup(fib_index, &bgp_200_pfx);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 1,
tm->hw[0]->sw_if_index),
"RPF list for BGP route has itf index 0");
/*
* insert a more specific route than 1.1.1.0/24 that also covers the
* missing 1.1.1.2/32, but not 1.1.1.200/32. we epxect
* 200.200.200.200 to resolve through it.
*/
fib_prefix_t pfx_1_1_1_0_s_28 = {
.fp_len = 28,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 1.1.1.0/24 */
.ip4.as_u32 = clib_host_to_net_u32(0x01010100),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_0_s_28,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_0_s_28);
dpo2 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_02 == ai), "1.1.1.0/24 resolves via 10.10.10.2");
/*
* +1 entry. +1 shared path-list
*/
FIB_TEST((5 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+9 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+14 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* the recursive adj for 200.200.200.200 should be updated.
* 200.200.200.201 remains unchanged.
*/
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
/*
* remove this /28. 200.200.200.200/32 should revert back to via 1.1.1.0/24
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_0_s_28,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_0_s_28) ==
FIB_NODE_INDEX_INVALID),
"1.1.1.0/28 removed");
FIB_TEST((fib_table_lookup(fib_index, &pfx_1_1_1_0_s_28) ==
fib_table_lookup(fib_index, &pfx_1_1_1_0_s_24)),
"1.1.1.0/28 lookup via /24");
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
/*
* -1 entry. -1 shared path-list
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+13 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* remove 1.1.1.0/24. 200.200.200.200/32 should revert back to via 0.0.0.0/0
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_0_s_24,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_0_s_24) ==
FIB_NODE_INDEX_INVALID),
"1.1.1.0/24 removed");
fei = fib_table_lookup(fib_index, &pfx_1_1_1_2_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"1.1.1.2/32 route is DROP");
fei = fib_table_lookup(fib_index, &pfx_1_1_1_200_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"1.1.1.200/32 route is DROP");
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
/*
* -1 entry
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+12 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* insert the missing 1.1.1.2/32
*/
fei = fib_table_entry_path_add(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai = ai_01), "1.1.1.2/32 resolves via 10.10.10.1");
FIB_TEST_REC_FORW(&bgp_201_pfx, &pfx_1_1_1_200_s_32, 0);
FIB_TEST_REC_FORW(&bgp_200_pfx, &pfx_1_1_1_2_s_32, 0);
/*
* no change. 1.1.1.2/32 was already there RR sourced.
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+12 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* remove 200.200.200.201/32 which does not have a valid via FIB
*/
fib_table_entry_path_remove(fib_index,
&bgp_201_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_200_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
FIB_ROUTE_PATH_FLAG_NONE);
/*
* -2 entries (BGP and RR). -1 shared path-list;
*/
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_201_pfx) ==
FIB_NODE_INDEX_INVALID),
"200.200.200.201/32 removed");
FIB_TEST((fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_200_s_32) ==
FIB_NODE_INDEX_INVALID),
"1.1.1.200/32 removed");
FIB_TEST((3 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+7 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+10 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* remove 200.200.200.200/32 which does have a valid via FIB
*/
fib_table_entry_path_remove(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_200_pfx) ==
FIB_NODE_INDEX_INVALID),
"200.200.200.200/32 removed");
FIB_TEST((fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_2_s_32) !=
FIB_NODE_INDEX_INVALID),
"1.1.1.2/32 still present");
/*
* -1 entry (BGP, the RR source is also API sourced). -1 shared path-list;
*/
FIB_TEST((2 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+6 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+9 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* A recursive prefix that has a 2 path load-balance.
* It also shares a next-hop with other BGP prefixes and hence
* test the ref counting of RR sourced prefixes and 2 level LB.
*/
const fib_prefix_t bgp_102 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 100.100.100.101/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x64646466),
},
};
fib_table_entry_path_add(fib_index,
&bgp_102,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&bgp_102,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &bgp_102);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "100.100.100.102/32 presnet");
dpo = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_1_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_2_s_32);
dpo2 = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 2), "Recursive LB has %d bucket", lb->lb_n_buckets);
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket(dpo->dpoi_index, 0)),
"First via 10.10.10.1");
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket(dpo->dpoi_index, 1)),
"Second via 10.10.10.1");
fib_table_entry_path_remove(fib_index,
&bgp_102,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&bgp_102,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &bgp_102);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "100.100.100.102/32 removed");
/*
* remove the remaining recursives
*/
fib_table_entry_path_remove(fib_index,
&bgp_100_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&bgp_101_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_100_pfx) ==
FIB_NODE_INDEX_INVALID),
"100.100.100.100/32 removed");
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_101_pfx) ==
FIB_NODE_INDEX_INVALID),
"100.100.100.101/32 removed");
/*
* -2 entry (2*BGP, the RR source is also API sourced). -1 shared path-list;
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add a recursive route via a connected cover, using an adj-fib that does exist
*/
fib_table_entry_path_add(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
~0, // no index provided.
fib_index, // Same as route's FIB
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
/*
* +1 entry. +1 shared path-list (recursive via 10.10.10.1)
*/
FIB_TEST((2 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+6 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+8 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket(dpo->dpoi_index, 0)),
"200.200.200.200/32 is recursive via adj for 10.10.10.1");
FIB_TEST((FIB_ENTRY_FLAG_ATTACHED == fib_entry_get_flags(fei)),
"Flags set on RR via existing attached");
/*
* Add a recursive route via a connected cover, using and adj-fib that does
* not exist
*/
ip46_address_t nh_10_10_10_3 = {
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a03),
};
fib_prefix_t pfx_10_10_10_3 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = nh_10_10_10_3,
};
fib_table_entry_path_add(fib_index,
&bgp_201_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_3,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
/*
* +2 entries (BGP and RR). +1 shared path-list (recursive via 10.10.10.3) and
* one unshared non-recursive via 10.10.10.3
*/
FIB_TEST((3 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+10 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
ai_03 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&nh_10_10_10_3,
tm->hw[0]->sw_if_index);
fei = fib_table_lookup_exact_match(fib_index, &bgp_201_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_3);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai == ai_03), "adj for 10.10.10.3/32 is via adj for 10.10.10.3");
FIB_TEST(((FIB_ENTRY_FLAG_ATTACHED | FIB_ENTRY_FLAG_CONNECTED) ==
fib_entry_get_flags(fei)),
"Flags set on RR via non-existing attached");
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket(dpo->dpoi_index, 0)),
"adj for 200.200.200.200/32 is recursive via adj for 10.10.10.3");
adj_unlock(ai_03);
/*
* remove the recursives
*/
fib_table_entry_path_remove(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&bgp_201_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_3,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_201_pfx) ==
FIB_NODE_INDEX_INVALID),
"200.200.200.201/32 removed");
FIB_TEST((fib_table_lookup_exact_match(fib_index, &bgp_200_pfx) ==
FIB_NODE_INDEX_INVALID),
"200.200.200.200/32 removed");
FIB_TEST((fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_3) ==
FIB_NODE_INDEX_INVALID),
"10.10.10.3/32 removed");
/*
* -3 entries (2*BGP and RR). -2 shared path-list (recursive via 10.10.10.3 &
* 10.10.10.1) and one unshared non-recursive via 10.10.10.3
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* RECURSION LOOPS
* Add 5.5.5.5/32 -> 5.5.5.6/32 -> 5.5.5.7/32 -> 5.5.5.5/32
*/
fib_prefix_t pfx_5_5_5_5_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x05050505),
},
};
fib_prefix_t pfx_5_5_5_6_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x05050506),
},
};
fib_prefix_t pfx_5_5_5_7_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x05050507),
},
};
fib_table_entry_path_add(fib_index,
&pfx_5_5_5_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_6_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_7_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&pfx_5_5_5_7_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_5_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
/*
* +3 entries, +3 shared path-list
*/
FIB_TEST((4 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+8 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+10 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* All the entries have only looped paths, so they are all drop
*/
fei = fib_table_lookup(fib_index, &pfx_5_5_5_7_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.7/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_5_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.5/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_6_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.6/32 is via adj for DROP");
/*
* provide 5.5.5.6/32 with alternate path.
* this will allow only 5.5.5.6/32 to forward with this path, the others
* are still drop since the loop is still present.
*/
fib_table_entry_path_add(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_5_5_5_6_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo1->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 1), "5.5.5.6 LB has %d bucket", lb->lb_n_buckets);
dpo2 = load_balance_get_bucket(dpo1->dpoi_index, 0);
FIB_TEST(DPO_ADJACENCY == dpo2->dpoi_type, "type is %d", dpo2->dpoi_type);
FIB_TEST((ai_01 == dpo2->dpoi_index),
"5.5.5.6 bucket 0 resolves via 10.10.10.2");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_7_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.7/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_5_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.5/32 is via adj for DROP");
/*
* remove the alternate path for 5.5.5.6/32
* back to all drop
*/
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_5_5_5_7_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.7/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_5_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.5/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_6_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.6/32 is via adj for DROP");
/*
* break the loop by giving 5.5.5.5/32 a new set of paths
* expect all to forward via this new path.
*/
fib_table_entry_update_one_path(fib_index,
&pfx_5_5_5_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_5_5_5_5_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo1->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 1), "5.5.5.5 LB has %d bucket", lb->lb_n_buckets);
dpo2 = load_balance_get_bucket(dpo1->dpoi_index, 0);
FIB_TEST(DPO_ADJACENCY == dpo2->dpoi_type, "type is %d", dpo2->dpoi_type);
FIB_TEST((ai_01 == dpo2->dpoi_index),
"5.5.5.5 bucket 0 resolves via 10.10.10.2");
fei = fib_table_lookup_exact_match(fib_index, &pfx_5_5_5_7_s_32);
dpo2 = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo2->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 1), "Recursive LB has %d bucket", lb->lb_n_buckets);
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket(dpo2->dpoi_index, 0)),
"5.5.5.5.7 via 5.5.5.5");
fei = fib_table_lookup_exact_match(fib_index, &pfx_5_5_5_6_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo1->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 1), "Recursive LB has %d bucket", lb->lb_n_buckets);
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket(dpo1->dpoi_index, 0)),
"5.5.5.5.6 via 5.5.5.7");
/*
* revert back to the loop. so we can remove the prefixes with
* the loop intact
*/
fib_table_entry_update_one_path(fib_index,
&pfx_5_5_5_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_6_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_5_5_5_7_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.7/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_5_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.5/32 is via adj for DROP");
fei = fib_table_lookup(fib_index, &pfx_5_5_5_6_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"LB for 5.5.5.6/32 is via adj for DROP");
/*
* remove all the 5.5.5.x/32 prefixes
*/
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_5_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_6_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_7_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_7_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_5_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
/*
* -3 entries, -3 shared path-list
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Single level loop 5.5.5.5/32 via 5.5.5.5/32
*/
fib_table_entry_path_add(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_6_s_32.fp_addr,
~0, // no index provided.
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_5_5_5_6_s_32);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"1-level 5.5.5.6/32 loop is via adj for DROP");
fib_table_entry_path_remove(fib_index,
&pfx_5_5_5_6_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_5_5_5_6_s_32.fp_addr,
~0, // no index provided.
fib_index, // same as route's FIB
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_5_5_5_6_s_32),
"1-level 5.5.5.6/32 loop is removed");
/*
* A recursive route whose next-hop is covered by the prefix.
* This would mean the via-fib, which inherits forwarding from its
* cover, thus picks up forwarding from the prfix, which is via the
* via-fib, and we have a loop.
*/
fib_prefix_t pfx_23_23_23_0_s_24 = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x17171700),
},
};
fib_prefix_t pfx_23_23_23_23_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x17171717),
},
};
fei = fib_table_entry_path_add(fib_index,
&pfx_23_23_23_0_s_24,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_23_23_23_23_s_32.fp_addr,
~0, // recursive
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(load_balance_is_drop(dpo),
"23.23.23.0/24 via covered is DROP");
fib_table_entry_delete_index(fei, FIB_SOURCE_API);
/*
* add-remove test. no change.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* A recursive route with recursion constraints.
* 200.200.200.200/32 via 1.1.1.1 is recurse via host constrained
*/
fib_table_entry_path_add(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_1_1_1_1,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_RESOLVE_VIA_HOST);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_1_s_32);
dpo2 = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket(dpo1->dpoi_index, 0)),
"adj for 200.200.200.200/32 is recursive via adj for 1.1.1.1");
/*
* save the load-balance. we expect it to be inplace modified
*/
lb = load_balance_get(dpo1->dpoi_index);
/*
* add a covering prefix for the via fib that would otherwise serve
* as the resolving route when the host is removed
*/
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_0_s_28,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_0_s_28);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai == ai_01),
"adj for 1.1.1.0/28 is via adj for 1.1.1.1");
/*
* remove the host via FIB - expect the BGP prefix to be drop
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo1->dpoi_index, 0)),
"adj for 200.200.200.200/32 is recursive via adj for DROP");
/*
* add the via-entry host reoute back. expect to resolve again
*/
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket(dpo1->dpoi_index, 0)),
"adj for 200.200.200.200/32 is recursive via adj for 1.1.1.1");
/*
* add another path for the recursive. it will then have 2.
*/
fib_prefix_t pfx_1_1_1_3_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010103),
},
};
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_3_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_3_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_RESOLVE_VIA_HOST);
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_1_s_32);
dpo2 = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket(dpo->dpoi_index, 0)),
"adj for 200.200.200.200/32 is recursive via adj for 1.1.1.1");
fei = fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_3_s_32);
dpo1 = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket(dpo->dpoi_index, 1)),
"adj for 200.200.200.200/32 is recursive via adj for 1.1.1.3");
/*
* expect the lb-map used by the recursive's load-balance is using both buckets
*/
load_balance_map_t *lbm;
index_t lbmi;
lb = load_balance_get(dpo->dpoi_index);
lbmi = lb->lb_map;
load_balance_map_lock(lbmi);
lbm = load_balance_map_get(lbmi);
FIB_TEST(lbm->lbm_buckets[0] == 0,
"LB maps's bucket 0 is %d",
lbm->lbm_buckets[0]);
FIB_TEST(lbm->lbm_buckets[1] == 1,
"LB maps's bucket 1 is %d",
lbm->lbm_buckets[1]);
/*
* withdraw one of the /32 via-entrys.
* that ECMP path will be unresolved and forwarding should continue on the
* other available path. this is an iBGP PIC edge failover.
* Test the forwarding changes without re-fetching the adj from the
* recursive entry. this ensures its the same one that is updated; i.e. an
* inplace-modify.
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
FIB_TEST(!dpo_cmp(dpo, fib_entry_contribute_ip_forwarding(fei)),
"post PIC 200.200.200.200/32 was inplace modified");
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket_i(lb, 0)),
"post PIC adj for 200.200.200.200/32 is recursive"
" via adj for 1.1.1.3");
/*
* the LB maps that was locked above should have been modified to remove
* the path that was down, and thus its bucket points to a path that is
* still up.
*/
FIB_TEST(lbm->lbm_buckets[0] == 1,
"LB maps's bucket 0 is %d",
lbm->lbm_buckets[0]);
FIB_TEST(lbm->lbm_buckets[1] == 1,
"LB maps's bucket 1 is %d",
lbm->lbm_buckets[1]);
load_balance_map_unlock(lb->lb_map);
/*
* add it back. again
*/
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(!dpo_cmp(dpo2, load_balance_get_bucket_i(lb, 0)),
"post PIC recovery adj for 200.200.200.200/32 is recursive "
"via adj for 1.1.1.1");
FIB_TEST(!dpo_cmp(dpo1, load_balance_get_bucket_i(lb, 1)),
"post PIC recovery adj for 200.200.200.200/32 is recursive "
"via adj for 1.1.1.3");
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(lb == load_balance_get(dpo->dpoi_index),
"post PIC 200.200.200.200/32 was inplace modified");
/*
* add a 3rd path. this makes the LB 16 buckets.
*/
fib_table_entry_path_add(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_RESOLVE_VIA_HOST);
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(lb == load_balance_get(dpo->dpoi_index),
"200.200.200.200/32 was inplace modified for 3rd path");
FIB_TEST(16 == lb->lb_n_buckets,
"200.200.200.200/32 was inplace modified for 3rd path to 16 buckets");
lbmi = lb->lb_map;
load_balance_map_lock(lbmi);
lbm = load_balance_map_get(lbmi);
for (ii = 0; ii < 16; ii++)
{
FIB_TEST(lbm->lbm_buckets[ii] == ii,
"LB Map for 200.200.200.200/32 at %d is %d",
ii, lbm->lbm_buckets[ii]);
}
/*
* trigger PIC by removing the first via-entry
* the first 6 buckets of the map should map to the next 6
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &bgp_200_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(lb == load_balance_get(dpo->dpoi_index),
"200.200.200.200/32 was inplace modified for 3rd path");
FIB_TEST(2 == lb->lb_n_buckets,
"200.200.200.200/32 was inplace modified for 3rd path remove to 2 buckets");
for (ii = 0; ii < 6; ii++)
{
FIB_TEST(lbm->lbm_buckets[ii] == ii+6,
"LB Map for 200.200.200.200/32 at %d is %d",
ii, lbm->lbm_buckets[ii]);
}
for (ii = 6; ii < 16; ii++)
{
FIB_TEST(lbm->lbm_buckets[ii] == ii,
"LB Map for 200.200.200.200/32 at %d is %d",
ii, lbm->lbm_buckets[ii]);
}
/*
* tidy up
*/
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0,
fib_index,
1,
MPLS_LABEL_INVALID);
fib_table_entry_path_remove(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_1_1_1_1,
~0,
fib_index,
1,
FIB_ROUTE_PATH_RESOLVE_VIA_HOST);
fib_table_entry_path_remove(fib_index,
&bgp_200_pfx,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_3_s_32.fp_addr,
~0,
fib_index,
1,
FIB_ROUTE_PATH_RESOLVE_VIA_HOST);
fib_table_entry_delete(fib_index,
&pfx_1_1_1_3_s_32,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_1_1_1_0_s_28,
FIB_SOURCE_API);
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_0_s_28)),
"1.1.1.1/28 removed");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_3_s_32)),
"1.1.1.3/32 removed");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &bgp_200_pfx)),
"200.200.200.200/32 removed");
/*
* add-remove test. no change.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* A route whose paths are built up iteratively and then removed
* all at once
*/
fib_prefix_t pfx_4_4_4_4_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 4.4.4.4/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x04040404),
},
};
fib_table_entry_path_add(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_2,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_add(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_3,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(FIB_NODE_INDEX_INVALID !=
fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32),
"4.4.4.4/32 present");
fib_table_entry_delete(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32),
"4.4.4.4/32 removed");
/*
* add-remove test. no change.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* A route with multiple paths at once
*/
fib_route_path_t *r_paths = NULL;
for (ii = 0; ii < 4; ii++)
{
fib_route_path_t r_path = {
.frp_proto = FIB_PROTOCOL_IP4,
.frp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a02 + ii),
},
.frp_sw_if_index = tm->hw[0]->sw_if_index,
.frp_weight = 1,
.frp_fib_index = ~0,
};
vec_add1(r_paths, r_path);
}
fib_table_entry_update(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
r_paths);
fei = fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "4.4.4.4/32 present");
dpo = fib_entry_contribute_ip_forwarding(fei);
lb = load_balance_get(dpo->dpoi_index);
FIB_TEST((lb->lb_n_buckets == 4), "4.4.4.4/32 lb over %d paths", lb->lb_n_buckets);
fib_table_entry_delete(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32),
"4.4.4.4/32 removed");
vec_free(r_paths);
/*
* add-remove test. no change.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* A route deag route
*/
fib_table_entry_path_add(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&zero_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "4.4.4.4/32 present");
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
lookup_dpo_t *lkd = lookup_dpo_get(dpo->dpoi_index);
FIB_TEST((fib_index == lkd->lkd_fib_index),
"4.4.4.4/32 is deag in %d %U",
lkd->lkd_fib_index,
format_dpo_id, dpo, 0);
fib_table_entry_delete(fib_index,
&pfx_4_4_4_4_s_32,
FIB_SOURCE_API);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_4_4_4_4_s_32),
"4.4.4.4/32 removed");
vec_free(r_paths);
/*
* add-remove test. no change.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+7 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Duplicate paths:
* add a recursive with duplicate paths. Expect the duplicate to be ignored.
*/
fib_prefix_t pfx_34_1_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x22010101),
},
};
fib_prefix_t pfx_34_34_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x22220101),
},
};
fei = fib_table_entry_path_add(fib_index,
&pfx_34_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_34_34_1_1_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_entry_path_add(fib_index,
&pfx_34_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_34_34_1_1_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST_REC_FORW(&pfx_34_1_1_1_s_32, &pfx_34_34_1_1_s_32, 0);
fib_table_entry_delete_index(fei, FIB_SOURCE_API);
/*
* CLEANUP
* remove: 1.1.1.2/32, 1.1.2.0/24 and 1.1.1.1/32
* all of which are via 10.10.10.1, Itf1
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fib_table_entry_path_remove(fib_index,
&pfx_1_1_2_0_s_24,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_1_s_32),
"1.1.1.1/32 removed");
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_1_1_1_2_s_32),
"1.1.1.2/32 removed");
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_1_1_2_0_s_24),
"1.1.2.0/24 removed");
/*
* -3 entries and -1 shared path-list
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+4 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+4 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* An attached-host route. Expect to link to the incomplete adj
*/
fib_prefix_t pfx_4_1_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 4.1.1.1/32 */
.ip4.as_u32 = clib_host_to_net_u32(0x04010101),
},
};
fib_table_entry_path_add(fib_index,
&pfx_4_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&zero_addr,
tm->hw[0]->sw_if_index,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_4_1_1_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "4.1.1.1/32 present");
ai = fib_entry_get_adj(fei);
ai2 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&pfx_4_1_1_1_s_32.fp_addr,
tm->hw[0]->sw_if_index);
FIB_TEST((ai == ai2), "Attached-host link to incomplete ADJ");
adj_unlock(ai2);
/*
* +1 entry and +1 shared path-list
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+5 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
fib_table_entry_delete(fib_index,
&pfx_4_1_1_1_s_32,
FIB_SOURCE_API);
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+4 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+4 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* add a v6 prefix via v4 next-hops
*/
fib_prefix_t pfx_2001_s_64 = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6.as_u64[0] = clib_host_to_net_u64(0x2001000000000000),
},
};
fei = fib_table_entry_path_add(0, //default v6 table
&pfx_2001_s_64,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(0, &pfx_2001_s_64);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "2001::/64 present");
ai = fib_entry_get_adj(fei);
adj = adj_get(ai);
FIB_TEST((adj->lookup_next_index == IP_LOOKUP_NEXT_ARP),
"2001::/64 via ARP-adj");
FIB_TEST((adj->ia_link == VNET_LINK_IP6),
"2001::/64 is link type v6");
FIB_TEST((adj->ia_nh_proto == FIB_PROTOCOL_IP4),
"2001::/64 ADJ-adj is NH proto v4");
fib_table_entry_delete(0, &pfx_2001_s_64, FIB_SOURCE_API);
/*
* add a uRPF exempt prefix:
* test:
* - it's forwarding is drop
* - it's uRPF list is not empty
* - the uRPF list for the default route (it's cover) is empty
*/
fei = fib_table_entry_special_add(fib_index,
&pfx_4_1_1_1_s_32,
FIB_SOURCE_URPF_EXEMPT,
FIB_ENTRY_FLAG_DROP,
ADJ_INDEX_INVALID);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(load_balance_is_drop(dpo),
"uRPF exempt 4.1.1.1/32 DROP");
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 1, 0),
"uRPF list for exempt prefix has itf index 0");
fei = fib_table_lookup_exact_match(fib_index, &pfx_0_0_0_0_s_0);
FIB_TEST(fib_test_urpf_is_equal(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, 0),
"uRPF list for 0.0.0.0/0 empty");
fib_table_entry_delete(fib_index, &pfx_4_1_1_1_s_32, FIB_SOURCE_URPF_EXEMPT);
/*
* CLEANUP
* remove adj-fibs:
*/
fib_table_entry_delete(fib_index,
&pfx_10_10_10_1_s_32,
FIB_SOURCE_ADJ);
fib_table_entry_delete(fib_index,
&pfx_10_10_10_2_s_32,
FIB_SOURCE_ADJ);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32),
"10.10.10.1/32 adj-fib removed");
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_2_s_32),
"10.10.10.2/32 adj-fib removed");
/*
* -2 entries and -2 non-shared path-list
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR+2 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* unlock the adjacencies for which this test provided a rewrite.
* These are the last locks on these adjs. they should thus go away.
*/
adj_unlock(ai_02);
adj_unlock(ai_01);
adj_unlock(ai_12_12_12_12);
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
/*
* CLEANUP
* remove the interface prefixes
*/
local_pfx.fp_len = 32;
fib_table_entry_special_remove(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE);
fei = fib_table_lookup(fib_index, &local_pfx);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &local_pfx),
"10.10.10.10/32 adj-fib removed");
local_pfx.fp_len = 24;
fib_table_entry_delete(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE);
FIB_TEST(FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &local_pfx),
"10.10.10.10/24 adj-fib removed");
/*
* -2 entries and -2 non-shared path-list
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Last but not least, remove the VRF
*/
FIB_TEST((0 == fib_table_get_num_entries(fib_index,
FIB_PROTOCOL_IP4,
FIB_SOURCE_API)),
"NO API Source'd prefixes");
FIB_TEST((0 == fib_table_get_num_entries(fib_index,
FIB_PROTOCOL_IP4,
FIB_SOURCE_RR)),
"NO RR Source'd prefixes");
FIB_TEST((0 == fib_table_get_num_entries(fib_index,
FIB_PROTOCOL_IP4,
FIB_SOURCE_INTERFACE)),
"NO INterface Source'd prefixes");
fib_table_unlock(fib_index, FIB_PROTOCOL_IP4);
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NBR-5 == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NBR-5 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
FIB_TEST((NBR-5 == pool_elts(fib_urpf_list_pool)), "uRPF pool size is %d",
pool_elts(fib_urpf_list_pool));
return 0;
}
static int
fib_test_v6 (void)
{
/*
* In the default table check for the presence and correct forwarding
* of the special entries
*/
fib_node_index_t dfrt, fei, ai, locked_ai, ai_01, ai_02;
const dpo_id_t *dpo, *dpo_drop;
const ip_adjacency_t *adj;
const receive_dpo_t *rd;
test_main_t *tm;
u32 fib_index;
int ii;
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
/* via 2001:0:0:1::2 */
ip46_address_t nh_2001_2 = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x2001000000000001),
[1] = clib_host_to_net_u64(0x0000000000000002),
},
},
};
tm = &test_main;
dpo_drop = drop_dpo_get(DPO_PROTO_IP6);
/* Find or create FIB table 11 */
fib_index = fib_table_find_or_create_and_lock(FIB_PROTOCOL_IP6, 11);
for (ii = 0; ii < 4; ii++)
{
ip6_main.fib_index_by_sw_if_index[tm->hw[ii]->sw_if_index] = fib_index;
}
fib_prefix_t pfx_0_0 = {
.fp_len = 0,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
{0, 0},
},
},
};
dfrt = fib_table_lookup(fib_index, &pfx_0_0);
FIB_TEST((FIB_NODE_INDEX_INVALID != dfrt), "default route present");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(dfrt)),
"Default route is DROP");
dpo = fib_entry_contribute_ip_forwarding(dfrt);
FIB_TEST((dpo->dpoi_index == ip6_fib_table_fwding_lookup(
&ip6_main,
1,
&pfx_0_0.fp_addr.ip6)),
"default-route; fwd and non-fwd tables match");
// FIXME - check specials.
/*
* At this stage there is one v4 FIB with 5 routes and two v6 FIBs
* each with 6 entries. All entries are special so no path-list sharing.
*/
#define NPS (5+6+6)
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NPS == fib_path_list_pool_size()), "path list pool size is %d",
fib_path_list_pool_size());
FIB_TEST((NPS == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* add interface routes.
* validate presence of /64 attached and /128 recieve.
* test for the presence of the receive address in the glean and local adj
*
* receive on 2001:0:0:1::1/128
*/
fib_prefix_t local_pfx = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x2001000000000001),
[1] = clib_host_to_net_u64(0x0000000000000001),
},
},
}
};
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP6,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached interface route present");
ai = fib_entry_get_adj(fei);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai), "attached interface route adj present");
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_GLEAN == adj->lookup_next_index),
"attached interface adj is glean");
FIB_TEST((0 == ip46_address_cmp(&local_pfx.fp_addr,
&adj->sub_type.glean.receive_addr)),
"attached interface adj is receive ok");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST((dpo->dpoi_index == ip6_fib_table_fwding_lookup(
&ip6_main,
1,
&local_pfx.fp_addr.ip6)),
"attached-route; fwd and non-fwd tables match");
local_pfx.fp_len = 128;
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP6,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local interface route present");
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST((DPO_RECEIVE == dpo->dpoi_type),
"local interface adj is local");
rd = receive_dpo_get(dpo->dpoi_index);
FIB_TEST((0 == ip46_address_cmp(&local_pfx.fp_addr,
&rd->rd_addr)),
"local interface adj is receive ok");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST((dpo->dpoi_index == ip6_fib_table_fwding_lookup(
&ip6_main,
1,
&local_pfx.fp_addr.ip6)),
"local-route; fwd and non-fwd tables match");
/*
* +2 entries. +2 unshared path-lists
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB is empty");
FIB_TEST((NPS+2 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Modify the default route to be via an adj not yet known.
* this sources the defalut route with the API source, which is
* a higher preference to the DEFAULT_ROUTE source
*/
fib_table_entry_path_add(fib_index, &pfx_0_0,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_0_0);
FIB_TEST((fei == dfrt), "default route same index");
ai = fib_entry_get_adj(fei);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai), "default route adj present");
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&nh_2001_2, &adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
/*
* find the adj in the shared db
*/
locked_ai = adj_nbr_add_or_lock(FIB_PROTOCOL_IP6,
VNET_LINK_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index);
FIB_TEST((locked_ai == ai), "ADJ NBR DB find");
adj_unlock(locked_ai);
/*
* no more entires. +1 shared path-list
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+3 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* remove the API source from the default route. We expected
* the route to remain, sourced by DEFAULT_ROUTE, and hence a DROP
*/
fib_table_entry_path_remove(fib_index, &pfx_0_0,
FIB_SOURCE_API,
FIB_PROTOCOL_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_0_0);
FIB_TEST((fei == dfrt), "default route same index");
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(dfrt)),
"Default route is DROP");
/*
* no more entires. -1 shared path-list
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+2 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+2 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add an 2 ARP entry => a complete ADJ plus adj-fib.
*/
fib_prefix_t pfx_2001_1_2_s_128 = {
.fp_len = 128,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x2001000000000001),
[1] = clib_host_to_net_u64(0x0000000000000002),
},
},
}
};
fib_prefix_t pfx_2001_1_3_s_128 = {
.fp_len = 128,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x2001000000000001),
[1] = clib_host_to_net_u64(0x0000000000000003),
},
},
}
};
u8 eth_addr[] = {
0xde, 0xde, 0xde, 0xba, 0xba, 0xba,
};
ai_01 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP6,
VNET_LINK_IP6,
&pfx_2001_1_2_s_128.fp_addr,
tm->hw[0]->sw_if_index);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai_01), "adj created");
adj = adj_get(ai_01);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&pfx_2001_1_2_s_128.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
adj_nbr_update_rewrite(ai_01, ADJ_NBR_REWRITE_FLAG_COMPLETE,
fib_test_build_rewrite(eth_addr));
FIB_TEST((IP_LOOKUP_NEXT_REWRITE == adj->lookup_next_index),
"adj is complete");
FIB_TEST((0 == ip46_address_cmp(&pfx_2001_1_2_s_128.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
fib_table_entry_update_one_path(fib_index,
&pfx_2001_1_2_s_128,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP6,
&pfx_2001_1_2_s_128.fp_addr,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2001_1_2_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "ADJ-FIB resolves via adj");
eth_addr[5] = 0xb2;
ai_02 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP6,
VNET_LINK_IP6,
&pfx_2001_1_3_s_128.fp_addr,
tm->hw[0]->sw_if_index);
FIB_TEST((FIB_NODE_INDEX_INVALID != ai_02), "adj created");
adj = adj_get(ai_02);
FIB_TEST((IP_LOOKUP_NEXT_ARP == adj->lookup_next_index),
"adj is incomplete");
FIB_TEST((0 == ip46_address_cmp(&pfx_2001_1_3_s_128.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
adj_nbr_update_rewrite(ai_02, ADJ_NBR_REWRITE_FLAG_COMPLETE,
fib_test_build_rewrite(eth_addr));
FIB_TEST((IP_LOOKUP_NEXT_REWRITE == adj->lookup_next_index),
"adj is complete");
FIB_TEST((0 == ip46_address_cmp(&pfx_2001_1_3_s_128.fp_addr,
&adj->sub_type.nbr.next_hop)),
"adj nbr next-hop ok");
FIB_TEST((ai_01 != ai_02), "ADJs are different");
fib_table_entry_update_one_path(fib_index,
&pfx_2001_1_3_s_128,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP6,
&pfx_2001_1_3_s_128.fp_addr,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2001_1_3_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_02 == ai), "ADJ-FIB resolves via adj");
/*
* +2 entries, +2 unshread path-lists.
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+4 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+4 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add a 2 routes via the first ADJ. ensure path-list sharing
*/
fib_prefix_t pfx_2001_a_s_64 = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x200100000000000a),
[1] = clib_host_to_net_u64(0x0000000000000000),
},
},
}
};
fib_prefix_t pfx_2001_b_s_64 = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x200100000000000b),
[1] = clib_host_to_net_u64(0x0000000000000000),
},
},
}
};
fib_table_entry_path_add(fib_index,
&pfx_2001_a_s_64,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2001_a_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::a/64 resolves via 2001:0:0:1::1");
fib_table_entry_path_add(fib_index,
&pfx_2001_b_s_64,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2001_b_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::b/64 resolves via 2001:0:0:1::1");
/*
* +2 entries, +1 shared path-list.
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+5 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* add a v4 prefix via a v6 next-hop
*/
fib_prefix_t pfx_1_1_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = 0x01010101,
},
};
fei = fib_table_entry_path_add(0, // default table
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP6,
&nh_2001_2,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fei == fib_table_lookup_exact_match(0, &pfx_1_1_1_1_s_32),
"1.1.1.1/32 o v6 route present");
ai = fib_entry_get_adj(fei);
adj = adj_get(ai);
FIB_TEST((adj->lookup_next_index == IP_LOOKUP_NEXT_ARP),
"1.1.1.1/32 via ARP-adj");
FIB_TEST((adj->ia_link == VNET_LINK_IP4),
"1.1.1.1/32 ADJ-adj is link type v4");
FIB_TEST((adj->ia_nh_proto == FIB_PROTOCOL_IP6),
"1.1.1.1/32 ADJ-adj is NH proto v6");
fib_table_entry_delete(0, &pfx_1_1_1_1_s_32, FIB_SOURCE_API);
/*
* An attached route
*/
fib_prefix_t pfx_2001_c_s_64 = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
.as_u64 = {
[0] = clib_host_to_net_u64(0x200100000000000c),
[1] = clib_host_to_net_u64(0x0000000000000000),
},
},
}
};
fib_table_entry_path_add(fib_index,
&pfx_2001_c_s_64,
FIB_SOURCE_CLI,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP6,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_c_s_64);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached route present");
ai = fib_entry_get_adj(fei);
adj = adj_get(ai);
FIB_TEST((adj->lookup_next_index == IP_LOOKUP_NEXT_GLEAN),
"2001:0:0:c/64 attached resolves via glean");
fib_table_entry_path_remove(fib_index,
&pfx_2001_c_s_64,
FIB_SOURCE_CLI,
FIB_PROTOCOL_IP6,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_c_s_64);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "attached route removed");
/*
* Shutdown the interface on which we have a connected and through
* which the routes are reachable.
* This will result in the connected, adj-fibs, and routes linking to drop
* The local/for-us prefix continues to receive.
*/
clib_error_t * error;
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[0]->sw_if_index,
~VNET_SW_INTERFACE_FLAG_ADMIN_UP);
FIB_TEST((NULL == error), "Interface shutdown OK");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001::a/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::3/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::2/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::1/128 not drop");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1/64 resolves via drop");
/*
* no change
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+5 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* shutdown one of the other interfaces, then add a connected.
* and swap one of the routes to it.
*/
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[1]->sw_if_index,
~VNET_SW_INTERFACE_FLAG_ADMIN_UP);
FIB_TEST((NULL == error), "Interface 1 shutdown OK");
fib_prefix_t connected_pfx = {
.fp_len = 64,
.fp_proto = FIB_PROTOCOL_IP6,
.fp_addr = {
.ip6 = {
/* 2001:0:0:2::1/64 */
.as_u64 = {
[0] = clib_host_to_net_u64(0x2001000000000002),
[1] = clib_host_to_net_u64(0x0000000000000001),
},
},
}
};
fib_table_entry_update_one_path(fib_index, &connected_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP6,
NULL,
tm->hw[1]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &connected_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached interface route present");
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST(!dpo_cmp(dpo, dpo_drop),
"2001:0:0:2/64 not resolves via drop");
connected_pfx.fp_len = 128;
fib_table_entry_update_one_path(fib_index, &connected_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP6,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &connected_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local interface route present");
dpo = fib_entry_contribute_ip_forwarding(fei);
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
FIB_TEST((DPO_RECEIVE == dpo->dpoi_type),
"local interface adj is local");
rd = receive_dpo_get(dpo->dpoi_index);
FIB_TEST((0 == ip46_address_cmp(&connected_pfx.fp_addr,
&rd->rd_addr)),
"local interface adj is receive ok");
/*
* +2 entries, +2 unshared path-lists
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+7 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+8 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* bring the interface back up. we expected the routes to return
* to normal forwarding.
*/
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[0]->sw_if_index,
VNET_SW_INTERFACE_FLAG_ADMIN_UP);
FIB_TEST((NULL == error), "Interface bring-up OK");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::a/64 resolves via 2001:0:0:1::1");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::b/64 resolves via 2001:0:0:1::1");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_02 == ai), "ADJ-FIB resolves via adj");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "ADJ-FIB resolves via adj");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
ai = fib_entry_get_adj(fei);
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_GLEAN == adj->lookup_next_index),
"attached interface adj is glean");
/*
* Same test as above, but this time the HW interface goes down
*/
error = vnet_hw_interface_set_flags(vnet_get_main(),
tm->hw_if_indicies[0],
~VNET_HW_INTERFACE_FLAG_LINK_UP);
FIB_TEST((NULL == error), "Interface shutdown OK");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001::a/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::3/128 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::2/128 resolves via drop");
local_pfx.fp_len = 128;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1::1/128 not drop");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(!dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"2001:0:0:1/64 resolves via drop");
error = vnet_hw_interface_set_flags(vnet_get_main(),
tm->hw_if_indicies[0],
VNET_HW_INTERFACE_FLAG_LINK_UP);
FIB_TEST((NULL == error), "Interface bring-up OK");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::a/64 resolves via 2001:0:0:1::1");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "2001::b/64 resolves via 2001:0:0:1::1");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_02 == ai), "ADJ-FIB resolves via adj");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
ai = fib_entry_get_adj(fei);
FIB_TEST((ai_01 == ai), "ADJ-FIB resolves via adj");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
ai = fib_entry_get_adj(fei);
adj = adj_get(ai);
FIB_TEST((IP_LOOKUP_NEXT_GLEAN == adj->lookup_next_index),
"attached interface adj is glean");
/*
* Delete the interface that the routes reolve through.
* Again no routes are removed. They all point to drop.
*
* This is considered an error case. The control plane should
* not remove interfaces through which routes resolve, but
* such things can happen. ALL affected routes will drop.
*/
vnet_delete_hw_interface(vnet_get_main(), tm->hw_if_indicies[0]);
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::3/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::2/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::1/128 is drop");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1/64 resolves via drop");
/*
* no change
*/
FIB_TEST((1 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS+7 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS+8 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* Add the interface back. routes stay unresolved.
*/
error = ethernet_register_interface(vnet_get_main(),
test_interface_device_class.index,
0 /* instance */,
hw_address,
&tm->hw_if_indicies[0],
/* flag change */ 0);
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001::b/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::3/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::2/64 resolves via drop");
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1::1/128 is drop");
local_pfx.fp_len = 64;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST(load_balance_is_drop(fib_entry_contribute_ip_forwarding(fei)),
"2001:0:0:1/64 resolves via drop");
/*
* CLEANUP ALL the routes
*/
fib_table_entry_delete(fib_index,
&pfx_2001_c_s_64,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_2001_a_s_64,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_2001_b_s_64,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_2001_1_3_s_128,
FIB_SOURCE_ADJ);
fib_table_entry_delete(fib_index,
&pfx_2001_1_2_s_128,
FIB_SOURCE_ADJ);
local_pfx.fp_len = 64;
fib_table_entry_delete(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE);
local_pfx.fp_len = 128;
fib_table_entry_special_remove(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE);
connected_pfx.fp_len = 64;
fib_table_entry_delete(fib_index, &connected_pfx,
FIB_SOURCE_INTERFACE);
connected_pfx.fp_len = 128;
fib_table_entry_special_remove(fib_index, &connected_pfx,
FIB_SOURCE_INTERFACE);
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_2001_a_s_64)),
"2001::a/64 removed");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_2001_b_s_64)),
"2001::b/64 removed");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_2001_1_3_s_128)),
"2001:0:0:1::3/128 removed");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &pfx_2001_1_2_s_128)),
"2001:0:0:1::3/128 removed");
local_pfx.fp_len = 64;
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &local_pfx)),
"2001:0:0:1/64 removed");
local_pfx.fp_len = 128;
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &local_pfx)),
"2001:0:0:1::1/128 removed");
connected_pfx.fp_len = 64;
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &connected_pfx)),
"2001:0:0:2/64 removed");
connected_pfx.fp_len = 128;
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup_exact_match(fib_index, &connected_pfx)),
"2001:0:0:2::1/128 removed");
/*
* -8 entries. -7 path-lists (1 was shared).
*/
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
/*
* now remove the VRF
*/
fib_table_unlock(fib_index, FIB_PROTOCOL_IP6);
FIB_TEST((0 == fib_path_list_db_size()), "path list DB population:%d",
fib_path_list_db_size());
FIB_TEST((NPS-6 == fib_path_list_pool_size()), "path list pool size is%d",
fib_path_list_pool_size());
FIB_TEST((NPS-6 == fib_entry_pool_size()), "entry pool size is %d",
fib_entry_pool_size());
adj_unlock(ai_02);
adj_unlock(ai_01);
/*
* return the interfaces to up state
*/
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[0]->sw_if_index,
VNET_SW_INTERFACE_FLAG_ADMIN_UP);
error = vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[1]->sw_if_index,
VNET_SW_INTERFACE_FLAG_ADMIN_UP);
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
return (0);
}
/*
* Test Attached Exports
*/
static int
fib_test_ae (void)
{
const dpo_id_t *dpo, *dpo_drop;
const u32 fib_index = 0;
fib_node_index_t fei;
test_main_t *tm;
ip4_main_t *im;
tm = &test_main;
im = &ip4_main;
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
/*
* add interface routes. We'll assume this works. It's more rigorously
* tested elsewhere.
*/
fib_prefix_t local_pfx = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
/* 10.10.10.10 */
.as_u32 = clib_host_to_net_u32(0x0a0a0a0a),
},
},
};
vec_validate(im->fib_index_by_sw_if_index, tm->hw[0]->sw_if_index);
im->fib_index_by_sw_if_index[tm->hw[0]->sw_if_index] = fib_index;
dpo_drop = drop_dpo_get(DPO_PROTO_IP4);
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"attached interface route present");
local_pfx.fp_len = 32;
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"local interface route present");
/*
* Add an 2 ARP entry => a complete ADJ plus adj-fib.
*/
fib_prefix_t pfx_10_10_10_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.10.10.1 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a01),
},
};
fib_node_index_t ai;
fib_table_entry_update_one_path(fib_index,
&pfx_10_10_10_1_s_32,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 created");
ai = fib_entry_get_adj(fei);
/*
* create another FIB table into which routes will be imported
*/
u32 import_fib_index1;
import_fib_index1 = fib_table_find_or_create_and_lock(FIB_PROTOCOL_IP4, 11);
/*
* Add an attached route in the import FIB
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(import_fib_index1,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached export created");
/*
* check for the presence of the adj-fibs in the import table
*/
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 imported");
FIB_TEST((ai == fib_entry_get_adj(fei)),
"adj-fib1 Import uses same adj as export");
/*
* check for the presence of the local in the import table
*/
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local imported");
/*
* Add another adj-fin in the export table. Expect this
* to get magically exported;
*/
fib_prefix_t pfx_10_10_10_2_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.10.10.2 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a02),
},
};
fib_table_entry_update_one_path(fib_index,
&pfx_10_10_10_2_s_32,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_2_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 present");
ai = fib_entry_get_adj(fei);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 imported");
FIB_TEST((ai == fib_entry_get_adj(fei)),
"Import uses same adj as export");
FIB_TEST((FIB_ENTRY_FLAG_ATTACHED & fib_entry_get_flags(fei)),
"ADJ-fib2 imported flags %d",
fib_entry_get_flags(fei));
/*
* create a 2nd FIB table into which routes will be imported
*/
u32 import_fib_index2;
import_fib_index2 = fib_table_find_or_create_and_lock(FIB_PROTOCOL_IP4, 12);
/*
* Add an attached route in the import FIB
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(import_fib_index2,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached export created");
/*
* check for the presence of all the adj-fibs and local in the import table
*/
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 imported");
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 imported");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index2, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local imported");
/*
* add a 3rd adj-fib. expect it to be exported to both tables.
*/
fib_prefix_t pfx_10_10_10_3_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.10.10.3 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a03),
},
};
fib_table_entry_update_one_path(fib_index,
&pfx_10_10_10_3_s_32,
FIB_SOURCE_ADJ,
FIB_ENTRY_FLAG_ATTACHED,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_3_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib3 present");
ai = fib_entry_get_adj(fei);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib3 imported to FIB1");
FIB_TEST((ai == fib_entry_get_adj(fei)),
"Import uses same adj as export");
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib3 imported to FIB2");
FIB_TEST((ai == fib_entry_get_adj(fei)),
"Import uses same adj as export");
/*
* remove the 3rd adj fib. we expect it to be removed from both FIBs
*/
fib_table_entry_delete(fib_index,
&pfx_10_10_10_3_s_32,
FIB_SOURCE_ADJ);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib3 remved");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib3 removed from FIB1");
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_3_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib3 removed from FIB2");
/*
* remove the attached route from the 2nd FIB. expect the imported
* entires to be removed
*/
local_pfx.fp_len = 24;
fib_table_entry_delete(import_fib_index2,
&local_pfx,
FIB_SOURCE_API);
fei = fib_table_lookup_exact_match(import_fib_index2, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "attached export removed");
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib1 removed from FIB2");
fei = fib_table_lookup_exact_match(import_fib_index2, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib2 removed from FIB2");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index2, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "local removed from FIB2");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 still in FIB1");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 still in FIB1");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local still in FIB1");
/*
* modify the route in FIB1 so it is no longer attached. expect the imported
* entires to be removed
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(import_fib_index1,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_2_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib1 removed from FIB1");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib2 removed from FIB1");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "local removed from FIB1");
/*
* modify it back to attached. expect the adj-fibs back
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(import_fib_index1,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 imported in FIB1");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 imported in FIB1");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local imported in FIB1");
/*
* add a covering attached next-hop for the interface address, so we have
* a valid adj to find when we check the forwarding tables
*/
fib_prefix_t pfx_10_0_0_0_s_8 = {
.fp_len = 8,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
/* 10.0.0.0 */
.ip4.as_u32 = clib_host_to_net_u32(0x0a000000),
},
};
fei = fib_table_entry_update_one_path(fib_index,
&pfx_10_0_0_0_s_8,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_3_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
dpo = fib_entry_contribute_ip_forwarding(fei);
/*
* remove the route in the export fib. expect the adj-fibs to be removed
*/
local_pfx.fp_len = 24;
fib_table_entry_delete(fib_index,
&local_pfx,
FIB_SOURCE_INTERFACE);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "Delete export: ADJ-fib1 removed from FIB1");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib2 removed from FIB1");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "local removed from FIB1");
/*
* the adj-fibs in the export VRF are present in the FIB table,
* but not installed in forwarding, since they have no attached cover.
* Consequently a lookup in the MTRIE gives the adj for the covering
* route 10.0.0.0/8.
*/
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 in export");
index_t lbi;
lbi = ip4_fib_forwarding_lookup(fib_index, &pfx_10_10_10_1_s_32.fp_addr.ip4);
FIB_TEST(lbi == dpo->dpoi_index,
"10.10.10.1 forwards on \n%U not \n%U",
format_load_balance, lbi, 0,
format_dpo_id, dpo, 0);
lbi = ip4_fib_forwarding_lookup(fib_index, &pfx_10_10_10_2_s_32.fp_addr.ip4);
FIB_TEST(lbi == dpo->dpoi_index,
"10.10.10.2 forwards on %U", format_dpo_id, dpo, 0);
lbi = ip4_fib_forwarding_lookup(fib_index, &pfx_10_10_10_3_s_32.fp_addr.ip4);
FIB_TEST(lbi == dpo->dpoi_index,
"10.10.10.3 forwards on %U", format_dpo_id, dpo, 0);
/*
* add the export prefix back, but not as attached.
* No adj-fibs in export nor import tables
*/
local_pfx.fp_len = 24;
fei = fib_table_entry_update_one_path(fib_index,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_10_10_10_1_s_32.fp_addr,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
dpo = fib_entry_contribute_ip_forwarding(fei);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "non-attached in export: ADJ-fib1 in export");
lbi = ip4_fib_forwarding_lookup(fib_index, &pfx_10_10_10_1_s_32.fp_addr.ip4);
FIB_TEST(lbi == dpo->dpoi_index,
"10.10.10.1 forwards on %U", format_dpo_id, dpo, 0);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 in export");
lbi = ip4_fib_forwarding_lookup(fib_index, &pfx_10_10_10_2_s_32.fp_addr.ip4);
FIB_TEST(lbi == dpo->dpoi_index,
"10.10.10.2 forwards on %U", format_dpo_id, dpo, 0);
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib1 removed from FIB1");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "ADJ-fib2 removed from FIB1");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID == fei), "local removed from FIB1");
/*
* modify the export prefix so it is attached. expect all covereds to return
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(fib_index,
&local_pfx,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 reinstalled in export");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"Adj-fib1 is not drop in export");
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 reinstalled in export");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local reinstalled in export");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached in export: ADJ-fib1 imported");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"Adj-fib1 is not drop in export");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 imported");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 imported");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local imported");
/*
* modify the export prefix so connected. no change.
*/
local_pfx.fp_len = 24;
fib_table_entry_update_one_path(fib_index, &local_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib1 reinstalled in export");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"Adj-fib1 is not drop in export");
fei = fib_table_lookup_exact_match(fib_index, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 reinstalled in export");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(fib_index, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local reinstalled in export");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "attached in export: ADJ-fib1 imported");
dpo = fib_entry_contribute_ip_forwarding(fei);
FIB_TEST(dpo_cmp(dpo_drop, load_balance_get_bucket(dpo->dpoi_index, 0)),
"Adj-fib1 is not drop in export");
fei = fib_table_lookup_exact_match(import_fib_index1, &pfx_10_10_10_2_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "ADJ-fib2 imported");
local_pfx.fp_len = 32;
fei = fib_table_lookup_exact_match(import_fib_index1, &local_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "local imported");
/*
* CLEANUP
*/
fib_table_entry_delete(fib_index,
&pfx_10_0_0_0_s_8,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_10_10_10_1_s_32,
FIB_SOURCE_ADJ);
fib_table_entry_delete(fib_index,
&pfx_10_10_10_2_s_32,
FIB_SOURCE_ADJ);
local_pfx.fp_len = 32;
fib_table_entry_delete(fib_index,
&local_pfx,
FIB_SOURCE_INTERFACE);
local_pfx.fp_len = 24;
fib_table_entry_delete(fib_index,
&local_pfx,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&local_pfx,
FIB_SOURCE_INTERFACE);
local_pfx.fp_len = 24;
fib_table_entry_delete(import_fib_index1,
&local_pfx,
FIB_SOURCE_API);
fib_table_unlock(import_fib_index1, FIB_PROTOCOL_IP4);
fib_table_unlock(import_fib_index2, FIB_PROTOCOL_IP4);
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
return (0);
}
/*
* Test the recursive route route handling for GRE tunnels
*/
static int
fib_test_label (void)
{
fib_node_index_t fei, ai_mpls_10_10_10_1, ai_v4_10_10_11_1, ai_v4_10_10_11_2, ai_mpls_10_10_11_2, ai_mpls_10_10_11_1;
const u32 fib_index = 0;
test_main_t *tm;
ip4_main_t *im;
int lb_count, ii;
lb_count = pool_elts(load_balance_pool);
tm = &test_main;
im = &ip4_main;
/*
* add interface routes. We'll assume this works. It's more rigorously
* tested elsewhere.
*/
fib_prefix_t local0_pfx = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
/* 10.10.10.10 */
.as_u32 = clib_host_to_net_u32(0x0a0a0a0a),
},
},
};
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
vec_validate(im->fib_index_by_sw_if_index, tm->hw[0]->sw_if_index);
im->fib_index_by_sw_if_index[tm->hw[0]->sw_if_index] = fib_index;
fib_table_entry_update_one_path(fib_index, &local0_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local0_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"attached interface route present");
local0_pfx.fp_len = 32;
fib_table_entry_update_one_path(fib_index, &local0_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local0_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"local interface route present");
fib_prefix_t local1_pfx = {
.fp_len = 24,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4 = {
/* 10.10.11.10 */
.as_u32 = clib_host_to_net_u32(0x0a0a0b0a),
},
},
};
vec_validate(im->fib_index_by_sw_if_index, tm->hw[1]->sw_if_index);
im->fib_index_by_sw_if_index[tm->hw[1]->sw_if_index] = fib_index;
fib_table_entry_update_one_path(fib_index, &local1_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_ATTACHED),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[1]->sw_if_index,
~0,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local1_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"attached interface route present");
local1_pfx.fp_len = 32;
fib_table_entry_update_one_path(fib_index, &local1_pfx,
FIB_SOURCE_INTERFACE,
(FIB_ENTRY_FLAG_CONNECTED |
FIB_ENTRY_FLAG_LOCAL),
FIB_PROTOCOL_IP4,
NULL,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup_exact_match(fib_index, &local1_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei),
"local interface route present");
ip46_address_t nh_10_10_10_1 = {
.ip4 = {
.as_u32 = clib_host_to_net_u32(0x0a0a0a01),
},
};
ip46_address_t nh_10_10_11_1 = {
.ip4 = {
.as_u32 = clib_host_to_net_u32(0x0a0a0b01),
},
};
ip46_address_t nh_10_10_11_2 = {
.ip4 = {
.as_u32 = clib_host_to_net_u32(0x0a0a0b02),
},
};
ai_v4_10_10_11_1 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index);
ai_v4_10_10_11_2 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_IP4,
&nh_10_10_11_2,
tm->hw[1]->sw_if_index);
ai_mpls_10_10_10_1 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_MPLS,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index);
ai_mpls_10_10_11_2 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_MPLS,
&nh_10_10_11_2,
tm->hw[1]->sw_if_index);
ai_mpls_10_10_11_1 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_MPLS,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index);
/*
* Add an etry with one path with a real out-going label
*/
fib_prefix_t pfx_1_1_1_1_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010101),
},
};
fib_test_lb_bucket_t l99_eos_o_10_10_10_1 = {
.type = FT_LB_LABEL_O_ADJ,
.label_o_adj = {
.adj = ai_mpls_10_10_10_1,
.label = 99,
.eos = MPLS_EOS,
},
};
fib_test_lb_bucket_t l99_neos_o_10_10_10_1 = {
.type = FT_LB_LABEL_O_ADJ,
.label_o_adj = {
.adj = ai_mpls_10_10_10_1,
.label = 99,
.eos = MPLS_NON_EOS,
},
};
mpls_label_t *l99 = NULL;
vec_add1(l99, 99);
fib_table_entry_update_one_path(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
l99,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST((FIB_NODE_INDEX_INVALID != fei), "1.1.1.1/32 created");
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&l99_eos_o_10_10_10_1),
"1.1.1.1/32 LB 1 bucket via label 99 over 10.10.10.1");
/*
* add a path with an implicit NULL label
*/
fib_test_lb_bucket_t a_o_10_10_11_1 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_v4_10_10_11_1,
},
};
fib_test_lb_bucket_t a_mpls_o_10_10_11_1 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_mpls_10_10_11_1,
},
};
mpls_label_t *l_imp_null = NULL;
vec_add1(l_imp_null, MPLS_IETF_IMPLICIT_NULL_LABEL);
fei = fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
l_imp_null,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&l99_eos_o_10_10_10_1,
&a_o_10_10_11_1),
"1.1.1.1/32 LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.1");
/*
* assign the route a local label
*/
fib_table_entry_local_label_add(fib_index,
&pfx_1_1_1_1_s_32,
24001);
fib_prefix_t pfx_24001_eos = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_label = 24001,
.fp_eos = MPLS_EOS,
};
fib_prefix_t pfx_24001_neos = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_label = 24001,
.fp_eos = MPLS_NON_EOS,
};
/*
* The EOS entry should link to both the paths,
* and use an ip adj for the imp-null
* The NON-EOS entry should link to both the paths,
* and use an mpls adj for the imp-null
*/
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
2,
&l99_eos_o_10_10_10_1,
&a_o_10_10_11_1),
"24001/eos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.1");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
2,
&l99_neos_o_10_10_10_1,
&a_mpls_o_10_10_11_1),
"24001/neos LB 1 bucket via: "
"label 99 over 10.10.10.1 ",
"mpls-adj via 10.10.11.1");
/*
* add an unlabelled path, this is excluded from the neos chains,
*/
fib_test_lb_bucket_t adj_o_10_10_11_2 = {
.type = FT_LB_ADJ,
.adj = {
.adj = ai_v4_10_10_11_2,
},
};
fei = fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_11_2,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
16, // 3 choices spread over 16 buckets
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 16 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.1",
"adj over 10.10.11.2");
/*
* get and lock a reference to the non-eos of the via entry 1.1.1.1/32
*/
dpo_id_t non_eos_1_1_1_1 = DPO_INVALID;
fib_entry_contribute_forwarding(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
&non_eos_1_1_1_1);
/*
* n-eos has only the 2 labelled paths
*/
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
2,
&l99_neos_o_10_10_10_1,
&a_mpls_o_10_10_11_1),
"24001/neos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj-mpls over 10.10.11.2");
/*
* A labelled recursive
*/
fib_prefix_t pfx_2_2_2_2_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020202),
},
};
fib_test_lb_bucket_t l1600_eos_o_1_1_1_1 = {
.type = FT_LB_LABEL_O_LB,
.label_o_lb = {
.lb = non_eos_1_1_1_1.dpoi_index,
.label = 1600,
.eos = MPLS_EOS,
},
};
mpls_label_t *l1600 = NULL;
vec_add1(l1600, 1600);
fib_table_entry_update_one_path(fib_index,
&pfx_2_2_2_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0,
fib_index,
1,
l1600,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2_2_2_2_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&l1600_eos_o_1_1_1_1),
"2.2.2.2.2/32 LB 1 buckets via: "
"label 1600 over 1.1.1.1");
dpo_id_t dpo_44 = DPO_INVALID;
index_t urpfi;
fib_entry_contribute_forwarding(fei, FIB_FORW_CHAIN_TYPE_UNICAST_IP4, &dpo_44);
urpfi = load_balance_get_urpf(dpo_44.dpoi_index);
FIB_TEST(fib_urpf_check(urpfi, tm->hw[0]->sw_if_index),
"uRPF check for 2.2.2.2/32 on %d OK",
tm->hw[0]->sw_if_index);
FIB_TEST(fib_urpf_check(urpfi, tm->hw[1]->sw_if_index),
"uRPF check for 2.2.2.2/32 on %d OK",
tm->hw[1]->sw_if_index);
FIB_TEST(!fib_urpf_check(urpfi, 99),
"uRPF check for 2.2.2.2/32 on 99 not-OK",
99);
fib_entry_contribute_forwarding(fei, FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS, &dpo_44);
FIB_TEST(urpfi == load_balance_get_urpf(dpo_44.dpoi_index),
"Shared uRPF on IP and non-EOS chain");
dpo_reset(&dpo_44);
/*
* we are holding a lock on the non-eos LB of the via-entry.
* do a PIC-core failover by shutting the link of the via-entry.
*
* shut down the link with the valid label
*/
vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[0]->sw_if_index,
0);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&a_o_10_10_11_1,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 2 buckets via: "
"adj over 10.10.11.1, ",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
2,
&a_o_10_10_11_1,
&adj_o_10_10_11_2),
"24001/eos LB 2 buckets via: "
"adj over 10.10.11.1, ",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&a_mpls_o_10_10_11_1),
"24001/neos LB 1 buckets via: "
"adj-mpls over 10.10.11.2");
/*
* test that the pre-failover load-balance has been in-place
* modified
*/
dpo_id_t current = DPO_INVALID;
fib_entry_contribute_forwarding(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
¤t);
FIB_TEST(!dpo_cmp(&non_eos_1_1_1_1,
¤t),
"PIC-core LB inplace modified %U %U",
format_dpo_id, &non_eos_1_1_1_1, 0,
format_dpo_id, ¤t, 0);
dpo_reset(&non_eos_1_1_1_1);
dpo_reset(¤t);
/*
* no-shut the link with the valid label
*/
vnet_sw_interface_set_flags(vnet_get_main(),
tm->hw[0]->sw_if_index,
VNET_SW_INTERFACE_FLAG_ADMIN_UP);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
16, // 3 choices spread over 16 buckets
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 16 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.1",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
16, // 3 choices spread over 16 buckets
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&l99_eos_o_10_10_10_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&a_o_10_10_11_1,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2,
&adj_o_10_10_11_2),
"24001/eos LB 16 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.1",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
2,
&l99_neos_o_10_10_10_1,
&a_mpls_o_10_10_11_1),
"24001/neos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj-mpls over 10.10.11.2");
/*
* remove the first path with the valid label
*/
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&a_o_10_10_11_1,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 2 buckets via: "
"adj over 10.10.11.1",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
2,
&a_o_10_10_11_1,
&adj_o_10_10_11_2),
"24001/eos LB 2 buckets via: "
"adj over 10.10.11.1",
"adj-v4 over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&a_mpls_o_10_10_11_1),
"24001/neos LB 1 buckets via: "
"adj-mpls over 10.10.11.2");
/*
* remove the other path with a valid label
*/
fib_test_lb_bucket_t bucket_drop = {
.type = FT_LB_SPECIAL,
.special = {
.adj = DPO_PROTO_IP4,
},
};
fib_table_entry_path_remove(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_PROTOCOL_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 1 buckets via: "
"adj over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
1,
&adj_o_10_10_11_2),
"24001/eos LB 1 buckets via: "
"adj over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&bucket_drop),
"24001/eos LB 1 buckets via: DROP");
/*
* add back the path with the valid label
*/
l99 = NULL;
vec_add1(l99, 99);
fib_table_entry_path_add(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
l99,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&l99_eos_o_10_10_10_1,
&adj_o_10_10_11_2),
"1.1.1.1/32 LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
2,
&l99_eos_o_10_10_10_1,
&adj_o_10_10_11_2),
"24001/eos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_24001_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&l99_neos_o_10_10_10_1),
"24001/neos LB 1 buckets via: "
"label 99 over 10.10.10.1");
/*
* change the local label
*/
fib_table_entry_local_label_add(fib_index,
&pfx_1_1_1_1_s_32,
25005);
fib_prefix_t pfx_25005_eos = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_label = 25005,
.fp_eos = MPLS_EOS,
};
fib_prefix_t pfx_25005_neos = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_label = 25005,
.fp_eos = MPLS_NON_EOS,
};
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup(fib_index, &pfx_24001_eos)),
"24001/eos removed after label change");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
fib_table_lookup(fib_index, &pfx_24001_neos)),
"24001/eos removed after label change");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_25005_eos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
2,
&l99_eos_o_10_10_10_1,
&adj_o_10_10_11_2),
"25005/eos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.2");
fei = fib_table_lookup(MPLS_FIB_DEFAULT_TABLE_ID,
&pfx_25005_neos);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&l99_neos_o_10_10_10_1),
"25005/neos LB 1 buckets via: "
"label 99 over 10.10.10.1");
/*
* remove the local label.
* the check that the MPLS entries are gone is done by the fact the
* MPLS table is no longer present.
*/
fib_table_entry_local_label_remove(fib_index,
&pfx_1_1_1_1_s_32,
25005);
fei = fib_table_lookup(fib_index, &pfx_1_1_1_1_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&l99_eos_o_10_10_10_1,
&adj_o_10_10_11_2),
"24001/eos LB 2 buckets via: "
"label 99 over 10.10.10.1, "
"adj over 10.10.11.2");
FIB_TEST((FIB_NODE_INDEX_INVALID ==
mpls_fib_index_from_table_id(MPLS_FIB_DEFAULT_TABLE_ID)),
"No more MPLS FIB entries => table removed");
/*
* add another via-entry for the recursive
*/
fib_prefix_t pfx_1_1_1_2_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x01010102),
},
};
fib_test_lb_bucket_t l101_eos_o_10_10_10_1 = {
.type = FT_LB_LABEL_O_ADJ,
.label_o_adj = {
.adj = ai_mpls_10_10_10_1,
.label = 101,
.eos = MPLS_EOS,
},
};
mpls_label_t *l101 = NULL;
vec_add1(l101, 101);
fei = fib_table_entry_update_one_path(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
l101,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&l101_eos_o_10_10_10_1),
"1.1.1.2/32 LB 1 buckets via: "
"label 101 over 10.10.10.1");
dpo_id_t non_eos_1_1_1_2 = DPO_INVALID;
fib_entry_contribute_forwarding(fib_table_lookup(fib_index,
&pfx_1_1_1_1_s_32),
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
&non_eos_1_1_1_1);
fib_entry_contribute_forwarding(fib_table_lookup(fib_index,
&pfx_1_1_1_2_s_32),
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
&non_eos_1_1_1_2);
fib_test_lb_bucket_t l1601_eos_o_1_1_1_2 = {
.type = FT_LB_LABEL_O_LB,
.label_o_lb = {
.lb = non_eos_1_1_1_2.dpoi_index,
.label = 1601,
.eos = MPLS_EOS,
},
};
mpls_label_t *l1601 = NULL;
vec_add1(l1601, 1601);
l1600_eos_o_1_1_1_1.label_o_lb.lb = non_eos_1_1_1_1.dpoi_index;
fei = fib_table_entry_path_add(fib_index,
&pfx_2_2_2_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_2_s_32.fp_addr,
~0,
fib_index,
1,
l1601,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&l1600_eos_o_1_1_1_1,
&l1601_eos_o_1_1_1_2),
"2.2.2.2/32 LB 2 buckets via: "
"label 1600 via 1.1,1.1, "
"label 16001 via 1.1.1.2");
/*
* update the via-entry so it no longer has an imp-null path.
* the LB for the recursive can use an imp-null
*/
l_imp_null = NULL;
vec_add1(l_imp_null, MPLS_IETF_IMPLICIT_NULL_LABEL);
fei = fib_table_entry_update_one_path(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
l_imp_null,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&a_o_10_10_11_1),
"1.1.1.2/32 LB 1 buckets via: "
"adj 10.10.11.1");
fei = fib_table_lookup(fib_index, &pfx_2_2_2_2_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
2,
&l1600_eos_o_1_1_1_1,
&l1601_eos_o_1_1_1_2),
"2.2.2.2/32 LB 2 buckets via: "
"label 1600 via 1.1,1.1, "
"label 16001 via 1.1.1.2");
/*
* update the via-entry so it no longer has labelled paths.
* the LB for the recursive should exclue this via form its LB
*/
fei = fib_table_entry_update_one_path(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&a_o_10_10_11_1),
"1.1.1.2/32 LB 1 buckets via: "
"adj 10.10.11.1");
fei = fib_table_lookup(fib_index, &pfx_2_2_2_2_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&l1600_eos_o_1_1_1_1),
"2.2.2.2/32 LB 1 buckets via: "
"label 1600 via 1.1,1.1");
dpo_reset(&non_eos_1_1_1_1);
dpo_reset(&non_eos_1_1_1_2);
/*
* Add a recursive with no out-labels. We expect to use the IP of the via
*/
fib_prefix_t pfx_2_2_2_3_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020203),
},
};
dpo_id_t ip_1_1_1_1 = DPO_INVALID;
fib_table_entry_update_one_path(fib_index,
&pfx_2_2_2_3_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fib_entry_contribute_forwarding(fib_table_lookup(fib_index,
&pfx_1_1_1_1_s_32),
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
&ip_1_1_1_1);
fib_test_lb_bucket_t ip_o_1_1_1_1 = {
.type = FT_LB_O_LB,
.lb = {
.lb = ip_1_1_1_1.dpoi_index,
},
};
fei = fib_table_lookup(fib_index, &pfx_2_2_2_3_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_o_1_1_1_1),
"2.2.2.2.3/32 LB 1 buckets via: "
"ip 1.1.1.1");
/*
* Add a recursive with an imp-null out-label.
* We expect to use the IP of the via
*/
fib_prefix_t pfx_2_2_2_4_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020204),
},
};
fib_table_entry_update_one_path(fib_index,
&pfx_2_2_2_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&pfx_1_1_1_1_s_32.fp_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
fei = fib_table_lookup(fib_index, &pfx_2_2_2_4_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_o_1_1_1_1),
"2.2.2.2.4/32 LB 1 buckets via: "
"ip 1.1.1.1");
dpo_reset(&ip_1_1_1_1);
/*
* Create an entry with a deep label stack
*/
fib_prefix_t pfx_2_2_5_5_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020505),
},
};
fib_test_lb_bucket_t ls_eos_o_10_10_10_1 = {
.type = FT_LB_LABEL_STACK_O_ADJ,
.label_stack_o_adj = {
.adj = ai_mpls_10_10_11_1,
.label_stack_size = 8,
.label_stack = {
200, 201, 202, 203, 204, 205, 206, 207
},
.eos = MPLS_EOS,
},
};
mpls_label_t *label_stack = NULL;
vec_validate(label_stack, 7);
for (ii = 0; ii < 8; ii++)
{
label_stack[ii] = ii + 200;
}
fei = fib_table_entry_update_one_path(fib_index,
&pfx_2_2_5_5_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_11_1,
tm->hw[1]->sw_if_index,
~0, // invalid fib index
1,
label_stack,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ls_eos_o_10_10_10_1),
"2.2.5.5/32 LB 1 buckets via: "
"adj 10.10.11.1");
fib_table_entry_delete_index(fei, FIB_SOURCE_API);
/*
* cleanup
*/
fib_table_entry_delete(fib_index,
&pfx_1_1_1_2_s_32,
FIB_SOURCE_API);
fei = fib_table_lookup(fib_index, &pfx_2_2_2_2_s_32);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&l1600_eos_o_1_1_1_1),
"2.2.2.2/32 LB 1 buckets via: "
"label 1600 via 1.1,1.1");
fib_table_entry_delete(fib_index,
&pfx_1_1_1_1_s_32,
FIB_SOURCE_API);
FIB_TEST(fib_test_validate_entry(fei,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&bucket_drop),
"2.2.2.2/32 LB 1 buckets via: DROP");
fib_table_entry_delete(fib_index,
&pfx_2_2_2_2_s_32,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_2_2_2_3_s_32,
FIB_SOURCE_API);
fib_table_entry_delete(fib_index,
&pfx_2_2_2_4_s_32,
FIB_SOURCE_API);
adj_unlock(ai_mpls_10_10_10_1);
adj_unlock(ai_mpls_10_10_11_2);
adj_unlock(ai_v4_10_10_11_1);
adj_unlock(ai_v4_10_10_11_2);
adj_unlock(ai_mpls_10_10_11_1);
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
local0_pfx.fp_len = 32;
fib_table_entry_delete(fib_index,
&local0_pfx,
FIB_SOURCE_INTERFACE);
local0_pfx.fp_len = 24;
fib_table_entry_delete(fib_index,
&local0_pfx,
FIB_SOURCE_INTERFACE);
local1_pfx.fp_len = 32;
fib_table_entry_delete(fib_index,
&local1_pfx,
FIB_SOURCE_INTERFACE);
local1_pfx.fp_len = 24;
fib_table_entry_delete(fib_index,
&local1_pfx,
FIB_SOURCE_INTERFACE);
/*
* +1 for the drop LB in the MPLS tables.
*/
FIB_TEST(lb_count+1 == pool_elts(load_balance_pool),
"Load-balance resources freed %d of %d",
lb_count+1, pool_elts(load_balance_pool));
return (0);
}
#define N_TEST_CHILDREN 4
#define PARENT_INDEX 0
typedef struct fib_node_test_t_
{
fib_node_t node;
u32 sibling;
u32 index;
fib_node_back_walk_ctx_t *ctxs;
u32 destroyed;
} fib_node_test_t;
static fib_node_test_t fib_test_nodes[N_TEST_CHILDREN+1];
#define PARENT() (&fib_test_nodes[PARENT_INDEX].node)
#define FOR_EACH_TEST_CHILD(_tc) \
for (ii = 1, (_tc) = &fib_test_nodes[1]; \
ii < N_TEST_CHILDREN+1; \
ii++, (_tc) = &fib_test_nodes[ii])
static fib_node_t *
fib_test_child_get_node (fib_node_index_t index)
{
return (&fib_test_nodes[index].node);
}
static int fib_test_walk_spawns_walks;
static fib_node_back_walk_rc_t
fib_test_child_back_walk_notify (fib_node_t *node,
fib_node_back_walk_ctx_t *ctx)
{
fib_node_test_t *tc = (fib_node_test_t*) node;
vec_add1(tc->ctxs, *ctx);
if (1 == fib_test_walk_spawns_walks)
fib_walk_sync(FIB_NODE_TYPE_TEST, tc->index, ctx);
if (2 == fib_test_walk_spawns_walks)
fib_walk_async(FIB_NODE_TYPE_TEST, tc->index,
FIB_WALK_PRIORITY_HIGH, ctx);
return (FIB_NODE_BACK_WALK_CONTINUE);
}
static void
fib_test_child_last_lock_gone (fib_node_t *node)
{
fib_node_test_t *tc = (fib_node_test_t *)node;
tc->destroyed = 1;
}
/**
* The FIB walk's graph node virtual function table
*/
static const fib_node_vft_t fib_test_child_vft = {
.fnv_get = fib_test_child_get_node,
.fnv_last_lock = fib_test_child_last_lock_gone,
.fnv_back_walk = fib_test_child_back_walk_notify,
};
/*
* the function (that should have been static but isn't so I can do this)
* that processes the walk from the async queue,
*/
f64 fib_walk_process_queues(vlib_main_t * vm,
const f64 quota);
u32 fib_walk_queue_get_size(fib_walk_priority_t prio);
static int
fib_test_walk (void)
{
fib_node_back_walk_ctx_t high_ctx = {}, low_ctx = {};
fib_node_test_t *tc;
vlib_main_t *vm;
u32 ii;
vm = vlib_get_main();
fib_node_register_type(FIB_NODE_TYPE_TEST, &fib_test_child_vft);
/*
* init a fake node on which we will add children
*/
fib_node_init(&fib_test_nodes[PARENT_INDEX].node,
FIB_NODE_TYPE_TEST);
FOR_EACH_TEST_CHILD(tc)
{
fib_node_init(&tc->node, FIB_NODE_TYPE_TEST);
fib_node_lock(&tc->node);
tc->ctxs = NULL;
tc->index = ii;
tc->sibling = fib_node_child_add(FIB_NODE_TYPE_TEST,
PARENT_INDEX,
FIB_NODE_TYPE_TEST, ii);
}
/*
* enqueue a walk across the parents children.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
FIB_TEST(N_TEST_CHILDREN+1 == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children pre-walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* give the walk a large amount of time so it gets to the end
*/
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is empty post walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* walk again. should be no increase in the number of visits, since
* the walk will have terminated.
*/
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
FIB_TEST(0 == vec_len(tc->ctxs),
"%d child visitsed %d times",
ii, vec_len(tc->ctxs));
}
/*
* schedule a low and hig priority walk. expect the high to be performed
* before the low.
* schedule the high prio walk first so that it is further from the head
* of the dependency list. that way it won't merge with the low one.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
low_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_ADJ_UPDATE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_LOW, &low_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
FIB_TEST(high_ctx.fnbw_reason == tc->ctxs[0].fnbw_reason,
"%d child visitsed by high prio walk", ii);
FIB_TEST(low_ctx.fnbw_reason == tc->ctxs[1].fnbw_reason,
"%d child visitsed by low prio walk", ii);
vec_free(tc->ctxs);
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is empty post prio walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post prio walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* schedule 2 walks of the same priority that can be megred.
* expect that each child is thus visited only once.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
low_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &low_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times during merge walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is empty post merge walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post merge walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* schedule 2 walks of the same priority that cannot be megred.
* expect that each child is thus visited twice and in the order
* in which the walks were scheduled.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
low_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_ADJ_UPDATE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &low_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
FIB_TEST(high_ctx.fnbw_reason == tc->ctxs[0].fnbw_reason,
"%d child visitsed by high prio walk", ii);
FIB_TEST(low_ctx.fnbw_reason == tc->ctxs[1].fnbw_reason,
"%d child visitsed by low prio walk", ii);
vec_free(tc->ctxs);
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is empty post no-merge walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post no-merge walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* schedule a walk that makes one one child progress.
* we do this by giving the queue draining process zero
* time quanta. it's a do..while loop, so it does something.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_process_queues(vm, 0);
FOR_EACH_TEST_CHILD(tc)
{
if (ii == N_TEST_CHILDREN)
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times in zero quanta walk",
ii, vec_len(tc->ctxs));
}
else
{
FIB_TEST(0 == vec_len(tc->ctxs),
"%d child visitsed %d times in 0 quanta walk",
ii, vec_len(tc->ctxs));
}
}
FIB_TEST(1 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is not empty post zero quanta walk");
FIB_TEST(N_TEST_CHILDREN+1 == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post zero qunta walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* another one step
*/
fib_walk_process_queues(vm, 0);
FOR_EACH_TEST_CHILD(tc)
{
if (ii >= N_TEST_CHILDREN-1)
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times in 2nd zero quanta walk",
ii, vec_len(tc->ctxs));
}
else
{
FIB_TEST(0 == vec_len(tc->ctxs),
"%d child visitsed %d times in 2nd 0 quanta walk",
ii, vec_len(tc->ctxs));
}
}
FIB_TEST(1 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is not empty post zero quanta walk");
FIB_TEST(N_TEST_CHILDREN+1 == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post zero qunta walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* schedule another walk that will catch-up and merge.
*/
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
if (ii >= N_TEST_CHILDREN-1)
{
FIB_TEST(2 == vec_len(tc->ctxs),
"%d child visitsed %d times in 2nd zero quanta merge walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
else
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times in 2nd 0 quanta merge walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is not empty post 2nd zero quanta merge walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post 2nd zero qunta merge walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* park a async walk in the middle of the list, then have an sync walk catch
* it. same expectations as async catches async.
*/
high_ctx.fnbw_reason = FIB_NODE_BW_REASON_FLAG_RESOLVE;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_process_queues(vm, 0);
fib_walk_process_queues(vm, 0);
fib_walk_sync(FIB_NODE_TYPE_TEST, PARENT_INDEX, &high_ctx);
FOR_EACH_TEST_CHILD(tc)
{
if (ii >= N_TEST_CHILDREN-1)
{
FIB_TEST(2 == vec_len(tc->ctxs),
"%d child visitsed %d times in sync catches async walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
else
{
FIB_TEST(1 == vec_len(tc->ctxs),
"%d child visitsed %d times in sync catches async walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
}
FIB_TEST(0 == fib_walk_queue_get_size(FIB_WALK_PRIORITY_HIGH),
"Queue is not empty post 2nd zero quanta merge walk");
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post 2nd zero qunta merge walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* make the parent a child of one of its children, thus inducing a routing loop.
*/
fib_test_nodes[PARENT_INDEX].sibling =
fib_node_child_add(FIB_NODE_TYPE_TEST,
1, // the first child
FIB_NODE_TYPE_TEST,
PARENT_INDEX);
/*
* execute a sync walk from the parent. each child visited spawns more sync
* walks. we expect the walk to terminate.
*/
fib_test_walk_spawns_walks = 1;
fib_walk_sync(FIB_NODE_TYPE_TEST, PARENT_INDEX, &high_ctx);
FOR_EACH_TEST_CHILD(tc)
{
/*
* child 1 - which is last in the list - has the loop.
* the other children a re thus visitsed first. the we meet
* child 1. we go round the loop again, visting the other children.
* then we meet the walk in the dep list and bail. child 1 is not visitsed
* again.
*/
if (1 == ii)
{
FIB_TEST(1 == vec_len(tc->ctxs),
"child %d visitsed %d times during looped sync walk",
ii, vec_len(tc->ctxs));
}
else
{
FIB_TEST(2 == vec_len(tc->ctxs),
"child %d visitsed %d times during looped sync walk",
ii, vec_len(tc->ctxs));
}
vec_free(tc->ctxs);
}
FIB_TEST(N_TEST_CHILDREN == fib_node_list_get_size(PARENT()->fn_children),
"Parent has %d children post sync loop walk",
fib_node_list_get_size(PARENT()->fn_children));
/*
* the walk doesn't reach the max depth because the infra knows that sync
* meets sync implies a loop and bails early.
*/
FIB_TEST(high_ctx.fnbw_depth == 9,
"Walk context depth %d post sync loop walk",
high_ctx.fnbw_depth);
/*
* execute an async walk of the graph loop, with each child spawns sync walks
*/
high_ctx.fnbw_depth = 0;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
/*
* we don't really care how many times the children are visisted, as long as
* it is more than once.
*/
FIB_TEST(1 <= vec_len(tc->ctxs),
"child %d visitsed %d times during looped aync spawns sync walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
/*
* execute an async walk of the graph loop, with each child spawns async walks
*/
fib_test_walk_spawns_walks = 2;
high_ctx.fnbw_depth = 0;
fib_walk_async(FIB_NODE_TYPE_TEST, PARENT_INDEX,
FIB_WALK_PRIORITY_HIGH, &high_ctx);
fib_walk_process_queues(vm, 1);
FOR_EACH_TEST_CHILD(tc)
{
/*
* we don't really care how many times the children are visisted, as long as
* it is more than once.
*/
FIB_TEST(1 <= vec_len(tc->ctxs),
"child %d visitsed %d times during looped async spawns async walk",
ii, vec_len(tc->ctxs));
vec_free(tc->ctxs);
}
fib_node_child_remove(FIB_NODE_TYPE_TEST,
1, // the first child
fib_test_nodes[PARENT_INDEX].sibling);
/*
* cleanup
*/
FOR_EACH_TEST_CHILD(tc)
{
fib_node_child_remove(FIB_NODE_TYPE_TEST, PARENT_INDEX,
tc->sibling);
fib_node_deinit(&tc->node);
fib_node_unlock(&tc->node);
}
fib_node_deinit(PARENT());
/*
* The parent will be destroyed when the last lock on it goes.
* this test ensures all the walk objects are unlocking it.
*/
FIB_TEST((1 == fib_test_nodes[PARENT_INDEX].destroyed),
"Parent was destroyed");
return (0);
}
static int
lfib_test (void)
{
const mpls_label_t deag_label = 50;
const u32 lfib_index = 0;
const u32 fib_index = 0;
dpo_id_t dpo = DPO_INVALID;
const dpo_id_t *dpo1;
fib_node_index_t lfe;
lookup_dpo_t *lkd;
test_main_t *tm;
int lb_count;
adj_index_t ai_mpls_10_10_10_1;
tm = &test_main;
lb_count = pool_elts(load_balance_pool);
FIB_TEST((0 == adj_nbr_db_size()), "ADJ DB size is %d",
adj_nbr_db_size());
/*
* MPLS enable an interface so we get the MPLS table created
*/
mpls_sw_interface_enable_disable(&mpls_main,
tm->hw[0]->sw_if_index,
1);
ip46_address_t nh_10_10_10_1 = {
.ip4.as_u32 = clib_host_to_net_u32(0x0a0a0a01),
};
ai_mpls_10_10_10_1 = adj_nbr_add_or_lock(FIB_PROTOCOL_IP4,
VNET_LINK_MPLS,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index);
/*
* Test the specials stack properly.
*/
fib_prefix_t exp_null_v6_pfx = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_eos = MPLS_EOS,
.fp_label = MPLS_IETF_IPV6_EXPLICIT_NULL_LABEL,
.fp_payload_proto = DPO_PROTO_IP6,
};
lfe = fib_table_lookup(lfib_index, &exp_null_v6_pfx);
FIB_TEST((FIB_NODE_INDEX_INVALID != lfe),
"%U/%U present",
format_mpls_unicast_label, MPLS_IETF_IPV6_EXPLICIT_NULL_LABEL,
format_mpls_eos_bit, MPLS_EOS);
fib_entry_contribute_forwarding(lfe,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
&dpo);
dpo1 = load_balance_get_bucket(dpo.dpoi_index, 0);
lkd = lookup_dpo_get(dpo1->dpoi_index);
FIB_TEST((fib_index == lkd->lkd_fib_index),
"%U/%U is deag in %d %U",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS,
lkd->lkd_fib_index,
format_dpo_id, &dpo, 0);
FIB_TEST((LOOKUP_INPUT_DST_ADDR == lkd->lkd_input),
"%U/%U is dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
FIB_TEST((LOOKUP_TABLE_FROM_INPUT_INTERFACE == lkd->lkd_table),
"%U/%U is lookup in interface's table",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
FIB_TEST((DPO_PROTO_IP6 == lkd->lkd_proto),
"%U/%U is %U dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS,
format_dpo_proto, lkd->lkd_proto);
/*
* A route deag route for EOS
*/
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_eos = MPLS_EOS,
.fp_label = deag_label,
.fp_payload_proto = DPO_PROTO_IP4,
};
lfe = fib_table_entry_path_add(lfib_index,
&pfx,
FIB_SOURCE_CLI,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&zero_addr,
~0,
fib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((lfe == fib_table_lookup(lfib_index, &pfx)),
"%U/%U present",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
fib_entry_contribute_forwarding(lfe,
FIB_FORW_CHAIN_TYPE_MPLS_EOS,
&dpo);
dpo1 = load_balance_get_bucket(dpo.dpoi_index, 0);
lkd = lookup_dpo_get(dpo1->dpoi_index);
FIB_TEST((fib_index == lkd->lkd_fib_index),
"%U/%U is deag in %d %U",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS,
lkd->lkd_fib_index,
format_dpo_id, &dpo, 0);
FIB_TEST((LOOKUP_INPUT_DST_ADDR == lkd->lkd_input),
"%U/%U is dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
FIB_TEST((DPO_PROTO_IP4 == lkd->lkd_proto),
"%U/%U is %U dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS,
format_dpo_proto, lkd->lkd_proto);
fib_table_entry_delete_index(lfe, FIB_SOURCE_CLI);
FIB_TEST((FIB_NODE_INDEX_INVALID == fib_table_lookup(lfib_index,
&pfx)),
"%U/%U not present",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
/*
* A route deag route for non-EOS
*/
pfx.fp_eos = MPLS_NON_EOS;
lfe = fib_table_entry_path_add(lfib_index,
&pfx,
FIB_SOURCE_CLI,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&zero_addr,
~0,
lfib_index,
1,
NULL,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST((lfe == fib_table_lookup(lfib_index, &pfx)),
"%U/%U present",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_NON_EOS);
fib_entry_contribute_forwarding(lfe,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
&dpo);
dpo1 = load_balance_get_bucket(dpo.dpoi_index, 0);
lkd = lookup_dpo_get(dpo1->dpoi_index);
FIB_TEST((fib_index == lkd->lkd_fib_index),
"%U/%U is deag in %d %U",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_NON_EOS,
lkd->lkd_fib_index,
format_dpo_id, &dpo, 0);
FIB_TEST((LOOKUP_INPUT_DST_ADDR == lkd->lkd_input),
"%U/%U is dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_NON_EOS);
FIB_TEST((DPO_PROTO_MPLS == lkd->lkd_proto),
"%U/%U is %U dst deag",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_NON_EOS,
format_dpo_proto, lkd->lkd_proto);
fib_table_entry_delete_index(lfe, FIB_SOURCE_CLI);
FIB_TEST((FIB_NODE_INDEX_INVALID == fib_table_lookup(lfib_index,
&pfx)),
"%U/%U not present",
format_mpls_unicast_label, deag_label,
format_mpls_eos_bit, MPLS_EOS);
dpo_reset(&dpo);
/*
* An MPLS x-connect
*/
fib_prefix_t pfx_1200 = {
.fp_len = 21,
.fp_proto = FIB_PROTOCOL_MPLS,
.fp_label = 1200,
.fp_eos = MPLS_NON_EOS,
};
fib_test_lb_bucket_t neos_o_10_10_10_1 = {
.type = FT_LB_LABEL_STACK_O_ADJ,
.label_stack_o_adj = {
.adj = ai_mpls_10_10_10_1,
.label_stack_size = 4,
.label_stack = {
200, 300, 400, 500,
},
.eos = MPLS_NON_EOS,
},
};
dpo_id_t neos_1200 = DPO_INVALID;
dpo_id_t ip_1200 = DPO_INVALID;
mpls_label_t *l200 = NULL;
vec_add1(l200, 200);
vec_add1(l200, 300);
vec_add1(l200, 400);
vec_add1(l200, 500);
lfe = fib_table_entry_update_one_path(fib_index,
&pfx_1200,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
FIB_PROTOCOL_IP4,
&nh_10_10_10_1,
tm->hw[0]->sw_if_index,
~0, // invalid fib index
1,
l200,
FIB_ROUTE_PATH_FLAG_NONE);
FIB_TEST(fib_test_validate_entry(lfe,
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
1,
&neos_o_10_10_10_1),
"1200/0 LB 1 buckets via: "
"adj 10.10.11.1");
/*
* A recursive route via the MPLS x-connect
*/
fib_prefix_t pfx_2_2_2_3_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020203),
},
};
fib_route_path_t *rpaths = NULL, rpath = {
.frp_proto = FIB_PROTOCOL_MPLS,
.frp_local_label = 1200,
.frp_sw_if_index = ~0, // recurive
.frp_fib_index = 0, // Default MPLS fib
.frp_weight = 1,
.frp_flags = FIB_ROUTE_PATH_FLAG_NONE,
.frp_label_stack = NULL,
};
vec_add1(rpaths, rpath);
fib_table_entry_path_add2(fib_index,
&pfx_2_2_2_3_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
rpaths);
/*
* A labelled recursive route via the MPLS x-connect
*/
fib_prefix_t pfx_2_2_2_4_s_32 = {
.fp_len = 32,
.fp_proto = FIB_PROTOCOL_IP4,
.fp_addr = {
.ip4.as_u32 = clib_host_to_net_u32(0x02020204),
},
};
mpls_label_t *l999 = NULL;
vec_add1(l999, 999);
rpaths[0].frp_label_stack = l999,
fib_table_entry_path_add2(fib_index,
&pfx_2_2_2_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
rpaths);
fib_entry_contribute_forwarding(fib_table_lookup(fib_index, &pfx_1200),
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
&ip_1200);
fib_entry_contribute_forwarding(fib_table_lookup(fib_index, &pfx_1200),
FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS,
&neos_1200);
fib_test_lb_bucket_t ip_o_1200 = {
.type = FT_LB_O_LB,
.lb = {
.lb = ip_1200.dpoi_index,
},
};
fib_test_lb_bucket_t mpls_o_1200 = {
.type = FT_LB_LABEL_O_LB,
.label_o_lb = {
.lb = neos_1200.dpoi_index,
.label = 999,
.eos = MPLS_EOS,
},
};
lfe = fib_table_lookup(fib_index, &pfx_2_2_2_3_s_32);
FIB_TEST(fib_test_validate_entry(lfe,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_o_1200),
"2.2.2.2.3/32 LB 1 buckets via: label 1200 EOS");
lfe = fib_table_lookup(fib_index, &pfx_2_2_2_4_s_32);
FIB_TEST(fib_test_validate_entry(lfe,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&mpls_o_1200),
"2.2.2.2.4/32 LB 1 buckets via: label 1200 non-EOS");
fib_table_entry_delete(fib_index, &pfx_1200, FIB_SOURCE_API);
fib_table_entry_delete(fib_index, &pfx_2_2_2_3_s_32, FIB_SOURCE_API);
fib_table_entry_delete(fib_index, &pfx_2_2_2_4_s_32, FIB_SOURCE_API);
dpo_reset(&neos_1200);
dpo_reset(&ip_1200);
/*
* A recursive via a label that does not exist
*/
fib_test_lb_bucket_t bucket_drop = {
.type = FT_LB_SPECIAL,
.special = {
.adj = DPO_PROTO_MPLS,
},
};
rpaths[0].frp_label_stack = NULL;
lfe = fib_table_entry_path_add2(fib_index,
&pfx_2_2_2_4_s_32,
FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE,
rpaths);
fib_entry_contribute_forwarding(fib_table_lookup(fib_index, &pfx_1200),
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
&ip_1200);
ip_o_1200.lb.lb = ip_1200.dpoi_index;
FIB_TEST(fib_test_validate_entry(lfe,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&ip_o_1200),
"2.2.2.2.4/32 LB 1 buckets via: label 1200 EOS");
lfe = fib_table_lookup(fib_index, &pfx_1200);
FIB_TEST(fib_test_validate_entry(lfe,
FIB_FORW_CHAIN_TYPE_UNICAST_IP4,
1,
&bucket_drop),
"2.2.2.4/32 LB 1 buckets via: ip4-DROP");
fib_table_entry_delete(fib_index, &pfx_2_2_2_4_s_32, FIB_SOURCE_API);
dpo_reset(&ip_1200);
/*
* cleanup
*/
mpls_sw_interface_enable_disable(&mpls_main,
tm->hw[0]->sw_if_index,
0);
FIB_TEST(lb_count == pool_elts(load_balance_pool),
"Load-balance resources freed %d of %d",
lb_count, pool_elts(load_balance_pool));
return (0);
}
static clib_error_t *
fib_test (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd_arg)
{
int res;
res = 0;
fib_test_mk_intf(4);
if (unformat (input, "ip"))
{
res += fib_test_v4();
res += fib_test_v6();
}
else if (unformat (input, "label"))
{
res += fib_test_label();
}
else if (unformat (input, "ae"))
{
res += fib_test_ae();
}
else if (unformat (input, "lfib"))
{
res += lfib_test();
}
else if (unformat (input, "walk"))
{
res += fib_test_walk();
}
else
{
/*
* These walk UT aren't run as part of the full suite, since the
* fib-walk process must be disabled in order for the tests to work
*
* fib_test_walk();
*/
res += fib_test_v4();
res += fib_test_v6();
res += fib_test_ae();
res += fib_test_label();
res += lfib_test();
}
if (res)
{
return clib_error_return(0, "FIB Unit Test Failed");
}
else
{
return (NULL);
}
}
VLIB_CLI_COMMAND (test_fib_command, static) = {
.path = "test fib",
.short_help = "fib unit tests - DO NOT RUN ON A LIVE SYSTEM",
.function = fib_test,
};
clib_error_t *
fib_test_init (vlib_main_t *vm)
{
return 0;
}
VLIB_INIT_FUNCTION (fib_test_init);
|
748685.c | #include <stdio.h>
#include <stdlib.h>
int sum(int *A, int N);
int main()
{
int N;
printf("Enter the number of elements: ");
scanf("%d", &N);
int *A = (int *)malloc(N*sizeof(int));
for (int i = 0; i < N; ++i)
{
printf("Enter the element #%d: ", i+1);
scanf("%d", &A[i]);
}
int ans = sum(A, N);
switch (ans)
{
case 0:
printf("sum: zero %d\n", -ans);
break;
default:
printf("sum: non-zero %d\n", ans);
}
return 0;
}
int sum(int *A, int N)
{
int ans = 0;
for (int i = 0; i < N; ++i)
ans += A[i];
return ans;
}
|
620903.c | /*
* Copyright (c) 2019, 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.
*/
#include <stdint.h>
#include "config/aom_config.h"
#include "config/aom_scale_rtcd.h"
#include "aom/aom_codec.h"
#include "aom/aom_encoder.h"
#include "aom_ports/system_state.h"
#include "av1/common/onyxc_int.h"
#include "av1/encoder/encoder.h"
#include "av1/encoder/firstpass.h"
#include "av1/encoder/gop_structure.h"
static void set_multi_layer_params(GF_GROUP *const gf_group, int l, int r,
int *frame_ind, int arf_ind, int level) {
if (r - l < 4) {
while (++l < r) {
// leaf nodes, not a look-ahead frame
gf_group->update_type[*frame_ind] = LF_UPDATE;
gf_group->arf_src_offset[*frame_ind] = 0;
gf_group->arf_pos_in_gf[*frame_ind] = 0;
gf_group->arf_update_idx[*frame_ind] = arf_ind;
gf_group->pyramid_level[*frame_ind] = 0;
++gf_group->pyramid_lvl_nodes[0];
++(*frame_ind);
}
} else {
int m = (l + r) / 2;
int arf_pos_in_gf = *frame_ind;
gf_group->update_type[*frame_ind] = INTNL_ARF_UPDATE;
gf_group->arf_src_offset[*frame_ind] = m - l - 1;
gf_group->arf_pos_in_gf[*frame_ind] = 0;
gf_group->arf_update_idx[*frame_ind] = 1; // mark all internal ARF 1
gf_group->pyramid_level[*frame_ind] = level;
++gf_group->pyramid_lvl_nodes[level];
++(*frame_ind);
// set parameters for frames displayed before this frame
set_multi_layer_params(gf_group, l, m, frame_ind, 1, level - 1);
// for overlay frames, we need to record the position of its corresponding
// arf frames for bit allocation
gf_group->update_type[*frame_ind] = INTNL_OVERLAY_UPDATE;
gf_group->arf_src_offset[*frame_ind] = 0;
gf_group->arf_pos_in_gf[*frame_ind] = arf_pos_in_gf;
gf_group->arf_update_idx[*frame_ind] = 1;
gf_group->pyramid_level[*frame_ind] = 0;
++(*frame_ind);
// set parameters for frames displayed after this frame
set_multi_layer_params(gf_group, m, r, frame_ind, arf_ind, level - 1);
}
}
static INLINE unsigned char get_pyramid_height(int pyramid_width) {
assert(pyramid_width <= MAX_GF_INTERVAL && pyramid_width >= MIN_GF_INTERVAL &&
"invalid gf interval for pyramid structure");
return pyramid_width > 12 ? 4 : (pyramid_width > 6 ? 3 : 2);
}
static int construct_multi_layer_gf_structure(GF_GROUP *const gf_group,
const int gf_interval) {
int frame_index = 0;
gf_group->pyramid_height = get_pyramid_height(gf_interval);
assert(gf_group->pyramid_height <= MAX_PYRAMID_LVL);
av1_zero_array(gf_group->pyramid_lvl_nodes, MAX_PYRAMID_LVL);
// At the beginning of each GF group it will be a key or overlay frame,
gf_group->update_type[frame_index] = OVERLAY_UPDATE;
gf_group->arf_src_offset[frame_index] = 0;
gf_group->arf_pos_in_gf[frame_index] = 0;
gf_group->arf_update_idx[frame_index] = 0;
gf_group->pyramid_level[frame_index] = 0;
++frame_index;
// ALT0
gf_group->update_type[frame_index] = ARF_UPDATE;
gf_group->arf_src_offset[frame_index] = gf_interval - 1;
gf_group->arf_pos_in_gf[frame_index] = 0;
gf_group->arf_update_idx[frame_index] = 0;
gf_group->pyramid_level[frame_index] = gf_group->pyramid_height;
++frame_index;
// set parameters for the rest of the frames
set_multi_layer_params(gf_group, 0, gf_interval, &frame_index, 0,
gf_group->pyramid_height - 1);
return frame_index;
}
#define CHECK_GF_PARAMETER 0
#if CHECK_GF_PARAMETER
void check_frame_params(GF_GROUP *const gf_group, int gf_interval,
int frame_nums) {
static const char *update_type_strings[] = {
"KF_UPDATE", "LF_UPDATE", "GF_UPDATE",
"ARF_UPDATE", "OVERLAY_UPDATE", "BRF_UPDATE",
"LAST_BIPRED_UPDATE", "BIPRED_UPDATE", "INTNL_OVERLAY_UPDATE",
"INTNL_ARF_UPDATE"
};
FILE *fid = fopen("GF_PARAMS.txt", "a");
fprintf(fid, "\n{%d}\n", gf_interval);
for (int i = 0; i <= frame_nums; ++i) {
fprintf(fid, "%s %d %d %d %d\n",
update_type_strings[gf_group->update_type[i]],
gf_group->arf_src_offset[i], gf_group->arf_pos_in_gf[i],
gf_group->arf_update_idx[i], gf_group->pyramid_level[i]);
}
fprintf(fid, "number of nodes in each level: \n");
for (int i = 0; i < gf_group->pyramid_height; ++i) {
fprintf(fid, "lvl %d: %d ", i, gf_group->pyramid_lvl_nodes[i]);
}
fprintf(fid, "\n");
fclose(fid);
}
#endif // CHECK_GF_PARAMETER
static int update_type_2_rf_level(FRAME_UPDATE_TYPE update_type) {
// Derive rf_level from update_type
switch (update_type) {
case LF_UPDATE: return INTER_NORMAL;
case ARF_UPDATE: return GF_ARF_STD;
case OVERLAY_UPDATE: return INTER_NORMAL;
case BRF_UPDATE: return GF_ARF_LOW;
case LAST_BIPRED_UPDATE: return INTER_NORMAL;
case BIPRED_UPDATE: return INTER_NORMAL;
case INTNL_ARF_UPDATE: return GF_ARF_LOW;
case INTNL_OVERLAY_UPDATE: return INTER_NORMAL;
default: return INTER_NORMAL;
}
}
static void define_pyramid_gf_group_structure(
AV1_COMP *cpi, const EncodeFrameParams *const frame_params) {
RATE_CONTROL *const rc = &cpi->rc;
TWO_PASS *const twopass = &cpi->twopass;
GF_GROUP *const gf_group = &twopass->gf_group;
const int key_frame = frame_params->frame_type == KEY_FRAME;
assert(rc->baseline_gf_interval >= MIN_GF_INTERVAL &&
rc->baseline_gf_interval <=
get_max_gf_length(cpi->oxcf.gf_max_pyr_height));
assert(cpi->oxcf.gf_max_pyr_height >= MIN_PYRAMID_LVL &&
cpi->oxcf.gf_max_pyr_height <= MAX_PYRAMID_LVL);
const int gf_update_frames =
construct_multi_layer_gf_structure(gf_group, rc->baseline_gf_interval);
int frame_index;
cpi->num_extra_arfs = 0;
for (frame_index = 0; frame_index < gf_update_frames; ++frame_index) {
// Set unused variables to default values
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
// Special handle for the first frame for assigning update_type
if (frame_index == 0) {
// For key frames the frame target rate is already set and it
// is also the golden frame.
if (key_frame) {
gf_group->update_type[frame_index] = KF_UPDATE;
continue;
}
if (rc->source_alt_ref_active) {
gf_group->update_type[frame_index] = OVERLAY_UPDATE;
} else {
gf_group->update_type[frame_index] = GF_UPDATE;
}
} else {
if (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE)
++cpi->num_extra_arfs;
}
// Assign rf level based on update type
gf_group->rf_level[frame_index] =
update_type_2_rf_level(gf_group->update_type[frame_index]);
}
// NOTE: We need to configure the frame at the end of the sequence + 1 that
// will be the start frame for the next group. Otherwise prior to the
// call to av1_get_second_pass_params() the data will be undefined.
if (rc->source_alt_ref_pending) {
gf_group->update_type[frame_index] = OVERLAY_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
} else {
gf_group->update_type[frame_index] = GF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_STD;
}
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
gf_group->arf_update_idx[frame_index] = 0;
// This value is only used for INTNL_OVERLAY_UPDATE
gf_group->arf_pos_in_gf[frame_index] = 0;
// This parameter is useless?
gf_group->arf_ref_idx[frame_index] = 0;
#ifdef CHCEK_GF_PARAMETER
check_frame_params(gf_group, rc->baseline_gf_interval, gf_update_frames);
#endif
}
static void define_flat_gf_group_structure(
AV1_COMP *cpi, const EncodeFrameParams *const frame_params) {
RATE_CONTROL *const rc = &cpi->rc;
TWO_PASS *const twopass = &cpi->twopass;
GF_GROUP *const gf_group = &twopass->gf_group;
int i;
int frame_index = 0;
const int key_frame = frame_params->frame_type == KEY_FRAME;
// The use of bi-predictive frames are only enabled when following 3
// conditions are met:
// (1) ALTREF is enabled;
// (2) The bi-predictive group interval is at least 2; and
// (3) The bi-predictive group interval is strictly smaller than the
// golden group interval.
const int is_bipred_enabled =
cpi->extra_arf_allowed && rc->source_alt_ref_pending &&
rc->bipred_group_interval &&
rc->bipred_group_interval <=
(rc->baseline_gf_interval - rc->source_alt_ref_pending);
int bipred_group_end = 0;
int bipred_frame_index = 0;
const unsigned char ext_arf_interval =
(unsigned char)(rc->baseline_gf_interval / (cpi->num_extra_arfs + 1) - 1);
int which_arf = cpi->num_extra_arfs;
int subgroup_interval[MAX_EXT_ARFS + 1];
int is_sg_bipred_enabled = is_bipred_enabled;
int accumulative_subgroup_interval = 0;
// For key frames the frame target rate is already set and it
// is also the golden frame.
// === [frame_index == 0] ===
if (!key_frame) {
if (rc->source_alt_ref_active) {
gf_group->update_type[frame_index] = OVERLAY_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
} else {
gf_group->update_type[frame_index] = GF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_STD;
}
gf_group->arf_update_idx[frame_index] = 0;
gf_group->arf_ref_idx[frame_index] = 0;
}
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
frame_index++;
bipred_frame_index++;
// === [frame_index == 1] ===
if (rc->source_alt_ref_pending) {
gf_group->update_type[frame_index] = ARF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_STD;
gf_group->arf_src_offset[frame_index] =
(unsigned char)(rc->baseline_gf_interval - 1);
gf_group->arf_update_idx[frame_index] = 0;
gf_group->arf_ref_idx[frame_index] = 0;
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
// NOTE: "bidir_pred_frame_index" stays unchanged for ARF_UPDATE frames.
// Work out the ARFs' positions in this gf group
// NOTE(weitinglin): ALT_REFs' are indexed inversely, but coded in display
// order (except for the original ARF). In the example of three ALT_REF's,
// We index ALTREF's as: KEY ----- ALT2 ----- ALT1 ----- ALT0
// but code them in the following order:
// KEY-ALT0-ALT2 ----- OVERLAY2-ALT1 ----- OVERLAY1 ----- OVERLAY0
//
// arf_pos_for_ovrly[]: Position for OVERLAY
// arf_pos_in_gf[]: Position for ALTREF
cpi->arf_pos_for_ovrly[0] = frame_index + cpi->num_extra_arfs +
gf_group->arf_src_offset[frame_index] + 1;
for (i = 0; i < cpi->num_extra_arfs; ++i) {
cpi->arf_pos_for_ovrly[i + 1] =
frame_index + (cpi->num_extra_arfs - i) * (ext_arf_interval + 2);
subgroup_interval[i] = cpi->arf_pos_for_ovrly[i] -
cpi->arf_pos_for_ovrly[i + 1] - (i == 0 ? 1 : 2);
}
subgroup_interval[cpi->num_extra_arfs] =
cpi->arf_pos_for_ovrly[cpi->num_extra_arfs] - frame_index -
(cpi->num_extra_arfs == 0 ? 1 : 2);
++frame_index;
// Insert an extra ARF
// === [frame_index == 2] ===
if (cpi->num_extra_arfs) {
gf_group->update_type[frame_index] = INTNL_ARF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_LOW;
gf_group->arf_src_offset[frame_index] = ext_arf_interval;
gf_group->arf_update_idx[frame_index] = which_arf;
gf_group->arf_ref_idx[frame_index] = 0;
++frame_index;
}
accumulative_subgroup_interval += subgroup_interval[cpi->num_extra_arfs];
}
const int normal_frames =
rc->baseline_gf_interval - (key_frame || rc->source_alt_ref_pending);
for (i = 0; i < normal_frames; ++i) {
gf_group->arf_update_idx[frame_index] = which_arf;
gf_group->arf_ref_idx[frame_index] = which_arf;
// If we are going to have ARFs, check whether we can have BWDREF in this
// subgroup, and further, whether we can have ARF subgroup which contains
// the BWDREF subgroup but contained within the GF group:
//
// GF group --> ARF subgroup --> BWDREF subgroup
if (rc->source_alt_ref_pending) {
is_sg_bipred_enabled =
is_bipred_enabled &&
(subgroup_interval[which_arf] > rc->bipred_group_interval);
}
// NOTE: BIDIR_PRED is only enabled when the length of the bi-predictive
// frame group interval is strictly smaller than that of the GOLDEN
// FRAME group interval.
// TODO(zoeliu): Currently BIDIR_PRED is only enabled when alt-ref is on.
if (is_sg_bipred_enabled && !bipred_group_end) {
const int cur_brf_src_offset = rc->bipred_group_interval - 1;
if (bipred_frame_index == 1) {
// --- BRF_UPDATE ---
gf_group->update_type[frame_index] = BRF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_LOW;
gf_group->brf_src_offset[frame_index] = cur_brf_src_offset;
} else if (bipred_frame_index == rc->bipred_group_interval) {
// --- LAST_BIPRED_UPDATE ---
gf_group->update_type[frame_index] = LAST_BIPRED_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
gf_group->brf_src_offset[frame_index] = 0;
// Reset the bi-predictive frame index.
bipred_frame_index = 0;
} else {
// --- BIPRED_UPDATE ---
gf_group->update_type[frame_index] = BIPRED_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
gf_group->brf_src_offset[frame_index] = 0;
}
gf_group->bidir_pred_enabled[frame_index] = 1;
bipred_frame_index++;
// Check whether the next bi-predictive frame group would entirely be
// included within the current golden frame group.
// In addition, we need to avoid coding a BRF right before an ARF.
if (bipred_frame_index == 1 &&
(i + 2 + cur_brf_src_offset) >= accumulative_subgroup_interval) {
bipred_group_end = 1;
}
} else {
gf_group->update_type[frame_index] = LF_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
}
++frame_index;
// Check if we need to update the ARF.
if (is_sg_bipred_enabled && cpi->num_extra_arfs && which_arf > 0 &&
frame_index > cpi->arf_pos_for_ovrly[which_arf]) {
--which_arf;
accumulative_subgroup_interval += subgroup_interval[which_arf] + 1;
// Meet the new subgroup; Reset the bipred_group_end flag.
bipred_group_end = 0;
// Insert another extra ARF after the overlay frame
if (which_arf) {
gf_group->update_type[frame_index] = INTNL_ARF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_LOW;
gf_group->arf_src_offset[frame_index] = ext_arf_interval;
gf_group->arf_update_idx[frame_index] = which_arf;
gf_group->arf_ref_idx[frame_index] = 0;
++frame_index;
}
}
}
// NOTE: We need to configure the frame at the end of the sequence + 1 that
// will be the start frame for the next group. Otherwise prior to the
// call to av1_get_second_pass_params() the data will be undefined.
gf_group->arf_update_idx[frame_index] = 0;
gf_group->arf_ref_idx[frame_index] = 0;
if (rc->source_alt_ref_pending) {
gf_group->update_type[frame_index] = OVERLAY_UPDATE;
gf_group->rf_level[frame_index] = INTER_NORMAL;
cpi->arf_pos_in_gf[0] = 1;
if (cpi->num_extra_arfs) {
// Overwrite the update_type for extra-ARF's corresponding internal
// OVERLAY's: Change from LF_UPDATE to INTNL_OVERLAY_UPDATE.
for (i = cpi->num_extra_arfs; i > 0; --i) {
cpi->arf_pos_in_gf[i] =
(i == cpi->num_extra_arfs ? 2 : cpi->arf_pos_for_ovrly[i + 1] + 1);
gf_group->update_type[cpi->arf_pos_for_ovrly[i]] = INTNL_OVERLAY_UPDATE;
gf_group->rf_level[cpi->arf_pos_for_ovrly[i]] = INTER_NORMAL;
}
}
} else {
gf_group->update_type[frame_index] = GF_UPDATE;
gf_group->rf_level[frame_index] = GF_ARF_STD;
}
gf_group->bidir_pred_enabled[frame_index] = 0;
gf_group->brf_src_offset[frame_index] = 0;
}
void av1_gop_setup_structure(AV1_COMP *cpi,
const EncodeFrameParams *const frame_params) {
RATE_CONTROL *const rc = &cpi->rc;
const int max_pyr_height = cpi->oxcf.gf_max_pyr_height;
const int valid_pyramid_gf_length =
max_pyr_height >= MIN_PYRAMID_LVL && max_pyr_height <= MAX_PYRAMID_LVL &&
rc->baseline_gf_interval >= MIN_GF_INTERVAL &&
rc->baseline_gf_interval <= get_max_gf_length(max_pyr_height);
// Decide whether to use a flat or pyramid structure for this GF
if (valid_pyramid_gf_length && rc->source_alt_ref_pending &&
cpi->extra_arf_allowed > 0) {
define_pyramid_gf_group_structure(cpi, frame_params);
cpi->new_bwdref_update_rule = 1;
} else {
define_flat_gf_group_structure(cpi, frame_params);
cpi->new_bwdref_update_rule = 0;
}
}
|
306590.c | /*
* Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/evp.h>
#include "internal/evp_int.h"
/* MAC PKEY context structure */
typedef struct {
EVP_MAC_CTX *ctx;
/*
* We know of two MAC types:
*
* 1. those who take a secret in raw form, i.e. raw data as a
* ASN1_OCTET_STRING embedded in a EVP_PKEY. So far, that's
* all of them but CMAC.
* 2. those who take a secret with associated cipher in very generic
* form, i.e. a complete EVP_MAC_CTX embedded in a PKEY. So far,
* only CMAC does this.
*
* (one might wonder why the second form isn't used for all)
*/
#define MAC_TYPE_RAW 1 /* VR_HMAC like MAC type (all but CMAC so far) */
#define MAC_TYPE_MAC 2 /* CMAC like MAC type (only CMAC known so far) */
int type;
/* The following is only used for MAC_TYPE_RAW implementations */
struct {
const EVP_MD *md; /* temp storage of MD */
ASN1_OCTET_STRING ktmp; /* temp storage for key */
} raw_data;
} MAC_PKEY_CTX;
static int pkey_mac_init(EVP_PKEY_CTX *ctx)
{
MAC_PKEY_CTX *hctx;
int nid = ctx->pmeth->pkey_id;
if ((hctx = OPENSSL_zalloc(sizeof(*hctx))) == NULL) {
EVPerr(EVP_F_PKEY_MAC_INIT, ERR_R_MALLOC_FAILURE);
return 0;
}
/* We're being smart and using the same base NIDs for PKEY and for MAC */
hctx->ctx = VR_EVP_MAC_CTX_new_id(nid);
if (hctx->ctx == NULL) {
VR_OPENSSL_free(hctx);
return 0;
}
if (nid == EVP_PKEY_CMAC) {
hctx->type = MAC_TYPE_MAC;
} else {
hctx->type = MAC_TYPE_RAW;
hctx->raw_data.ktmp.type = V_ASN1_OCTET_STRING;
}
VR_EVP_PKEY_CTX_set_data(ctx, hctx);
ctx->keygen_info_count = 0;
return 1;
}
static void pkey_mac_cleanup(EVP_PKEY_CTX *ctx);
static int pkey_mac_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)
{
MAC_PKEY_CTX *sctx, *dctx;
if (!pkey_mac_init(dst))
return 0;
sctx = VR_EVP_PKEY_CTX_get_data(src);
dctx = VR_EVP_PKEY_CTX_get_data(dst);
if (!VR_EVP_MAC_CTX_copy(dctx->ctx, sctx->ctx))
goto err;
switch (dctx->type) {
case MAC_TYPE_RAW:
dctx->raw_data.md = sctx->raw_data.md;
if (VR_ASN1_STRING_get0_data(&sctx->raw_data.ktmp) != NULL &&
!VR_ASN1_STRING_copy(&dctx->raw_data.ktmp, &sctx->raw_data.ktmp))
goto err;
break;
case MAC_TYPE_MAC:
/* Nothing more to do */
break;
default:
/* This should be dead code */
return 0;
}
return 1;
err:
pkey_mac_cleanup (dst);
return 0;
}
static void pkey_mac_cleanup(EVP_PKEY_CTX *ctx)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
if (hctx != NULL) {
switch (hctx->type) {
case MAC_TYPE_RAW:
OPENVR_SSL_clear_free(hctx->raw_data.ktmp.data,
hctx->raw_data.ktmp.length);
break;
}
VR_EVP_MAC_CTX_free(hctx->ctx);
VR_OPENSSL_free(hctx);
VR_EVP_PKEY_CTX_set_data(ctx, NULL);
}
}
static int pkey_mac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
int nid = ctx->pmeth->pkey_id;
switch (hctx->type) {
case MAC_TYPE_RAW:
{
ASN1_OCTET_STRING *hkey = NULL;
if (!hctx->raw_data.ktmp.data)
return 0;
hkey = VR_ASN1_OCTET_STRING_dup(&hctx->raw_data.ktmp);
if (!hkey)
return 0;
VR_EVP_PKEY_assign(pkey, nid, hkey);
}
break;
case MAC_TYPE_MAC:
{
EVP_MAC_CTX *cmkey = VR_EVP_MAC_CTX_new_id(nid);
if (cmkey == NULL)
return 0;
if (!VR_EVP_MAC_CTX_copy(cmkey, hctx->ctx)) {
VR_EVP_MAC_CTX_free(cmkey);
return 0;
}
VR_EVP_PKEY_assign(pkey, nid, cmkey);
}
break;
default:
/* This should be dead code */
return 0;
}
return 1;
}
static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(VR_EVP_MD_CTX_pkey_ctx(ctx));
if (!VR_EVP_MAC_update(hctx->ctx, data, count))
return 0;
return 1;
}
static int pkey_mac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
ASN1_OCTET_STRING *key = NULL;
int rv = 1;
/*
* For MACs with the EVP_PKEY_FLAG_SIGCTX_CUSTOM flag set and that
* gets the key passed as an ASN.1 OCTET STRING, we set the key here,
* as this may be only time it's set during a DigestSign.
*
* MACs that pass around the key in form of EVP_MAC_CTX are setting
* the key through other mechanisms. (this is only CMAC for now)
*/
int set_key =
hctx->type == MAC_TYPE_RAW
&& (ctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM) != 0;
if (set_key) {
if (VR_EVP_PKEY_id(VR_EVP_PKEY_CTX_get0_pkey(ctx))
!= VR_EVP_MAC_nid(VR_EVP_MAC_CTX_mac(hctx->ctx)))
return 0;
key = VR_EVP_PKEY_get0(VR_EVP_PKEY_CTX_get0_pkey(ctx));
if (key == NULL)
return 0;
}
/* Some MACs don't support this control... that's fine */
VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_FLAGS,
VR_EVP_MD_CTX_test_flags(mctx, ~EVP_MD_CTX_FLAG_NO_INIT));
VR_EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT);
VR_EVP_MD_CTX_set_update_fn(mctx, int_update);
if (set_key)
rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_KEY, key->data,
key->length);
return rv > 0;
}
static int pkey_mac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig,
size_t *siglen, EVP_MD_CTX *mctx)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
return VR_EVP_MAC_final(hctx->ctx, sig, siglen);
}
static int pkey_mac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
switch (type) {
case EVP_PKEY_CTRL_CIPHER:
switch (hctx->type) {
case MAC_TYPE_RAW:
return -2; /* The raw types don't support ciphers */
case MAC_TYPE_MAC:
{
int rv;
if ((rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_ENGINE,
ctx->engine)) < 0
|| (rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_CIPHER,
p2)) < 0
|| !(rv = VR_EVP_MAC_init(hctx->ctx)))
return rv;
}
break;
default:
/* This should be dead code */
return 0;
}
break;
case EVP_PKEY_CTRL_MD:
switch (hctx->type) {
case MAC_TYPE_RAW:
hctx->raw_data.md = p2;
break;
case MAC_TYPE_MAC:
if (ctx->pkey != NULL
&& !VR_EVP_MAC_CTX_copy(hctx->ctx,
(EVP_MAC_CTX *)ctx->pkey->pkey.ptr))
return 0;
if (!VR_EVP_MAC_init(hctx->ctx))
return 0;
break;
default:
/* This should be dead code */
return 0;
}
break;
case EVP_PKEY_CTRL_SET_DIGEST_SIZE:
return VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_SIZE, (size_t)p1);
case EVP_PKEY_CTRL_SET_MAC_KEY:
switch (hctx->type) {
case MAC_TYPE_RAW:
if ((!p2 && p1 > 0) || (p1 < -1))
return 0;
if (!VR_ASN1_OCTET_STRING_set(&hctx->raw_data.ktmp, p2, p1))
return 0;
break;
case MAC_TYPE_MAC:
if (!VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_KEY, p2, p1))
return 0;
break;
default:
/* This should be dead code */
return 0;
}
break;
case EVP_PKEY_CTRL_DIGESTINIT:
switch (hctx->type) {
case MAC_TYPE_RAW:
/* Ensure that we have attached the implementation */
if (!VR_EVP_MAC_init(hctx->ctx))
return 0;
{
int rv;
ASN1_OCTET_STRING *key =
(ASN1_OCTET_STRING *)ctx->pkey->pkey.ptr;
if ((rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_ENGINE,
ctx->engine)) < 0
|| (rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_MD,
hctx->raw_data.md)) < 0
|| (rv = VR_EVP_MAC_ctrl(hctx->ctx, EVP_MAC_CTRL_SET_KEY,
key->data, key->length)) < 0)
return rv;
}
break;
case MAC_TYPE_MAC:
return -2; /* The mac types don't support ciphers */
default:
/* This should be dead code */
return 0;
}
break;
default:
return -2;
}
return 1;
}
static int pkey_mac_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
MAC_PKEY_CTX *hctx = VR_EVP_PKEY_CTX_get_data(ctx);
return VR_EVP_MAC_ctrl_str(hctx->ctx, type, value);
}
const EVP_PKEY_METHOD cmac_pkey_meth = {
EVP_PKEY_CMAC,
EVP_PKEY_FLAG_SIGCTX_CUSTOM,
pkey_mac_init,
pkey_mac_copy,
pkey_mac_cleanup,
0, 0,
0,
pkey_mac_keygen,
0, 0,
0, 0,
0, 0,
pkey_mac_signctx_init,
pkey_mac_signctx,
0, 0,
0, 0,
0, 0,
0, 0,
pkey_mac_ctrl,
pkey_mac_ctrl_str
};
const EVP_PKEY_METHOD hmac_pkey_meth = {
EVP_PKEY_VR_HMAC,
0,
pkey_mac_init,
pkey_mac_copy,
pkey_mac_cleanup,
0, 0,
0,
pkey_mac_keygen,
0, 0,
0, 0,
0, 0,
pkey_mac_signctx_init,
pkey_mac_signctx,
0, 0,
0, 0,
0, 0,
0, 0,
pkey_mac_ctrl,
pkey_mac_ctrl_str
};
const EVP_PKEY_METHOD siphash_pkey_meth = {
EVP_PKEY_SIPHASH,
EVP_PKEY_FLAG_SIGCTX_CUSTOM,
pkey_mac_init,
pkey_mac_copy,
pkey_mac_cleanup,
0, 0,
0,
pkey_mac_keygen,
0, 0,
0, 0,
0, 0,
pkey_mac_signctx_init,
pkey_mac_signctx,
0, 0,
0, 0,
0, 0,
0, 0,
pkey_mac_ctrl,
pkey_mac_ctrl_str
};
const EVP_PKEY_METHOD poly1305_pkey_meth = {
EVP_PKEY_POLY1305,
EVP_PKEY_FLAG_SIGCTX_CUSTOM,
pkey_mac_init,
pkey_mac_copy,
pkey_mac_cleanup,
0, 0,
0,
pkey_mac_keygen,
0, 0,
0, 0,
0, 0,
pkey_mac_signctx_init,
pkey_mac_signctx,
0, 0,
0, 0,
0, 0,
0, 0,
pkey_mac_ctrl,
pkey_mac_ctrl_str
};
|
161084.c | /*
* FreeRTOS Kernel V10.4.1
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/* peripheral library include */
#include <plib.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
/* Demo includes. */
#include "lcd.h"
/*
* The LCD is written to by more than one task so is controlled by this
* 'gatekeeper' task. This is the only task that is actually permitted to
* access the LCD directly. Other tasks wanting to display a message send
* the message to the gatekeeper.
*/
static void vLCDTask( void *pvParameters );
/*
* Setup the peripherals required to communicate with the LCD.
*/
static void prvSetupLCD( void );
/*
* Move to the first (0) or second (1) row of the LCD.
*/
static void prvLCDGotoRow( unsigned short usRow );
/*
* Write a string of text to the LCD.
*/
static void prvLCDPutString( char *pcString );
/*
* Clear the LCD.
*/
static void prvLCDClear( void );
/*-----------------------------------------------------------*/
/* Brief delay to permit the LCD to catch up with commands. */
#define lcdVERY_SHORT_DELAY ( 1 )
#define lcdSHORT_DELAY ( 8 / portTICK_PERIOD_MS )
#define lcdLONG_DELAY ( 15 / portTICK_PERIOD_MS )
/* LCD specific definitions. */
#define LCD_CLEAR_DISPLAY_CMD 0x01
#define LCD_CURSOR_HOME_CMD 0x02
#define LCD_ENTRY_MODE_CMD 0x04
#define LCD_ENTRY_MODE_INCREASE 0x02
#define LCD_DISPLAY_CTRL_CMD 0x08
#define LCD_DISPLAY_CTRL_DISPLAY_ON 0x04
#define LCD_FUNCTION_SET_CMD 0x20
#define LCD_FUNCTION_SET_8_BITS 0x10
#define LCD_FUNCTION_SET_2_LINES 0x08
#define LCD_FUNCTION_SET_LRG_FONT 0x04
#define LCD_NEW_LINE 0xC0
#define LCD_COMMAND_ADDRESS 0x00
#define LCD_DATA_ADDRESS 0x01
/* The length of the queue used to send messages to the LCD gatekeeper task. */
#define lcdQUEUE_SIZE 3
/*-----------------------------------------------------------*/
/* The queue used to send messages to the LCD task. */
QueueHandle_t xLCDQueue;
/* LCD access functions. */
static void prvLCDCommand( char cCommand );
static void prvLCDData( char cChar );
/*-----------------------------------------------------------*/
QueueHandle_t xStartLCDTask( void )
{
/* Create the queue used by the LCD task. Messages for display on the LCD
are received via this queue. */
xLCDQueue = xQueueCreate( lcdQUEUE_SIZE, sizeof( xLCDMessage ));
/* Start the task that will write to the LCD. The LCD hardware is
initialised from within the task itself so delays can be used. */
xTaskCreate( vLCDTask, "LCD", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL );
return xLCDQueue;
}
/*-----------------------------------------------------------*/
static void prvLCDGotoRow( unsigned short usRow )
{
if(usRow == 0)
{
prvLCDCommand( LCD_CURSOR_HOME_CMD );
}
else
{
prvLCDCommand( LCD_NEW_LINE );
}
}
/*-----------------------------------------------------------*/
static void prvLCDCommand( char cCommand )
{
PMPSetAddress( LCD_COMMAND_ADDRESS );
PMPMasterWrite( cCommand );
vTaskDelay( lcdSHORT_DELAY );
}
/*-----------------------------------------------------------*/
static void prvLCDData( char cChar )
{
PMPSetAddress( LCD_DATA_ADDRESS );
PMPMasterWrite( cChar );
vTaskDelay( lcdVERY_SHORT_DELAY );
}
/*-----------------------------------------------------------*/
static void prvLCDPutString( char *pcString )
{
/* Write out each character with appropriate delay between each. */
while(*pcString)
{
prvLCDData(*pcString);
pcString++;
vTaskDelay(lcdSHORT_DELAY);
}
}
/*-----------------------------------------------------------*/
static void prvLCDClear(void)
{
prvLCDCommand(LCD_CLEAR_DISPLAY_CMD);
}
/*-----------------------------------------------------------*/
static void prvSetupLCD(void)
{
/* Wait for proper power up. */
vTaskDelay( lcdLONG_DELAY );
/* Open the PMP port */
mPMPOpen((PMP_ON | PMP_READ_WRITE_EN | PMP_CS2_CS1_EN |
PMP_LATCH_POL_HI | PMP_CS2_POL_HI | PMP_CS1_POL_HI |
PMP_WRITE_POL_HI | PMP_READ_POL_HI),
(PMP_MODE_MASTER1 | PMP_WAIT_BEG_4 | PMP_WAIT_MID_15 |
PMP_WAIT_END_4),
PMP_PEN_0, 0);
/* Wait for the LCD to power up correctly. */
vTaskDelay( lcdLONG_DELAY );
vTaskDelay( lcdLONG_DELAY );
vTaskDelay( lcdLONG_DELAY );
/* Set up the LCD function. */
prvLCDCommand( LCD_FUNCTION_SET_CMD | LCD_FUNCTION_SET_8_BITS | LCD_FUNCTION_SET_2_LINES | LCD_FUNCTION_SET_LRG_FONT );
/* Turn the display on. */
prvLCDCommand( LCD_DISPLAY_CTRL_CMD | LCD_DISPLAY_CTRL_DISPLAY_ON );
/* Clear the display. */
prvLCDCommand( LCD_CLEAR_DISPLAY_CMD );
vTaskDelay( lcdLONG_DELAY );
/* Increase the cursor. */
prvLCDCommand( LCD_ENTRY_MODE_CMD | LCD_ENTRY_MODE_INCREASE );
vTaskDelay( lcdLONG_DELAY );
vTaskDelay( lcdLONG_DELAY );
vTaskDelay( lcdLONG_DELAY );
}
/*-----------------------------------------------------------*/
static void vLCDTask(void *pvParameters)
{
xLCDMessage xMessage;
unsigned short usRow = 0;
/* Initialise the hardware. This uses delays so must not be called prior
to the scheduler being started. */
prvSetupLCD();
/* Welcome message. */
prvLCDPutString( "www.FreeRTOS.org" );
for(;;)
{
/* Wait for a message to arrive that requires displaying. */
while( xQueueReceive( xLCDQueue, &xMessage, portMAX_DELAY ) != pdPASS );
/* Clear the current display value. */
prvLCDClear();
/* Switch rows each time so we can see that the display is still being
updated. */
prvLCDGotoRow( usRow & 0x01 );
usRow++;
prvLCDPutString( xMessage.pcMessage );
/* Delay the requested amount of time to ensure the text just written
to the LCD is not overwritten. */
vTaskDelay( xMessage.xMinDisplayTime );
}
}
|
96450.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <string.h>
#include "syscfg/syscfg.h"
#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
#include "bootutil/sign_key.h"
#include "mbedtls/ecdsa.h"
#include "mbedtls/oid.h"
#include "mbedtls/asn1.h"
#include "bootutil_priv.h"
/*
* Declaring these like this adds NULL termination.
*/
static const uint8_t ec_pubkey_oid[] = MBEDTLS_OID_EC_ALG_UNRESTRICTED;
static const uint8_t ec_secp224r1_oid[] = MBEDTLS_OID_EC_GRP_SECP224R1;
/*
* Parse the public key used for signing.
*/
static int
bootutil_parse_eckey(mbedtls_ecdsa_context *ctx, uint8_t **p, uint8_t *end)
{
size_t len;
mbedtls_asn1_buf alg;
mbedtls_asn1_buf param;
if (mbedtls_asn1_get_tag(p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
return -1;
}
end = *p + len;
if (mbedtls_asn1_get_alg(p, end, &alg, ¶m)) {
return -2;
}
if (alg.len != sizeof(ec_pubkey_oid) - 1 ||
memcmp(alg.p, ec_pubkey_oid, sizeof(ec_pubkey_oid) - 1)) {
return -3;
}
if (param.len != sizeof(ec_secp224r1_oid) - 1||
memcmp(param.p, ec_secp224r1_oid, sizeof(ec_secp224r1_oid) - 1)) {
return -4;
}
if (mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP224R1)) {
return -5;
}
if (mbedtls_asn1_get_bitstring_null(p, end, &len)) {
return -6;
}
if (*p + len != end) {
return -7;
}
if (mbedtls_ecp_point_read_binary(&ctx->grp, &ctx->Q, *p, end - *p)) {
return -8;
}
if (mbedtls_ecp_check_pubkey(&ctx->grp, &ctx->Q)) {
return -9;
}
return 0;
}
static int
bootutil_cmp_sig(mbedtls_ecdsa_context *ctx, uint8_t *hash, uint32_t hlen,
uint8_t *sig, int slen)
{
return mbedtls_ecdsa_read_signature(ctx, hash, hlen, sig, slen);
}
int
bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
uint8_t key_id)
{
int rc;
uint8_t *cp;
uint8_t *end;
mbedtls_ecdsa_context ctx;
mbedtls_ecdsa_init(&ctx);
cp = (uint8_t *)bootutil_keys[key_id].key;
end = cp + *bootutil_keys[key_id].len;
rc = bootutil_parse_eckey(&ctx, &cp, end);
if (rc) {
return -1;
}
while (sig[slen - 1] == '\0') {
slen--;
}
rc = bootutil_cmp_sig(&ctx, hash, hlen, sig, slen);
mbedtls_ecdsa_free(&ctx);
return rc;
}
#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_EC) */
|
874058.c |
#ifdef HAVE_CONFIG_H
#include "../ext_config.h"
#endif
#include <php.h>
#include "../php_ext.h"
#include "../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
ZEPHIR_INIT_CLASS(stub_10__closure)
{
ZEPHIR_REGISTER_CLASS(stub, 10__closure, stub, 10__closure, stub_10__closure_method_entry, ZEND_ACC_FINAL_CLASS);
return SUCCESS;
}
PHP_METHOD(stub_10__closure, __invoke)
{
zval *config, config_sub;
zval *this_ptr = getThis();
ZVAL_UNDEF(&config_sub);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(config)
ZEND_PARSE_PARAMETERS_END();
#endif
zephir_fetch_params_without_memory_grow(1, 0, &config);
RETVAL_ZVAL(config, 1, 0);
return;
}
|
8382.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* case is sensitive in R6 and R7 */
#ifndef bool
typedef enum {false, true} bool;
#define bool bool
#endif
typedef unsigned int uint;
#define SCHEME_VER "v0.5"
/* NULLOBJ for the empty list type */
typedef enum { NULLOBJ, BOOLEAN, FIXNUM, CHARACTER, STRING } object_t;
typedef struct {
object_t type;
union {
struct {
bool value;
} boolean;
struct {
long value;
} fixnum;
struct {
char value;
} character;
struct {
char *value;
} string;
} data;
} object;
/* for boolean singleton and empty list */
static object *falseobj, *trueobj, *nullobj;
/* map between the unescaped and escaped characters */
static const char* unescaped = "abfnrtv\\'\"?";
static const char* escaped = "\a\b\f\n\r\t\v\\\'\"\?";
/* no memory reclaim! */
object *make_object(void)
{
object *obj = (object *) malloc(sizeof(object));
if (obj != NULL) return obj;
fprintf(stderr, "ERROR: Memory exhausted\n");
exit(1);
}
object *make_fixnum(long num)
{
object *obj = make_object();
obj->type = FIXNUM;
obj->data.fixnum.value = num;
return obj;
}
object *make_char(char value)
{
object *obj = make_object();
obj->type = CHARACTER;
obj->data.character.value = value;
return obj;
}
object *make_string(const char *value)
{
object *obj = make_object();
obj->type = STRING;
char **p = &obj->data.string.value;
*p = (char *) malloc(sizeof(char) + strlen(value));
if (*p == NULL) {
fprintf(stderr, "ERROR: Memory exhausted\n");
exit(1);
}
strcpy(*p, value);
return obj;
}
void initialize(void)
{
falseobj = make_object();
falseobj->type = BOOLEAN;
falseobj->data.boolean.value = false;
trueobj = make_object();
trueobj->type = BOOLEAN;
trueobj->data.boolean.value = true;
nullobj = make_object();
nullobj->type = NULLOBJ;
}
bool is_delimiter(int c)
{
return isspace(c) || c == EOF ||
c == '(' || c == ')' ||
c == '"' || c == ';';
}
int peek(FILE *in)
{
int c = getc(in);
ungetc(c, in);
return c;
}
void skip_blank(FILE *in)
{
int c;
while ((c = getc(in)) != EOF) {
if (isspace(c))
continue;
else if (c == ';')
while (((c = getc(in)) != EOF) && (c != '\n'))
continue;
ungetc(c, in);
break;
}
}
void match_string(FILE *in, const char *str)
{
int c;
while (*str != '\0')
if ((c = getc(in)) != *str++) break;
if (*str == '\0') return ;
fprintf(stderr, "ERROR: Unexcepted character code `%d'!!!\n", c);
exit(1);
}
void peek_delimiter(FILE *in)
{
if (is_delimiter(peek(in))) return ;
fprintf(stderr, "ERROR: Character now followed by delimiter\n");
exit(1);
}
object *read_character(FILE *in)
{
int c = getc(in);
switch (c) {
case EOF:
fprintf(stderr, "ERROR: Incomplete character literal\n");
exit(1);
case 's':
if (peek(in) != 'p') break;
match_string(in, "pace");
c = ' ';
break;
case 'n': /* linefeed */
if (peek(in) != 'e') break;
match_string(in, "ewline");
c = '\n';
break;
case 't':
if (peek(in) != 'a') break;
match_string(in, "ab");
c = '\t';
break;
case 'r':
if (peek(in) != 'e') break;
match_string(in, "eturn");
c = '\r';
break;
}
peek_delimiter(in);
if (peek(in) != '\n') skip_blank(in);
return make_char(c);
}
object * input(FILE *in)
{
skip_blank(in);
int c = getc(in);
/* allow empty string */
if (c == EOF) return NULL;
short sign = 1;
long num = 0;
#define BUF_SIZE 1024
char buffer[BUF_SIZE];
uint i = 0;
char *p;
if (c == '#') {
c = getc(in);
if ((c == 't' || c == 'f') && peek(in) != '\n')
skip_blank(in);
switch (c) {
case 't': return trueobj;
case 'f': return falseobj;
case '\\': return read_character(in);
default:
fprintf(stderr, "ERROR: Unknown boolean literal\n");
exit(1);
}
}
else if (isdigit(c) ||
(c == '-' && isdigit(peek(in))) ||
(c == '+' && isdigit(peek(in)))) {
if (c == '-') sign = -1;
else if (c != '+') ungetc(c, in);
while (isdigit(c = getc(in)))
num = (num * 10) + (c - '0');
num *= sign;
if (!is_delimiter(c)) {
fprintf(stderr, "ERROR: Fixnum not followed by delimiter\n");
exit(1);
}
ungetc(c, in);
if (c != '\n') skip_blank(in);
return make_fixnum(num);
}
else if (c == '"') {
while ((c = getc(in)) != '"') {
if (c == '\\') {
p = strchr(unescaped, (c = getc(in)));
if (p != NULL) c = escaped[p - unescaped];
}
if (c == EOF) {
fprintf(stderr, "ERROR: Nonterminated string literal\n");
exit(1);
}
if (i < BUF_SIZE-1) buffer[i++] = c;
else {
fprintf(stderr, "ERROR: Reached the end of string\n");
exit(1);
}
}
buffer[i] = '\0';
if (peek(in) != '\n') skip_blank(in);
return make_string(buffer);
}
else if (c == '(') {
skip_blank(in);
if ((c = getc(in)) == ')') {
if (peek(in) != '\n') skip_blank(in);
return nullobj;
}
fprintf(stderr, "ERROR: Unexcepted character code `%d'\n", c);
exit(1);
}
fprintf(stderr, "Unexcepted input `%d'\n", c);
exit(1);
}
object * eval(object *exp)
{ return exp; }
void output(object *obj)
{
if (obj == NULL) return ;
int c;
const char *str, *p;
switch (obj->type) {
case NULLOBJ:
printf("()");
break;
case BOOLEAN:
printf("#%c", obj == trueobj ? 't' : 'f');
break;
case FIXNUM:
printf("%ld", obj->data.fixnum.value);
break;
case CHARACTER:
c = obj->data.character.value;
printf("#\\");
switch (c) {
case '\n':
printf("newline");
break;
case '\t':
printf("tab");
break;
case '\r':
printf("return");
break;
case ' ':
printf("space");
break;
default:
putchar(c);
}
break;
case STRING:
str = obj->data.string.value;
putchar('"');
while (*str != '\0') {
p = strchr(escaped, *str);
if (p != NULL)
printf("\\%c", unescaped[p - escaped]);
else
putchar(*str);
str++;
}
putchar('"');
break;
default:
fprintf(stderr, "ERROR: Unknown type id %d\n", obj->type);
exit(1);
}
}
int main(void)
{
printf("Bootstrap Scheme %s CTRL+C to quit.\n", SCHEME_VER);
initialize();
while (true) {
printf("> ");
output(eval(input(stdin)));
puts("");
}
return 0;
}
|
786134.c | /*
* Copyright 2005-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
#include <stdio.h>
#include <assert.h>
#include "grib_api_internal.h"
int main(int argc, char *argv[])
{
unsigned long i = 0;
assert(grib_ibm_to_long(grib_long_to_ibm(i)) == i);
for(i = 1; i < 0x7fffffff; i++)
{
unsigned long j = i | 0x80000000;
if(grib_ibm_to_long(grib_long_to_ibm(i)) != i)
{
printf("i=%ld i=%lx e=%g x=%lx\n",i,i,grib_long_to_ibm(i),grib_ibm_to_long(grib_long_to_ibm(i)));
assert(grib_ibm_to_long(grib_long_to_ibm(i)) == i);
}
assert(grib_ibm_to_long(grib_long_to_ibm(j)) == j);
if((i%100000) == 0)
printf("i = %08lx %08lx %g %g\n",i,j,grib_long_to_ibm(i),grib_long_to_ibm(j));
}
return 0;
}
|
729976.c | /*
Copyright (c) 2012 Martin Sustrik All rights reserved.
Copyright (c) 2013 GoPivotal, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "../src/nn.h"
#include "../src/bus.h"
#include "../src/pair.h"
#include "../src/pipeline.h"
#include "../src/inproc.h"
#include "testutil.h"
#include "../src/utils/attr.h"
#include "../src/utils/thread.c"
#define SOCKET_ADDRESS_A "inproc://a"
#define SOCKET_ADDRESS_B "inproc://b"
#define SOCKET_ADDRESS_C "inproc://c"
#define SOCKET_ADDRESS_D "inproc://d"
#define SOCKET_ADDRESS_E "inproc://e"
void device1 (NN_UNUSED void *arg)
{
int rc;
int deva;
int devb;
/* Intialise the device sockets. */
deva = test_socket (AF_SP_RAW, NN_PAIR);
test_bind (deva, SOCKET_ADDRESS_A);
devb = test_socket (AF_SP_RAW, NN_PAIR);
test_bind (devb, SOCKET_ADDRESS_B);
/* Run the device. */
rc = nn_device (deva, devb);
nn_assert (rc < 0 && (nn_errno () == ETERM || nn_errno () == EBADF));
/* Clean up. */
test_close (devb);
test_close (deva);
}
void device2 (NN_UNUSED void *arg)
{
int rc;
int devc;
int devd;
/* Intialise the device sockets. */
devc = test_socket (AF_SP_RAW, NN_PULL);
test_bind (devc, SOCKET_ADDRESS_C);
devd = test_socket (AF_SP_RAW, NN_PUSH);
test_bind (devd, SOCKET_ADDRESS_D);
/* Run the device. */
rc = nn_device (devc, devd);
nn_assert (rc < 0 && nn_errno () == ETERM);
/* Clean up. */
test_close (devd);
test_close (devc);
}
void device3 (NN_UNUSED void *arg)
{
int rc;
int deve;
/* Intialise the device socket. */
deve = test_socket (AF_SP_RAW, NN_BUS);
test_bind (deve, SOCKET_ADDRESS_E);
/* Run the device. */
rc = nn_device (deve, -1);
nn_assert (rc < 0 && nn_errno () == ETERM);
/* Clean up. */
test_close (deve);
}
int main ()
{
int enda;
int endb;
int endc;
int endd;
int ende1;
int ende2;
struct nn_thread thread1;
struct nn_thread thread2;
struct nn_thread thread3;
int timeo;
/* Test the bi-directional device. */
/* Start the device. */
nn_thread_init (&thread1, device1, NULL);
/* Create two sockets to connect to the device. */
enda = test_socket (AF_SP, NN_PAIR);
test_connect (enda, SOCKET_ADDRESS_A);
endb = test_socket (AF_SP, NN_PAIR);
test_connect (endb, SOCKET_ADDRESS_B);
/* Pass a pair of messages between endpoints. */
test_send (enda, "ABC");
test_recv (endb, "ABC");
test_send (endb, "ABC");
test_recv (enda, "ABC");
/* Clean up. */
test_close (endb);
test_close (enda);
/* Test the uni-directional device. */
/* Start the device. */
nn_thread_init (&thread2, device2, NULL);
/* Create two sockets to connect to the device. */
endc = test_socket (AF_SP, NN_PUSH);
test_connect (endc, SOCKET_ADDRESS_C);
endd = test_socket (AF_SP, NN_PULL);
test_connect (endd, SOCKET_ADDRESS_D);
/* Pass a message between endpoints. */
test_send (endc, "XYZ");
test_recv (endd, "XYZ");
/* Clean up. */
test_close (endd);
test_close (endc);
/* Test the loopback device. */
/* Start the device. */
nn_thread_init (&thread3, device3, NULL);
/* Create two sockets to connect to the device. */
ende1 = test_socket (AF_SP, NN_BUS);
test_connect (ende1, SOCKET_ADDRESS_E);
ende2 = test_socket (AF_SP, NN_BUS);
test_connect (ende2, SOCKET_ADDRESS_E);
/* BUS is unreliable so wait a bit for connections to be established. */
nn_sleep (100);
/* Pass a message to the bus. */
test_send (ende1, "KLM");
test_recv (ende2, "KLM");
/* Make sure that the message doesn't arrive at the socket it was
originally sent to. */
timeo = 100;
test_setsockopt (ende1, NN_SOL_SOCKET, NN_RCVTIMEO,
&timeo, sizeof (timeo));
test_drop (ende1, ETIMEDOUT);
/* Clean up. */
test_close (ende2);
test_close (ende1);
/* Shut down the devices. */
nn_term ();
nn_thread_term (&thread1);
nn_thread_term (&thread2);
nn_thread_term (&thread3);
return 0;
}
|
895696.c | /*----------DEMO OF opendir(),closedir(),readdi()------------*/
#include<stdio.h>
#include<errno.h>
#include<sys/types.h>
#include<dirent.h>
char *myname;
int process(char *dir);
int main(int argc,char*argv[])
{
int i;
int errs=0;
myname = argv[0];
if(argc == 1)
errs = process(".");//current directory
else
for(i = 1;i<argc;i++)
errs += process(argv[i]);
return (errs != 0);
}
int process(char *dir)
{
DIR *dp;
struct dirent *ent;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"%s:%s:cannot open file for reading: %s\n",myname,dir,strerror(errno));
return 1;
}
errno = 0;
while((ent = readdir(dp)) != NULL)
printf("%81d %s\n",ent->d_ino,ent->d_name);
if(errno != 0)
{
fprintf(stderr,"%s:%s:reading directory entries :%s\n",myname,dir,strerror(errno));
return 1;
}
if(closedir(dp) != 0)
{
fprintf(stderr,"%s:%s:closing directory :%s\n",myname,dir,strerror(errno));
return 1;
}
return 0;
}
|
349894.c | /*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/compile.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "py/mphal.h"
#include "py/gc.h"
#include "lib/mp-readline/readline.h"
#include "lib/utils/pyexec.h"
#include "gccollect.h"
#include "user_interface.h"
STATIC char heap[36 * 1024];
STATIC void mp_reset(void) {
mp_stack_set_top((void*)0x40000000);
mp_stack_set_limit(8192);
mp_hal_init();
gc_init(heap, heap + sizeof(heap));
mp_init();
mp_obj_list_init(mp_sys_path, 0);
mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)
mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_lib));
mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_));
mp_obj_list_init(mp_sys_argv, 0);
MP_STATE_PORT(term_obj) = MP_OBJ_NULL;
MP_STATE_PORT(dupterm_arr_obj) = MP_OBJ_NULL;
#if MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA
extern void esp_native_code_init(void);
esp_native_code_init();
#endif
pin_init0();
readline_init0();
dupterm_task_init();
#if MICROPY_MODULE_FROZEN
pyexec_frozen_module("_boot.py");
pyexec_file("boot.py");
pyexec_file("main.py");
#endif
}
void soft_reset(void) {
mp_hal_stdout_tx_str("PYB: soft reboot\r\n");
mp_hal_delay_us(10000); // allow UART to flush output
mp_reset();
#if MICROPY_REPL_EVENT_DRIVEN
pyexec_event_repl_init();
#endif
}
void init_done(void) {
#if MICROPY_REPL_EVENT_DRIVEN
uart_task_init();
#endif
mp_reset();
mp_hal_stdout_tx_str("\r\n");
#if MICROPY_REPL_EVENT_DRIVEN
pyexec_event_repl_init();
#endif
#if !MICROPY_REPL_EVENT_DRIVEN
soft_reset:
for (;;) {
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
if (pyexec_raw_repl() != 0) {
break;
}
} else {
if (pyexec_friendly_repl() != 0) {
break;
}
}
}
soft_reset();
goto soft_reset;
#endif
}
void user_init(void) {
system_init_done_cb(init_done);
}
mp_import_stat_t fat_vfs_import_stat(const char *path);
#if !MICROPY_VFS_FAT
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
return NULL;
}
#endif
mp_import_stat_t mp_import_stat(const char *path) {
#if MICROPY_VFS_FAT
return fat_vfs_import_stat(path);
#else
(void)path;
return MP_IMPORT_STAT_NO_EXIST;
#endif
}
mp_obj_t vfs_proxy_call(qstr method_name, mp_uint_t n_args, const mp_obj_t *args);
mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
#if MICROPY_VFS_FAT
// TODO: Handle kwargs!
return vfs_proxy_call(MP_QSTR_open, n_args, args);
#else
return mp_const_none;
#endif
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void MP_FASTCODE(nlr_jump_fail)(void *val) {
printf("NLR jump failed\n");
for (;;) {
}
}
//void __assert(const char *file, int line, const char *func, const char *expr) {
void __assert(const char *file, int line, const char *expr) {
printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
for (;;) {
}
}
|
648341.c | /*
* Copyright 2013 Hans Leidekker for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "config.h"
#include <stdarg.h>
#define COBJMACROS
#include "windef.h"
#include "winbase.h"
#include "initguid.h"
#include "objbase.h"
#include "wbemdisp.h"
#include "rpcproxy.h"
#include "wine/debug.h"
#include "wbemdisp_private.h"
#include "wbemdisp_classes.h"
WINE_DEFAULT_DEBUG_CHANNEL(wbemdisp);
static HINSTANCE instance;
static HRESULT WINAPI WinMGMTS_QueryInterface(IParseDisplayName *iface, REFIID riid, void **ppv)
{
if(IsEqualGUID(riid, &IID_IUnknown)) {
TRACE("(IID_IUnknown %p)\n", ppv);
*ppv = iface;
}else if(IsEqualGUID(riid, &IID_IParseDisplayName)) {
TRACE("(IID_IParseDisplayName %p)\n", ppv);
*ppv = iface;
}else {
WARN("Unsupported riid %s\n", debugstr_guid(riid));
*ppv = NULL;
return E_NOINTERFACE;
}
IUnknown_AddRef((IUnknown*)*ppv);
return S_OK;
}
static ULONG WINAPI WinMGMTS_AddRef(IParseDisplayName *iface)
{
return 2;
}
static ULONG WINAPI WinMGMTS_Release(IParseDisplayName *iface)
{
return 1;
}
static HRESULT WINAPI WinMGMTS_ParseDisplayName(IParseDisplayName *iface, IBindCtx *pbc, LPOLESTR pszDisplayName,
ULONG *pchEaten, IMoniker **ppmkOut)
{
FIXME("(%p %s %p %p)\n", pbc, debugstr_w(pszDisplayName), pchEaten, ppmkOut);
return E_NOTIMPL;
}
static const IParseDisplayNameVtbl WinMGMTSVtbl = {
WinMGMTS_QueryInterface,
WinMGMTS_AddRef,
WinMGMTS_Release,
WinMGMTS_ParseDisplayName
};
static IParseDisplayName winmgmts = { &WinMGMTSVtbl };
static HRESULT WinMGMTS_create(IUnknown *outer, void **ppv)
{
*ppv = &winmgmts;
return S_OK;
}
struct factory
{
IClassFactory IClassFactory_iface;
HRESULT (*fnCreateInstance)( IUnknown *, LPVOID * );
};
static inline struct factory *impl_from_IClassFactory( IClassFactory *iface )
{
return CONTAINING_RECORD( iface, struct factory, IClassFactory_iface );
}
static HRESULT WINAPI factory_QueryInterface( IClassFactory *iface, REFIID riid, LPVOID *obj )
{
if (IsEqualGUID( riid, &IID_IUnknown ) || IsEqualGUID( riid, &IID_IClassFactory ))
{
IClassFactory_AddRef( iface );
*obj = iface;
return S_OK;
}
FIXME( "interface %s not implemented\n", debugstr_guid(riid) );
return E_NOINTERFACE;
}
static ULONG WINAPI factory_AddRef( IClassFactory *iface )
{
return 2;
}
static ULONG WINAPI factory_Release( IClassFactory *iface )
{
return 1;
}
static HRESULT WINAPI factory_CreateInstance( IClassFactory *iface, LPUNKNOWN outer, REFIID riid,
LPVOID *obj )
{
struct factory *factory = impl_from_IClassFactory( iface );
IUnknown *unk;
HRESULT hr;
TRACE( "%p, %s, %p\n", outer, debugstr_guid(riid), obj );
*obj = NULL;
if (outer) return CLASS_E_NOAGGREGATION;
hr = factory->fnCreateInstance( outer, (LPVOID *)&unk );
if (FAILED( hr ))
return hr;
hr = IUnknown_QueryInterface( unk, riid, obj );
if (FAILED( hr ))
return hr;
IUnknown_Release( unk );
return hr;
}
static HRESULT WINAPI factory_LockServer( IClassFactory *iface, BOOL lock )
{
FIXME( "%p, %d\n", iface, lock );
return S_OK;
}
static const struct IClassFactoryVtbl factory_vtbl =
{
factory_QueryInterface,
factory_AddRef,
factory_Release,
factory_CreateInstance,
factory_LockServer
};
static struct factory swbem_locator_cf = { { &factory_vtbl }, SWbemLocator_create };
static struct factory winmgmts_cf = { { &factory_vtbl }, WinMGMTS_create };
BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, LPVOID reserved )
{
switch (reason)
{
case DLL_WINE_PREATTACH:
return FALSE; /* prefer native version */
case DLL_PROCESS_ATTACH:
instance = hinst;
DisableThreadLibraryCalls( hinst );
break;
}
return TRUE;
}
HRESULT WINAPI DllGetClassObject( REFCLSID rclsid, REFIID iid, LPVOID *obj )
{
IClassFactory *cf = NULL;
TRACE( "%s, %s, %p\n", debugstr_guid(rclsid), debugstr_guid(iid), obj );
if (IsEqualGUID( rclsid, &CLSID_SWbemLocator ))
cf = &swbem_locator_cf.IClassFactory_iface;
else if (IsEqualGUID( rclsid, &CLSID_WinMGMTS ))
cf = &winmgmts_cf.IClassFactory_iface;
else
return CLASS_E_CLASSNOTAVAILABLE;
return IClassFactory_QueryInterface( cf, iid, obj );
}
/***********************************************************************
* DllCanUnloadNow (WBEMDISP.@)
*/
HRESULT WINAPI DllCanUnloadNow(void)
{
return S_FALSE;
}
/***********************************************************************
* DllRegisterServer (WBEMDISP.@)
*/
HRESULT WINAPI DllRegisterServer(void)
{
return __wine_register_resources( instance );
}
/***********************************************************************
* DllUnregisterServer (WBEMDISP.@)
*/
HRESULT WINAPI DllUnregisterServer(void)
{
return __wine_unregister_resources( instance );
}
|
408113.c | /* Generated by Nim Compiler v1.6.2 */
#define NIM_INTBITS 64
#define NIM_EmulateOverflowChecks
#include "nimbase.h"
#include <string.h>
#include <setjmp.h>
#include <glob.h>
#undef LANGUAGE_C
#undef MIPSEB
#undef MIPSEL
#undef PPC
#undef R3000
#undef R4000
#undef i386
#undef linux
#undef mips
#undef near
#undef far
#undef powerpc
#undef unix
#define nimfr_(x, y)
#define nimln_(x, y)
typedef struct tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ;
typedef struct tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA;
typedef struct tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw;
typedef struct tyObject_TType__facALICuu8zUj0hjvbTLFg tyObject_TType__facALICuu8zUj0hjvbTLFg;
typedef struct tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q;
typedef struct NimStringDesc NimStringDesc;
typedef struct TGenericSeq TGenericSeq;
typedef struct tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ;
typedef struct tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA;
typedef struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g;
typedef struct TNimType TNimType;
typedef struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w;
typedef struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ;
typedef struct tyObject_GcStack__7fytPA5bBsob6See21YMRA tyObject_GcStack__7fytPA5bBsob6See21YMRA;
typedef struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg;
typedef struct tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ;
typedef struct tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg;
typedef struct tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw;
typedef struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA;
typedef struct tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw;
typedef struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw;
typedef struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg;
typedef struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyTuple__ujsjpB2O9cjj3uDHsXbnSzg;
typedef struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg;
typedef struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ;
typedef struct tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg;
typedef struct TNimNode TNimNode;
typedef struct tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug;
typedef struct tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w;
typedef struct RootObj RootObj;
typedef struct tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q;
typedef struct tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw;
typedef struct tySequence__eiMlYcU7NrAOGD2H36QOOQ tySequence__eiMlYcU7NrAOGD2H36QOOQ;
typedef struct tyObject_TProcCon__s5jyYR8yL1QmFqiHICzU9aQ tyObject_TProcCon__s5jyYR8yL1QmFqiHICzU9aQ;
typedef struct tyObject_TMatchedConcept__9blNHn9cqK8EfxnwsfjDnKvg tyObject_TMatchedConcept__9blNHn9cqK8EfxnwsfjDnKvg;
typedef struct tySequence__eHqUwlHGGaPw0TDPDeL79cQ tySequence__eHqUwlHGGaPw0TDPDeL79cQ;
typedef struct tySequence__oYkV9aFZe0MXcEAprJaOUsA tySequence__oYkV9aFZe0MXcEAprJaOUsA;
typedef struct tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q;
typedef struct tySequence__Mh9agqM29bm9aP5AUL1x7dZGA tySequence__Mh9agqM29bm9aP5AUL1x7dZGA;
typedef struct tySequence__arD7Tw6eD6lvOczWZl9buNg tySequence__arD7Tw6eD6lvOczWZl9buNg;
typedef struct tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA;
typedef struct tyObject_TrunkcolonObjectType___POcWT53G7t0BSUjc31o0iA tyObject_TrunkcolonObjectType___POcWT53G7t0BSUjc31o0iA;
typedef struct tySequence__Bre9bNyuQOg1EJKitjSzn8w tySequence__Bre9bNyuQOg1EJKitjSzn8w;
typedef struct tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA;
typedef struct tyObject_TCtx__S3Av1Ng7MBWGEZZBhfDYCw tyObject_TCtx__S3Av1Ng7MBWGEZZBhfDYCw;
typedef struct tySequence__jWKvSdankQPoT5bw9cBU9aiw tySequence__jWKvSdankQPoT5bw9cBU9aiw;
typedef struct tyObject_IdentCachecolonObjectType___TzLHS09bRH9a0TYLs39cqcNaw tyObject_IdentCachecolonObjectType___TzLHS09bRH9a0TYLs39cqcNaw;
typedef struct tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ;
typedef struct tySequence__xSqu3cxq5WeFlOO3YgE6yA tySequence__xSqu3cxq5WeFlOO3YgE6yA;
typedef struct tyObject_HashSet__Gy4haGrophX9bC5RxnPAc6w tyObject_HashSet__Gy4haGrophX9bC5RxnPAc6w;
typedef struct tySequence__Bis5AbpONWcIRrPyPJS8Yw tySequence__Bis5AbpONWcIRrPyPJS8Yw;
typedef struct tyObject_Table__Ea0e9azliYta9cYyn0d49ah0w tyObject_Table__Ea0e9azliYta9cYyn0d49ah0w;
typedef struct tySequence__E8pi9b5QNahsURYzXMjh3qw tySequence__E8pi9b5QNahsURYzXMjh3qw;
typedef struct tyObject_Table__svXG3o7j9bfi6HJT79cNF29cQ tyObject_Table__svXG3o7j9bfi6HJT79cNF29cQ;
typedef struct tySequence__Hkw5zrAn53wlKDHdJF1GFA tySequence__Hkw5zrAn53wlKDHdJF1GFA;
typedef struct tySequence__4mZLwkxT8rbt9bf3wXrXYNQ tySequence__4mZLwkxT8rbt9bf3wXrXYNQ;
typedef struct tySequence__rQHmYk1HzcwNxKBymIFHpA tySequence__rQHmYk1HzcwNxKBymIFHpA;
typedef struct tySequence__XMM60DtBsc6xYsIpNANkrA tySequence__XMM60DtBsc6xYsIpNANkrA;
typedef struct tyObject_Table__ZqXrnX212T9bCb4lhpQ9bFBw tyObject_Table__ZqXrnX212T9bCb4lhpQ9bFBw;
typedef struct tySequence__ChDZ6dokJ9aj9cg3KBoCU5vg tySequence__ChDZ6dokJ9aj9cg3KBoCU5vg;
typedef struct tyObject_Table__UVZI5J9aS51B4B0eYPpW1Rg tyObject_Table__UVZI5J9aS51B4B0eYPpW1Rg;
typedef struct tySequence__mWRMiYLthG9coLjkbElCxkw tySequence__mWRMiYLthG9coLjkbElCxkw;
typedef struct tyObject_Table__iowAVDkco3qpbEH0z8OmkQ tyObject_Table__iowAVDkco3qpbEH0z8OmkQ;
typedef struct tySequence__bTDCDwD2P7TodzbAefLcSw tySequence__bTDCDwD2P7TodzbAefLcSw;
typedef struct tyObject_Table__KUYGGgSxi8wBr0SXET9bi3w tyObject_Table__KUYGGgSxi8wBr0SXET9bi3w;
typedef struct tySequence__3MPVXAHA08SszBrU4ffqEg tySequence__3MPVXAHA08SszBrU4ffqEg;
typedef struct tyObject_Table__KcymdZjUsmGSK8BxmvoJgw tyObject_Table__KcymdZjUsmGSK8BxmvoJgw;
typedef struct tySequence__YCf5zJHm4JI06qpmKwPUWg tySequence__YCf5zJHm4JI06qpmKwPUWg;
typedef struct tyObject_Table__Ab4q9c36aMR4mtkEOIBzdzA tyObject_Table__Ab4q9c36aMR4mtkEOIBzdzA;
typedef struct tySequence__7lEisrXlQEzwtUKW5pzRCw tySequence__7lEisrXlQEzwtUKW5pzRCw;
typedef struct tyObject_PackedConfig__McwvRupqDAJbGrinIDFZJQ tyObject_PackedConfig__McwvRupqDAJbGrinIDFZJQ;
typedef struct tyObject_Table__hd3qB0wXU9bWPJR7fjShhbA tyObject_Table__hd3qB0wXU9bWPJR7fjShhbA;
typedef struct tySequence__61s9cbAniKuBrdHwBhMDfQg tySequence__61s9cbAniKuBrdHwBhMDfQg;
typedef struct tyObject_Table__fdKWDDO1P17zvuQPReVgRA tyObject_Table__fdKWDDO1P17zvuQPReVgRA;
typedef struct tySequence__fdmz6VkIf1ewwrssKYqRFg tySequence__fdmz6VkIf1ewwrssKYqRFg;
typedef struct tyObject_Table__e2Ciu0s1q49aVQ7ULXy7l9bQ tyObject_Table__e2Ciu0s1q49aVQ7ULXy7l9bQ;
typedef struct tySequence__kxu4GK0onha2t9bo86mdVAg tySequence__kxu4GK0onha2t9bo86mdVAg;
typedef struct tySequence__48JTohSgTy339bRxHzUD8KA tySequence__48JTohSgTy339bRxHzUD8KA;
typedef struct tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw;
typedef struct tySequence__s9byh6WFJ16lPMcmqdaMTHA tySequence__s9byh6WFJ16lPMcmqdaMTHA;
typedef struct tyObject_Table__Ue6w4c82v7gc7t2qntTbAw tyObject_Table__Ue6w4c82v7gc7t2qntTbAw;
typedef struct tySequence__1U9bG8RcAedEeYkQLZjVFKA tySequence__1U9bG8RcAedEeYkQLZjVFKA;
typedef struct tyObject_Table__G1v8c16HePOldLeucwe05Q tyObject_Table__G1v8c16HePOldLeucwe05Q;
typedef struct tySequence__fIB1rTQ55aFonoft9a9bmljQ tySequence__fIB1rTQ55aFonoft9a9bmljQ;
typedef struct tyObject_Table__0Y2brGGKD9bV6GJLXT9aUDgA tyObject_Table__0Y2brGGKD9bV6GJLXT9aUDgA;
typedef struct tySequence__23SMqauuRsbDANhthj9bWlA tySequence__23SMqauuRsbDANhthj9bWlA;
typedef struct tyObject_Table__NttoEzoiq5CiphZe81oadg tyObject_Table__NttoEzoiq5CiphZe81oadg;
typedef struct tySequence__squ9b9bUH4OLHf6cEMrt6hVA tySequence__squ9b9bUH4OLHf6cEMrt6hVA;
typedef struct tyObject_Table__nagDFX4QHx0s6Fvma9blmSg tyObject_Table__nagDFX4QHx0s6Fvma9blmSg;
typedef struct tySequence__pHNq3oXj9av2sEUdqaqeZjw tySequence__pHNq3oXj9av2sEUdqaqeZjw;
typedef struct tySequence__MAQKEADohlpnXTModtugbQ tySequence__MAQKEADohlpnXTModtugbQ;
typedef struct tyObject_Operators__EbMP71azE1HSvYAQoCH9cXA tyObject_Operators__EbMP71azE1HSvYAQoCH9cXA;
typedef struct tyObject_Target__9abOl5DLX8suLujOaHSvGzw tyObject_Target__9abOl5DLX8suLujOaHSvGzw;
typedef struct tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg;
typedef struct tyObject_MsgConfig__kV7r8HWT0SqOYW2k2ukC6A tyObject_MsgConfig__kV7r8HWT0SqOYW2k2ukC6A;
typedef struct tySequence__tNFrR3kRuS1FSwuiLGoSSA tySequence__tNFrR3kRuS1FSwuiLGoSSA;
typedef struct tySequence__Zi9cGbCWofbtABoHJ5RbLNQ tySequence__Zi9cGbCWofbtABoHJ5RbLNQ;
typedef struct tyObject_HashSet__CD8Dpv0WGmASelVaNSo6zg tyObject_HashSet__CD8Dpv0WGmASelVaNSo6zg;
typedef struct tySequence__4eRCaZmrYLLw2k30GPTiMw tySequence__4eRCaZmrYLLw2k30GPTiMw;
typedef struct tySequence__sM4lkSb7zS6F7OVMvW9cffQ tySequence__sM4lkSb7zS6F7OVMvW9cffQ;
typedef struct tyTuple__47w2DboNEPf69aPgubZdd7Q tyTuple__47w2DboNEPf69aPgubZdd7Q;
typedef struct tySequence__pK3qSsBZwdXd6qyUMkd5Jw tySequence__pK3qSsBZwdXd6qyUMkd5Jw;
typedef struct tyObject_SuggestcolonObjectType___bkMuTTb2G70XfpzAiyNrnQ tyObject_SuggestcolonObjectType___bkMuTTb2G70XfpzAiyNrnQ;
typedef struct tyObject_ProfileDatacolonObjectType___rPBBfFL4X0b9cQ6rfMNPXig tyObject_ProfileDatacolonObjectType___rPBBfFL4X0b9cQ6rfMNPXig;
typedef struct tyTuple__kN8up2W6YKc5YA9avn5mV5w tyTuple__kN8up2W6YKc5YA9avn5mV5w;
typedef struct tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w;
typedef struct tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g;
typedef struct tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A;
typedef struct tyObject_TLoc__EtHNvCB0bgfu9bFjzx9cb6aA tyObject_TLoc__EtHNvCB0bgfu9bFjzx9cb6aA;
typedef struct tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA;
typedef struct tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA;
typedef struct Exception Exception;
typedef struct tySequence__uB9b75OUPRENsBAu4AnoePA tySequence__uB9b75OUPRENsBAu4AnoePA;
typedef struct TSafePoint TSafePoint;
typedef struct tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw;
typedef struct tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w;
typedef struct tyObject_PackedEncoder__B9cE9a0GbvqWW9aHf4N7RAaIw tyObject_PackedEncoder__B9cE9a0GbvqWW9aHf4N7RAaIw;
typedef struct tyObject_PackedModule__ZSxNoR2V6oK5xosmtvhjNQ tyObject_PackedModule__ZSxNoR2V6oK5xosmtvhjNQ;
typedef struct tyObject_Table__TRm6MPqklA8EYBmBMY117Q tyObject_Table__TRm6MPqklA8EYBmBMY117Q;
typedef struct tySequence__9cnx3zXnWzeclW8Ko4oUgAQ tySequence__9cnx3zXnWzeclW8Ko4oUgAQ;
typedef struct tyObject_LoadedModule__14iJKkvOiWT62KF2D8f9c5w tyObject_LoadedModule__14iJKkvOiWT62KF2D8f9c5w;
typedef struct tySequence__PXIzfWocnrafGz5p3CP5LA tySequence__PXIzfWocnrafGz5p3CP5LA;
typedef struct tySequence__9bAGqSvkAaFL9bWjsEPslrFA tySequence__9bAGqSvkAaFL9bWjsEPslrFA;
typedef struct tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw;
typedef struct tySequence__29bS0n2QNyO1R7e0qMMOvLA tySequence__29bS0n2QNyO1R7e0qMMOvLA;
typedef struct tySequence__b89aLriiJnVTD186H6zNIgg tySequence__b89aLriiJnVTD186H6zNIgg;
typedef struct tySequence__REuPuHuSlOkZ0Q5oqzDrQg tySequence__REuPuHuSlOkZ0Q5oqzDrQg;
typedef struct tySequence__I9aQmO9asXXWJ58UI9c8BCSzA tySequence__I9aQmO9asXXWJ58UI9c8BCSzA;
typedef struct tySequence__NyaOkf8ZwxP6rkRF5TOkew tySequence__NyaOkf8ZwxP6rkRF5TOkew;
typedef struct tySequence__L9bOt8CaTEmIjgtuZvp6syg tySequence__L9bOt8CaTEmIjgtuZvp6syg;
typedef struct tySequence__im8UB2GsZvUaQ4a1wKGWhQ tySequence__im8UB2GsZvUaQ4a1wKGWhQ;
typedef struct tySequence__xxnXDLpoqBo8zJzP9b1073g tySequence__xxnXDLpoqBo8zJzP9b1073g;
typedef struct tySequence__DfmUmNgVGnYaiV1I6227tw tySequence__DfmUmNgVGnYaiV1I6227tw;
typedef struct tySequence__t8Uv4lEJ4lkuECvP9c6JMhA tySequence__t8Uv4lEJ4lkuECvP9c6JMhA;
typedef struct tyObject_BiTable__SMd2CpsYscvX1veKoGcqmg tyObject_BiTable__SMd2CpsYscvX1veKoGcqmg;
typedef struct tyObject_BiTable__DyMEQOe8VsqcG49bIhU69bBQ tyObject_BiTable__DyMEQOe8VsqcG49bIhU69bBQ;
typedef struct tySequence__IHUFRsFxZNv7YydiUO2esQ tySequence__IHUFRsFxZNv7YydiUO2esQ;
typedef struct tyObject_Table__CE4eiu6FavV1vmUiTXQ70g tyObject_Table__CE4eiu6FavV1vmUiTXQ70g;
typedef struct tySequence__9bT7o0CflHuiE4VhmtqBPCw tySequence__9bT7o0CflHuiE4VhmtqBPCw;
typedef struct tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg;
typedef struct tyTuple__7q7q3E6Oj24ZNVJb9aonhAg tyTuple__7q7q3E6Oj24ZNVJb9aonhAg;
typedef struct tyTuple__yByxe8FSFNTgs4tcAkTYag tyTuple__yByxe8FSFNTgs4tcAkTYag;
typedef struct tySequence__1I3cxybVrOXM64KW2dfERQ tySequence__1I3cxybVrOXM64KW2dfERQ;
typedef struct tyObject_ImportedModule__kyodd8HBOgfP30dipCL3JQ tyObject_ImportedModule__kyodd8HBOgfP30dipCL3JQ;
typedef struct tyObject_TIdPair__AdFnD2YdADPeuJbG2YJ4vg tyObject_TIdPair__AdFnD2YdADPeuJbG2YJ4vg;
typedef struct tyObject_TInstantiationPair__HkXM4cJmOpk8zFcmq9c9c3gQ tyObject_TInstantiationPair__HkXM4cJmOpk8zFcmq9c9c3gQ;
typedef struct tyObject_TInstantiation__5LqgVn6Tq9ainQRK7TQAQxA tyObject_TInstantiation__5LqgVn6Tq9ainQRK7TQAQxA;
typedef struct tyTuple__KNXySARiHvEh2wA9asnyYmw tyTuple__KNXySARiHvEh2wA9asnyYmw;
typedef struct tyTuple__NAaJgGVgNmlGoqmiWxdOHQ tyTuple__NAaJgGVgNmlGoqmiWxdOHQ;
typedef struct tyTuple__1v9bKyksXWMsm0vNwmZ4EuQ tyTuple__1v9bKyksXWMsm0vNwmZ4EuQ;
typedef struct tyTuple__Y6Ewh3MCxsjd1bsriN6Gag tyTuple__Y6Ewh3MCxsjd1bsriN6Gag;
typedef struct tySequence__vGU8AyGT6KxtLJwEg0BpNw tySequence__vGU8AyGT6KxtLJwEg0BpNw;
typedef struct tyTuple__KvKIqRIx9anKcDMu8DPSkHw tyTuple__KvKIqRIx9anKcDMu8DPSkHw;
typedef struct tyObject_Iface__uvkV248cZcsEQKaQm7C9aEA tyObject_Iface__uvkV248cZcsEQKaQm7C9aEA;
typedef struct tySequence__vv5mGmK03BCr5e3LTZA5Hw tySequence__vv5mGmK03BCr5e3LTZA5Hw;
typedef struct tyTuple__l7R9cf53SDCcRmz9aWTyEKqQ tyTuple__l7R9cf53SDCcRmz9aWTyEKqQ;
typedef struct tySequence__O5RcspOP32YJ4YtU5ppxxA tySequence__O5RcspOP32YJ4YtU5ppxxA;
typedef struct tyObject_LazyType__Q19c34D32PKyTKlx6R6yODg tyObject_LazyType__Q19c34D32PKyTKlx6R6yODg;
typedef struct tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ;
typedef struct tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ;
typedef struct tyTuple__o67sDX0wYbEuhI9cJYAbDtg tyTuple__o67sDX0wYbEuhI9cJYAbDtg;
typedef struct tySequence__Or1y9bNpmj8PM8AcK9c9cg7RA tySequence__Or1y9bNpmj8PM8AcK9c9cg7RA;
typedef struct tyObject_LazyInstantiation__rlce0Sj8mBfLfm69c2yVTZg tyObject_LazyInstantiation__rlce0Sj8mBfLfm69c2yVTZg;
typedef struct tySequence__ipEvhpHAmm8ZCn9bZAOdNYA tySequence__ipEvhpHAmm8ZCn9bZAOdNYA;
typedef struct tyTuple__9aNnDWBFMF44sfFinBpMT4Q tyTuple__9aNnDWBFMF44sfFinBpMT4Q;
typedef struct tyTuple__dT8l9anHpNRgQSBAI9ctQ2wg tyTuple__dT8l9anHpNRgQSBAI9ctQ2wg;
typedef struct tySequence__159bHWBGAOOs6U7OZ9cQlO0g tySequence__159bHWBGAOOs6U7OZ9cQlO0g;
typedef struct tyTuple__VrD6plbUKJjYKM0lCr3hGQ tyTuple__VrD6plbUKJjYKM0lCr3hGQ;
typedef struct tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA;
typedef struct tyTuple__1ZbjBgxAbnye0IFMZ6w4OA tyTuple__1ZbjBgxAbnye0IFMZ6w4OA;
typedef struct tyTuple__xYhUhS7X82rKTqbT9bRfCnw tyTuple__xYhUhS7X82rKTqbT9bRfCnw;
typedef struct tyTuple__rplX06U9bjhu9asm5pWdgqsA tyTuple__rplX06U9bjhu9asm5pWdgqsA;
typedef struct tyTuple__1mtQ8sCEE7DbfIuQciv9b5Q tyTuple__1mtQ8sCEE7DbfIuQciv9b5Q;
typedef struct tyTuple__xDU9bZmv1ZbZkJDaATBekIQ tyTuple__xDU9bZmv1ZbZkJDaATBekIQ;
typedef struct tyTuple__a9bBCAQ2tegdUQVlHYxdJ2A tyTuple__a9bBCAQ2tegdUQVlHYxdJ2A;
typedef struct tyTuple__3i6hlQmqrn6m7tuVN8FHjQ tyTuple__3i6hlQmqrn6m7tuVN8FHjQ;
typedef struct tyTuple__OJFzEczluV8Jmo9bRpBfkzw tyTuple__OJFzEczluV8Jmo9bRpBfkzw;
typedef struct tyTuple__2SGm9aGCXuo7XSQ9bqD29axXw tyTuple__2SGm9aGCXuo7XSQ9bqD29axXw;
typedef struct tyTuple__F3gkSrMB1qp2Tvf9bixVXwg tyTuple__F3gkSrMB1qp2Tvf9bixVXwg;
typedef struct tyTuple__wcNatyuf8WOqAhGLhSvgiw tyTuple__wcNatyuf8WOqAhGLhSvgiw;
typedef struct tyObject_BTree__VZdzO0Tlflp7WMN4gS8oPg tyObject_BTree__VZdzO0Tlflp7WMN4gS8oPg;
typedef struct tyObject_NodecolonObjectType___dNELmBSmY7nthjhZupWO6g tyObject_NodecolonObjectType___dNELmBSmY7nthjhZupWO6g;
typedef struct tyTuple__4o9cW9aUwdGqgZI9bSHHYnbaQ tyTuple__4o9cW9aUwdGqgZI9bSHHYnbaQ;
typedef struct tyTuple__z822nu9bFF1AlQnLrHjdwpA tyTuple__z822nu9bFF1AlQnLrHjdwpA;
typedef struct tyObject_TFileInfo__GE3hAakXKOEpch4ap3zXAw tyObject_TFileInfo__GE3hAakXKOEpch4ap3zXAw;
typedef struct tyTuple__QeWl6B6ffS4pU6WWrtcrDw tyTuple__QeWl6B6ffS4pU6WWrtcrDw;
typedef struct tyObject_StackTraceEntry__oLyohQ7O2XOvGnflOss8EA tyObject_StackTraceEntry__oLyohQ7O2XOvGnflOss8EA;
typedef struct tyTuple__UvldbCB6B9ayi9bGYW7vJNLA tyTuple__UvldbCB6B9ayi9bGYW7vJNLA;
typedef struct tyTuple__0q9cmhneJEKnQERTpXXdz6Q tyTuple__0q9cmhneJEKnQERTpXXdz6Q;
typedef struct tyObject_PackedNode__7lDGAZiNp4zbO65GEpoKow tyObject_PackedNode__7lDGAZiNp4zbO65GEpoKow;
typedef struct tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg;
typedef struct tyTuple__Izx9aRSX9a0diDXD84jOS9aMQ tyTuple__Izx9aRSX9a0diDXD84jOS9aMQ;
typedef struct tyTuple__Q7r9caOmeWqQGZCIBHhGRUA tyTuple__Q7r9caOmeWqQGZCIBHhGRUA;
typedef struct tyTuple__7Wlwbz8zSe7Udyf7mmsd9cg tyTuple__7Wlwbz8zSe7Udyf7mmsd9cg;
typedef struct tyTuple__XyJ8LOAZzVVXSsmt09b8uWw tyTuple__XyJ8LOAZzVVXSsmt09b8uWw;
typedef struct tyObject_PackedInstantiation__39cWRURu69agjI9c1ohiUmxiA tyObject_PackedInstantiation__39cWRURu69agjI9c1ohiUmxiA;
typedef struct tySequence__vC9cvg0R8tfBaOXXi3sfMzw tySequence__vC9cvg0R8tfBaOXXi3sfMzw;
typedef struct tyTuple__9aoobCDZB4x41HJSOmh0mwA tyTuple__9aoobCDZB4x41HJSOmh0mwA;
typedef struct tyTuple__g0Q6Qx15nK53ce9aLo7YyrA tyTuple__g0Q6Qx15nK53ce9aLo7YyrA;
typedef struct tyObject_PackedSym__XjVn21MwvH8ij6CfopYZWw tyObject_PackedSym__XjVn21MwvH8ij6CfopYZWw;
typedef struct tyObject_PackedLib__oa01YzfeXO9bbIDH9cIki4Hw tyObject_PackedLib__oa01YzfeXO9bbIDH9cIki4Hw;
typedef struct tyObject_PackedType__IhXsK7mrwumUBtEqbZ2BqA tyObject_PackedType__IhXsK7mrwumUBtEqbZ2BqA;
typedef struct tyTuple__8x6vq4Dc9aLvKX9actMeR9avQ tyTuple__8x6vq4Dc9aLvKX9actMeR9avQ;
typedef struct tyTuple__FyNGItFCBJSXLJ9aJSzlX9aw tyTuple__FyNGItFCBJSXLJ9aJSzlX9aw;
struct tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA {
NI a;
NI b;
};
struct tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q {
NU16 line;
NI16 col;
NI32 fileIndex;
};
typedef NU32 tySet_tyEnum_TNodeFlag__jyh9acXHkhZANSSvPIY7ZLg;
typedef NU8 tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw;
struct TGenericSeq {
NI len;
NI reserved;
};
struct NimStringDesc {
TGenericSeq Sup;
NIM_CHAR data[SEQ_DECL_SIZE];
};
struct tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw {
tyObject_TType__facALICuu8zUj0hjvbTLFg* typ;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info;
tySet_tyEnum_TNodeFlag__jyh9acXHkhZANSSvPIY7ZLg flags;
tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind;
union{
struct {NI64 intVal;
} _kind_1;
struct {NF floatVal;
} _kind_2;
struct {NimStringDesc* strVal;
} _kind_3;
struct {tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym;
} _kind_4;
struct {tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* ident;
} _kind_5;
struct {tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ* sons;
} _kind_6;
};
};
struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g {
NI refcount;
TNimType* typ;
};
struct tyObject_GcStack__7fytPA5bBsob6See21YMRA {
void* bottom;
};
struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w {
NI len;
NI cap;
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g** d;
};
typedef tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ* tyArray__SPr7N6UKfuF549bNPiUvSRw[256];
typedef NU32 tyArray__BHbOSqU1t9b3Gt7K2c6fQig[24];
typedef tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* tyArray__N1u1nqOgmuJN9cSZrnMHgOQ[32];
typedef tyArray__N1u1nqOgmuJN9cSZrnMHgOQ tyArray__B6durA4ZCi1xjJvRtyYxMg[24];
typedef tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw* tyArray__lh2A89ahMmYg9bCmpVaplLbA[256];
struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA {
tyArray__lh2A89ahMmYg9bCmpVaplLbA data;
};
typedef tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* tyArray__0aOLqZchNi8nWtMTi8ND8w[2];
struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw {
tyArray__0aOLqZchNi8nWtMTi8ND8w link;
NI key;
NI upperBound;
NI level;
};
struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg {
tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* Field0;
NI Field1;
};
typedef tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyArray__LzOv2eCDGiceMKQstCLmhw[30];
struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg {
NI len;
tyArray__LzOv2eCDGiceMKQstCLmhw chunks;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg* next;
};
struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg {
NI minLargeObj;
NI maxLargeObj;
tyArray__SPr7N6UKfuF549bNPiUvSRw freeSmallChunks;
NU32 flBitmap;
tyArray__BHbOSqU1t9b3Gt7K2c6fQig slBitmap;
tyArray__B6durA4ZCi1xjJvRtyYxMg matrix;
tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw* llmem;
NI currMem;
NI maxMem;
NI freeMem;
NI occ;
NI lastSize;
tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA chunkStarts;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* root;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* deleted;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* last;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* freeAvlNodes;
NIM_BOOL locked;
NIM_BOOL blockChunkSizeIncrease;
NI nextChunkSize;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw bottomData;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg heapLinks;
};
struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg {
NI stackScans;
NI cycleCollections;
NI maxThreshold;
NI maxStackSize;
NI maxStackCells;
NI cycleTableSize;
NI64 maxPause;
};
struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ {
NI counter;
NI max;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg* head;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg** data;
};
struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ {
tyObject_GcStack__7fytPA5bBsob6See21YMRA stack;
NI cycleThreshold;
NI zctThreshold;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w zct;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w decStack;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tempStack;
NI recGcLock;
tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg region;
tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg stat;
tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ marked;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w additionalRoots;
NI gcThreadId;
};
typedef NU8 tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A;
typedef NU8 tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ;
typedef N_NIMCALL_PTR(void, tyProc__ojoeKfW4VYIm36I9cpDTQIg) (void* p, NI op);
typedef N_NIMCALL_PTR(void*, tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ) (void* p);
struct TNimType {
NI size;
NI align;
tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A kind;
tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ flags;
TNimType* base;
TNimNode* node;
void* finalizer;
tyProc__ojoeKfW4VYIm36I9cpDTQIg marker;
tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ deepcopy;
};
typedef NU8 tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ;
struct TNimNode {
tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ kind;
NI offset;
TNimType* typ;
NCSTRING name;
NI len;
TNimNode** sons;
};
typedef NU16 tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw;
struct tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA {
NI id;
NimStringDesc* s;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* next;
NI h;
};
typedef NU8 tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw[37];
typedef NU8 tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug;
typedef NU8 tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w;
struct RootObj {
TNimType* m_type;
};
struct tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w {
RootObj Sup;
tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q* idgen;
};
typedef tyObject_TType__facALICuu8zUj0hjvbTLFg* tyArray__d88NmFOoQ1OEoX9af4f9aptg[38];
struct tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q {
NI counter;
tySequence__Mh9agqM29bm9aP5AUL1x7dZGA* data;
};
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__RcJNn9bSvWdJgUmA1O6sbHA) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
typedef NU32 tySet_tyEnum_TExprFlag__0WWd9a4ssQWuY7Q6ZKepq9cQ;
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__39auogS0nN05zO6JrT7za9cQ) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TExprFlag__0WWd9a4ssQWuY7Q6ZKepq9cQ flags);
typedef N_NIMCALL_PTR(NIM_BOOL, tyProc__DZXD9cPwIfL76eNszoUR9aVA) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TType__facALICuu8zUj0hjvbTLFg* t);
typedef struct {
N_NIMCALL_PTR(NIM_BOOL, ClP_0) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, void* ClE_0);
void* ClE_0;
} tyProc__7JwrY3AhkVNlleAJXClX9cw;
typedef NU32 tySet_tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw;
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__qlV9aWvA5wrWVg9bI5PqwJyA) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* nOrig, tySet_tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw filter, tySet_tyEnum_TExprFlag__0WWd9a4ssQWuY7Q6ZKepq9cQ flags);
typedef N_NIMCALL_PTR(tyObject_TType__facALICuu8zUj0hjvbTLFg*, tyProc__IDzB9bjws1yntQXPpMRrBvA) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TType__facALICuu8zUj0hjvbTLFg* prev);
typedef struct {
N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, ClP_0) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q pt, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, void* ClE_0);
void* ClE_0;
} tyProc__3cacbJ4la9bDJNibHybQSnA;
typedef struct {
N_NIMCALL_PTR(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, ClP_0) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* fn, tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q pt, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, void* ClE_0);
void* ClE_0;
} tyProc__fMj9boIZZOt9cLWRnD3rtKhA;
typedef NI tyArray__emiAJ8okywrJw7ZHLzlXbQ[34];
struct tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA {
NI elems;
NI counter;
NI max;
tyObject_TrunkcolonObjectType___POcWT53G7t0BSUjc31o0iA* head;
tySequence__Bre9bNyuQOg1EJKitjSzn8w* data;
tyArray__emiAJ8okywrJw7ZHLzlXbQ a;
};
struct tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA {
NI counter;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* data;
};
typedef NU8 tyEnum_TTypeAttachedOp__Rp5P9bWYldQTLkZ7DytmxOg;
typedef N_NIMCALL_PTR(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, tyProc__zh0Qj9bYHDZFnJnPjcxz6NQ) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* dc, tyObject_TType__facALICuu8zUj0hjvbTLFg* t, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyEnum_TTypeAttachedOp__Rp5P9bWYldQTLkZ7DytmxOg op, NI col);
typedef NU32 tySet_tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ;
struct tyObject_HashSet__Gy4haGrophX9bC5RxnPAc6w {
tySequence__Bis5AbpONWcIRrPyPJS8Yw* data;
NI counter;
};
struct tyObject_Table__Ea0e9azliYta9cYyn0d49ah0w {
tySequence__E8pi9b5QNahsURYzXMjh3qw* data;
NI counter;
};
struct tyObject_Table__svXG3o7j9bfi6HJT79cNF29cQ {
tySequence__Hkw5zrAn53wlKDHdJF1GFA* data;
NI counter;
};
struct tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug {
tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w Sup;
tyObject_TType__facALICuu8zUj0hjvbTLFg* enforceVoidContext;
tyObject_TType__facALICuu8zUj0hjvbTLFg* voidType;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* module;
tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* currentScope;
tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* moduleScope;
tySequence__eiMlYcU7NrAOGD2H36QOOQ* imports;
tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* topLevelScope;
tyObject_TProcCon__s5jyYR8yL1QmFqiHICzU9aQ* p;
tyArray__d88NmFOoQ1OEoX9af4f9aptg intTypeCache;
tyObject_TType__facALICuu8zUj0hjvbTLFg* nilTypeCache;
tyObject_TMatchedConcept__9blNHn9cqK8EfxnwsfjDnKvg* matchedConcept;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* friendModules;
NI instCounter;
NI* templInstCounter;
NI inGenericContext;
NI inStaticContext;
NI inUnrolledContext;
NI compilesContextId;
NI compilesContextIdGenerator;
NI inGenericInst;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* converters;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* patterns;
tySequence__oYkV9aFZe0MXcEAprJaOUsA* optionStack;
tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q symMapping;
tySequence__arD7Tw6eD6lvOczWZl9buNg* libs;
tyProc__RcJNn9bSvWdJgUmA1O6sbHA semConstExpr;
tyProc__39auogS0nN05zO6JrT7za9cQ semExpr;
tyProc__39auogS0nN05zO6JrT7za9cQ semTryExpr;
tyProc__RcJNn9bSvWdJgUmA1O6sbHA semTryConstExpr;
tyProc__DZXD9cPwIfL76eNszoUR9aVA computeRequiresInit;
tyProc__7JwrY3AhkVNlleAJXClX9cw hasUnresolvedArgs;
tyProc__39auogS0nN05zO6JrT7za9cQ semOperand;
tyProc__RcJNn9bSvWdJgUmA1O6sbHA semConstBoolExpr;
tyProc__qlV9aWvA5wrWVg9bI5PqwJyA semOverloadedCall;
tyProc__IDzB9bjws1yntQXPpMRrBvA semTypeNode;
tyProc__3cacbJ4la9bDJNibHybQSnA semInferredLambda;
tyProc__fMj9boIZZOt9cLWRnD3rtKhA semGenerateInstance;
tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA includedFiles;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA pureEnumFields;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA userPragmas;
tyObject_TCtx__S3Av1Ng7MBWGEZZBhfDYCw* evalContext;
tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA unknownIdents;
tySequence__jWKvSdankQPoT5bw9cBU9aiw* generics;
NI topStmts;
NI lastGenericIdx;
NI hloLoopDetector;
NI inParallelStmt;
tyProc__zh0Qj9bYHDZFnJnPjcxz6NQ instTypeBoundOp;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* selfName;
tyObject_IdentCachecolonObjectType___TzLHS09bRH9a0TYLs39cqcNaw* cache;
tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA signatures;
NimStringDesc* recursiveDep;
NIM_BOOL suggestionsMade;
NIM_BOOL isAmbiguous;
tySet_tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ features;
NI inTypeContext;
NI inConceptDecl;
tySequence__xSqu3cxq5WeFlOO3YgE6yA* unusedImports;
tyObject_HashSet__Gy4haGrophX9bC5RxnPAc6w exportIndirections;
tyObject_Table__Ea0e9azliYta9cYyn0d49ah0w importModuleMap;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q lastTLineInfo;
tyObject_Table__svXG3o7j9bfi6HJT79cNF29cQ sideEffects;
NI inUncheckedAssignSection;
};
struct tyObject_Table__ZqXrnX212T9bCb4lhpQ9bFBw {
tySequence__ChDZ6dokJ9aj9cg3KBoCU5vg* data;
NI counter;
};
struct tyObject_Table__UVZI5J9aS51B4B0eYPpW1Rg {
tySequence__mWRMiYLthG9coLjkbElCxkw* data;
NI counter;
};
struct tyObject_Table__iowAVDkco3qpbEH0z8OmkQ {
tySequence__bTDCDwD2P7TodzbAefLcSw* data;
NI counter;
};
typedef tyObject_Table__iowAVDkco3qpbEH0z8OmkQ tyArray__pxY9cgs6r9cBvGwlO8XZ9ccbQ[5];
struct tyObject_Table__KUYGGgSxi8wBr0SXET9bi3w {
tySequence__3MPVXAHA08SszBrU4ffqEg* data;
NI counter;
};
struct tyObject_Table__KcymdZjUsmGSK8BxmvoJgw {
tySequence__YCf5zJHm4JI06qpmKwPUWg* data;
NI counter;
};
struct tyObject_Table__Ab4q9c36aMR4mtkEOIBzdzA {
tySequence__7lEisrXlQEzwtUKW5pzRCw* data;
NI counter;
};
typedef NU8 tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g;
typedef NU8 tyEnum_TGCMode__tkz389aDYNd8ykeZszCuBSw;
typedef NU8 tyEnum_TSystemCC__1eWBJUonHMOnlBwsOvpFmA;
typedef NU32 tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg;
typedef NU64 tySet_tyEnum_TGlobalOption__RAfAEZqjnKMDumgyKKc1qw;
struct tyObject_PackedConfig__McwvRupqDAJbGrinIDFZJQ {
tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g backend;
tyEnum_TGCMode__tkz389aDYNd8ykeZszCuBSw selectedGC;
tyEnum_TSystemCC__1eWBJUonHMOnlBwsOvpFmA cCompiler;
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options;
tySet_tyEnum_TGlobalOption__RAfAEZqjnKMDumgyKKc1qw globalOptions;
};
struct tyObject_Table__hd3qB0wXU9bWPJR7fjShhbA {
tySequence__61s9cbAniKuBrdHwBhMDfQg* data;
NI counter;
};
struct tyObject_Table__fdKWDDO1P17zvuQPReVgRA {
tySequence__fdmz6VkIf1ewwrssKYqRFg* data;
NI counter;
};
struct tyObject_Table__e2Ciu0s1q49aVQ7ULXy7l9bQ {
tySequence__kxu4GK0onha2t9bo86mdVAg* data;
NI counter;
};
typedef struct {
N_NIMCALL_PTR(NIM_BOOL, ClP_0) (void* ClE_0);
void* ClE_0;
} tyProc__In3g79a0qTcRmbTbJp9ba9ctg;
typedef tyObject_TType__facALICuu8zUj0hjvbTLFg* tyArray__9bjuenwQUcqO3lbmS2wX7uA[65];
struct tyObject_Table__Ue6w4c82v7gc7t2qntTbAw {
tySequence__1U9bG8RcAedEeYkQLZjVFKA* data;
NI counter;
};
struct tyObject_Table__G1v8c16HePOldLeucwe05Q {
tySequence__fIB1rTQ55aFonoft9a9bmljQ* data;
NI counter;
};
typedef N_NIMCALL_PTR(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, tyProc__VHDwJFdIqpwtpUGuxiXUwg) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* m, NI32 fileIdx);
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__mjUN9alLJ31lnSKkUsuyWMw) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* m, NI32 fileIdx);
struct tyObject_Table__0Y2brGGKD9bV6GJLXT9aUDgA {
tySequence__23SMqauuRsbDANhthj9bWlA* data;
NI counter;
};
struct tyObject_Table__NttoEzoiq5CiphZe81oadg {
tySequence__squ9b9bUH4OLHf6cEMrt6hVA* data;
NI counter;
};
struct tyObject_Table__nagDFX4QHx0s6Fvma9blmSg {
tySequence__pHNq3oXj9av2sEUdqaqeZjw* data;
NI counter;
};
typedef N_NIMCALL_PTR(void, tyProc__TjycsqkDBjsxd4da6KYTng) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
typedef N_NIMCALL_PTR(void, tyProc__Mrj9cEgtPER9bAXMDB9cTXrfQ) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* body);
typedef N_NIMCALL_PTR(NIM_BOOL, tyProc__J7Jq15ZScfKLqcLx8sEz9cA) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TType__facALICuu8zUj0hjvbTLFg* formal, tyObject_TType__facALICuu8zUj0hjvbTLFg* actual);
struct tyObject_Operators__EbMP71azE1HSvYAQoCH9cXA {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opNot;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opContains;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opLe;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opLt;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opAnd;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opOr;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opIsNil;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opEq;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opAdd;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opSub;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opMul;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opDiv;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* opLen;
};
struct tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ {
tySequence__4mZLwkxT8rbt9bf3wXrXYNQ* ifaces;
tySequence__rQHmYk1HzcwNxKBymIFHpA* packed_0;
tySequence__XMM60DtBsc6xYsIpNANkrA* encoders;
tyObject_Table__ZqXrnX212T9bCb4lhpQ9bFBw typeInstCache;
tyObject_Table__UVZI5J9aS51B4B0eYPpW1Rg procInstCache;
tyArray__pxY9cgs6r9cBvGwlO8XZ9ccbQ attachedOps;
tyObject_Table__KUYGGgSxi8wBr0SXET9bi3w methodsPerType;
tyObject_Table__KcymdZjUsmGSK8BxmvoJgw enumToStringProcs;
tyObject_Table__Ab4q9c36aMR4mtkEOIBzdzA emittedTypeInfo;
tyObject_PackedConfig__McwvRupqDAJbGrinIDFZJQ startupPackedConfig;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA packageSyms;
tyObject_Table__hd3qB0wXU9bWPJR7fjShhbA modulesPerPackage;
tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA deps;
tyObject_Table__fdKWDDO1P17zvuQPReVgRA importDeps;
NIM_BOOL suggestMode;
NIM_BOOL invalidTransitiveClosure;
tyObject_Table__e2Ciu0s1q49aVQ7ULXy7l9bQ inclToMod;
tySequence__48JTohSgTy339bRxHzUD8KA* importStack;
RootObj* backend;
tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* config;
tyObject_IdentCachecolonObjectType___TzLHS09bRH9a0TYLs39cqcNaw* cache;
RootObj* vm;
tyProc__In3g79a0qTcRmbTbJp9ba9ctg doStopCompile;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* usageSym;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* owners;
tySequence__s9byh6WFJ16lPMcmqdaMTHA* methods;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* systemModule;
tyArray__9bjuenwQUcqO3lbmS2wX7uA sysTypes;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA compilerprocs;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA exposed;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA packageTypes;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* emptyNode;
tyObject_Table__Ue6w4c82v7gc7t2qntTbAw canonTypes;
tyObject_Table__G1v8c16HePOldLeucwe05Q symBodyHashes;
tyProc__VHDwJFdIqpwtpUGuxiXUwg importModuleCallback;
tyProc__mjUN9alLJ31lnSKkUsuyWMw includeFileCallback;
tyObject_Table__0Y2brGGKD9bV6GJLXT9aUDgA cacheSeqs;
tyObject_Table__NttoEzoiq5CiphZe81oadg cacheCounters;
tyObject_Table__nagDFX4QHx0s6Fvma9blmSg cacheTables;
tySequence__MAQKEADohlpnXTModtugbQ* passes;
tyProc__TjycsqkDBjsxd4da6KYTng onDefinition;
tyProc__TjycsqkDBjsxd4da6KYTng onDefinitionResolveForward;
tyProc__TjycsqkDBjsxd4da6KYTng onUsage;
tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ* globalDestructors;
tyProc__Mrj9cEgtPER9bAXMDB9cTXrfQ strongSemCheck;
tyProc__J7Jq15ZScfKLqcLx8sEz9cA compatibleProps;
tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q* idgen;
tyObject_Operators__EbMP71azE1HSvYAQoCH9cXA operators;
};
typedef NU8 tyEnum_TSystemCPU__XYDt7D1G3qcClFyZy1Ky9ag;
typedef NU8 tyEnum_TSystemOS__s7Mlr1t66SUqP6BKJMXLaQ;
struct tyObject_Target__9abOl5DLX8suLujOaHSvGzw {
tyEnum_TSystemCPU__XYDt7D1G3qcClFyZy1Ky9ag targetCPU;
tyEnum_TSystemCPU__XYDt7D1G3qcClFyZy1Ky9ag hostCPU;
tyEnum_TSystemOS__s7Mlr1t66SUqP6BKJMXLaQ targetOS;
tyEnum_TSystemOS__s7Mlr1t66SUqP6BKJMXLaQ hostOS;
NI intSize;
NI floatSize;
NI ptrSize;
NimStringDesc* tnl;
};
typedef NU8 tySet_tyEnum_TErrorOutput__fBf8Teueoz9aAkO5cXaxrpA;
struct tyObject_MsgConfig__kV7r8HWT0SqOYW2k2ukC6A {
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q trackPos;
NIM_BOOL trackPosAttached;
tySet_tyEnum_TErrorOutput__fBf8Teueoz9aAkO5cXaxrpA errorOutputs;
tySequence__tNFrR3kRuS1FSwuiLGoSSA* msgContext;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q lastError;
tyObject_Table__Ab4q9c36aMR4mtkEOIBzdzA filenameToIndexTbl;
tySequence__Zi9cGbCWofbtABoHJ5RbLNQ* fileInfos;
NI32 systemFileIdx;
};
typedef NU8 tyEnum_FilenameOption__eL86bAtPxXWHj24F5gOMFQ;
typedef NU8 tyEnum_Command__0zjcIQ623TIRGPdtjLwTFA;
typedef NU8 tyEnum_ExceptionSystem__1mkAogyaDAT7g9cQjzsgKLQ;
typedef NU8 tyEnum_SymbolFilesOption__gBES9bqm1ru9ape8SeMRAFgQ;
struct tyObject_HashSet__CD8Dpv0WGmASelVaNSo6zg {
tySequence__4eRCaZmrYLLw2k30GPTiMw* data;
NI counter;
};
typedef NU8 tySet_tyEnum_LegacyFeature__hGCD9aOrxPvpXn4Ne6W6OVA;
typedef NU8 tyEnum_IdeCmd__1Ced39bl5eePmZ1PKMPXigQ;
typedef NU8 tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug[11];
struct tyTuple__47w2DboNEPf69aPgubZdd7Q {
NI Field0;
NI Field1;
NI Field2;
};
typedef NU8 tySet_tyEnum_StdOrrKind__6cbmyTzDPaZU9afMe4mz3Ug;
typedef struct {
N_NIMCALL_PTR(void, ClP_0) (tyObject_SuggestcolonObjectType___bkMuTTb2G70XfpzAiyNrnQ* result, void* ClE_0);
void* ClE_0;
} tyProc__YD0MR9bJ2x4beJkZdnjXN9cA;
typedef struct {
N_NIMCALL_PTR(void, ClP_0) (NimStringDesc* output, void* ClE_0);
void* ClE_0;
} tyProc__k2HFjxisIgDALbEUFojxaQ;
typedef NU8 tyEnum_Severity__x5BWBPGAbIH9clm5pmNp5DA;
typedef struct {
N_NIMCALL_PTR(void, ClP_0) (tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* config, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, NimStringDesc* msg, tyEnum_Severity__x5BWBPGAbIH9clm5pmNp5DA severity, void* ClE_0);
void* ClE_0;
} tyProc__oL9coyIA2VDTGdUcur9aL9bew;
struct tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw {
tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g backend;
tyObject_Target__9abOl5DLX8suLujOaHSvGzw target;
NI linesCompiled;
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options;
tySet_tyEnum_TGlobalOption__RAfAEZqjnKMDumgyKKc1qw globalOptions;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* macrosToExpand;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* arcToExpand;
tyObject_MsgConfig__kV7r8HWT0SqOYW2k2ukC6A m;
tyEnum_FilenameOption__eL86bAtPxXWHj24F5gOMFQ filenameOption;
NimStringDesc* unitSep;
NI evalTemplateCounter;
NI evalMacroCounter;
NI8 exitcode;
tyEnum_Command__0zjcIQ623TIRGPdtjLwTFA cmd;
NimStringDesc* cmdInput;
NIM_BOOL projectIsCmd;
NIM_BOOL implicitCmd;
tyEnum_TGCMode__tkz389aDYNd8ykeZszCuBSw selectedGC;
tyEnum_ExceptionSystem__1mkAogyaDAT7g9cQjzsgKLQ exc;
NIM_BOOL hintProcessingDots;
NI verbosity;
NI numberOfProcessors;
NF lastCmdTime;
tyEnum_SymbolFilesOption__gBES9bqm1ru9ape8SeMRAFgQ symbolFiles;
NI spellSuggestMax;
tyObject_HashSet__CD8Dpv0WGmASelVaNSo6zg cppDefines;
NimStringDesc* headerFile;
tySet_tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ features;
tySet_tyEnum_LegacyFeature__hGCD9aOrxPvpXn4Ne6W6OVA legacyFeatures;
NimStringDesc* arguments;
tyEnum_IdeCmd__1Ced39bl5eePmZ1PKMPXigQ ideCmd;
NIM_BOOL oldNewlines;
tyEnum_TSystemCC__1eWBJUonHMOnlBwsOvpFmA cCompiler;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug modifiedyNotes;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug cmdlineNotes;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug foreignPackageNotes;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug notes;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug warningAsErrors;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug mainPackageNotes;
NI mainPackageId;
NI errorCounter;
NI hintCounter;
NI warnCounter;
NI errorMax;
NI maxLoopIterationsVM;
NIM_BOOL isVmTrace;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* configVars;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* symbols;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* packageCache;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* nimblePaths;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* searchPaths;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* lazyPaths;
NimStringDesc* outFile;
NimStringDesc* outDir;
NimStringDesc* jsonBuildFile;
NimStringDesc* prefixDir;
NimStringDesc* libpath;
NimStringDesc* nimcacheDir;
tyTuple__47w2DboNEPf69aPgubZdd7Q nimStdlibVersion;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* dllOverrides;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* moduleOverrides;
tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* cfileSpecificOptions;
NimStringDesc* projectName;
NimStringDesc* projectPath;
NimStringDesc* projectFull;
NIM_BOOL projectIsStdin;
tySet_tyEnum_StdOrrKind__6cbmyTzDPaZU9afMe4mz3Ug lastMsgWasDot;
NI32 projectMainIdx;
NI32 projectMainIdx2;
NimStringDesc* command;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* commandArgs;
NimStringDesc* commandLine;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* extraCmds;
NIM_BOOL keepComments;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* implicitImports;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* implicitIncludes;
NimStringDesc* docSeeSrcUrl;
NimStringDesc* docRoot;
NimStringDesc* docCmd;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* configFiles;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* cIncludes;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* cLibs;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* cLinkedLibs;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* externalToLink;
NimStringDesc* linkOptionsCmd;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* compileOptionsCmd;
NimStringDesc* linkOptions;
NimStringDesc* compileOptions;
NimStringDesc* cCompilerPath;
tySequence__pK3qSsBZwdXd6qyUMkd5Jw* toCompile;
tyProc__YD0MR9bJ2x4beJkZdnjXN9cA suggestionResultHook;
NI suggestVersion;
NI suggestMaxResults;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q lastLineInfo;
tyProc__k2HFjxisIgDALbEUFojxaQ writelnHook;
tyProc__oL9coyIA2VDTGdUcur9aL9bew structuredErrorHook;
NimStringDesc* cppCustomNamespace;
NimStringDesc* nimMainPrefix;
tyObject_ProfileDatacolonObjectType___rPBBfFL4X0b9cQ6rfMNPXig* vmProfileData;
};
typedef NU8 tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw;
struct tyTuple__kN8up2W6YKc5YA9avn5mV5w {
NimStringDesc* Field0;
NI Field1;
NI Field2;
};
typedef NU16 tySet_tyEnum_TRenderFlag__wrPgUo1ExBlHvFnXN2nSHw;
typedef N_CLOSURE_PTR(NIM_BOOL, TM__tPA3StZ6VsKyoznyrIfFxg_9) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
struct tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g {
NI32 module;
NI32 item;
};
struct tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w {
RootObj Sup;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g itemId;
};
typedef NU8 tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag;
typedef NU8 tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA;
typedef NU64 tySet_tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw;
typedef NU8 tyEnum_TLocKind__O7PRFZKuiBBWbku09cayVBg;
typedef NU8 tyEnum_TStorageLoc__JK9cKMX3XnqHaUky9b6gkGEw;
typedef NU16 tySet_tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA;
struct tyObject_TLoc__EtHNvCB0bgfu9bFjzx9cb6aA {
tyEnum_TLocKind__O7PRFZKuiBBWbku09cayVBg k;
tyEnum_TStorageLoc__JK9cKMX3XnqHaUky9b6gkGEw storage;
tySet_tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA flags;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* lode;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r;
};
struct tyObject_TType__facALICuu8zUj0hjvbTLFg {
tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w Sup;
tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag kind;
tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA callConv;
tySet_tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw flags;
tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A* sons;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym;
NI64 size;
NI16 align;
NI16 paddingAtEnd;
NI16 lockLevel;
tyObject_TLoc__EtHNvCB0bgfu9bFjzx9cb6aA loc;
tyObject_TType__facALICuu8zUj0hjvbTLFg* typeInst;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g uniqueId;
};
typedef NU8 tySet_tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag[9];
typedef tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* tyArray__jlWPjgtbdjE069arIWHC9c9bg[1];
typedef tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* tyArray__AB6yfoUgfWM2NtGe9bzkCmw[2];
typedef NU8 tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw;
typedef NU16 tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg;
typedef NU64 tySet_tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw;
struct tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ {
tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w Sup;
tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw kind;
union{
struct {tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* gcUnsafetyReason;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* transformedBody;
} _kind_1;
struct {tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* guard;
NI bitsize;
NI alignment;
} _kind_2;
};
tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg magic;
tyObject_TType__facALICuu8zUj0hjvbTLFg* typ;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* name;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner;
tySet_tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw flags;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* ast;
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options;
NI position;
NI offset;
tyObject_TLoc__EtHNvCB0bgfu9bFjzx9cb6aA loc;
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* annex;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* constraint;
};
typedef NU8 tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw;
typedef NU8 tyEnum_TNodeKind__Dq0DNfMwTBUf7hLFKKDU7g;
struct tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA {
RootObj Sup;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* left;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* right;
NI L;
NimStringDesc* data;
};
struct Exception {
RootObj Sup;
Exception* parent;
NCSTRING name;
NimStringDesc* message;
tySequence__uB9b75OUPRENsBAu4AnoePA* trace;
Exception* up;
};
struct TSafePoint {
TSafePoint* prev;
NI status;
jmp_buf context;
};
typedef NU8 tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA;
typedef NimStringDesc* tyArray__Re75IspeoxXy2oCZHwcRrA[2];
typedef NU8 tyEnum_TGlobalOption__RAfAEZqjnKMDumgyKKc1qw;
typedef NU8 tySet_tyChar__nmiMWKVIe46vacnhAFrQvw[32];
struct tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw {
RootObj Sup;
NI colonstate_;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner1;
};
typedef struct {
N_NIMCALL_PTR(void, ClP_0) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, void* ClE_0);
void* ClE_0;
} tyProc__BuyrpAaTYqHepBvBU6qokA;
typedef N_CLOSURE_PTR(void, TM__tPA3StZ6VsKyoznyrIfFxg_44) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
typedef N_CLOSURE_PTR(void, TM__tPA3StZ6VsKyoznyrIfFxg_45) (tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
typedef NU8 tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ;
typedef NU8 tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ;
struct tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA {
tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ kind;
NIM_BOOL generated;
NIM_BOOL isOverriden;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* name;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* path;
};
typedef NU8 tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw;
struct tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w {
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options;
tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA defaultCC;
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* dynlib;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug notes;
tySet_tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ features;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* otherPragmas;
tySet_tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug warningAsErrors;
};
struct tyObject_Table__TRm6MPqklA8EYBmBMY117Q {
tySequence__9cnx3zXnWzeclW8Ko4oUgAQ* data;
NI counter;
};
struct tyObject_PackedEncoder__B9cE9a0GbvqWW9aHf4N7RAaIw {
NI32 thisModule;
NI32 lastFile;
NU32 lastLit;
tyObject_Table__TRm6MPqklA8EYBmBMY117Q filenames;
tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A* pendingTypes;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* pendingSyms;
tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA typeMarker;
tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA symMarker;
tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* config;
};
typedef NU8 tyEnum_ModuleStatus__MgSLMPwZ4GVYYz7Kn9bmm6Q;
struct tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw {
tySequence__29bS0n2QNyO1R7e0qMMOvLA* nodes;
};
typedef NU8 tySet_tyEnum_ModuleBackendFlag__fgnyOEZ7Q9aYVj8O59afcT4g;
struct tyObject_BiTable__SMd2CpsYscvX1veKoGcqmg {
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* vals;
tySequence__9bAGqSvkAaFL9bWjsEPslrFA* keys;
};
struct tyObject_BiTable__DyMEQOe8VsqcG49bIhU69bBQ {
tySequence__IHUFRsFxZNv7YydiUO2esQ* vals;
tySequence__9bAGqSvkAaFL9bWjsEPslrFA* keys;
};
struct tyObject_PackedModule__ZSxNoR2V6oK5xosmtvhjNQ {
NimStringDesc* definedSymbols;
tySet_tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw moduleFlags;
tySequence__PXIzfWocnrafGz5p3CP5LA* includes;
tySequence__9bAGqSvkAaFL9bWjsEPslrFA* imports;
tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw toReplay;
tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw topLevel;
tyObject_PackedTree__8otSrA7MENGYESDkEP7nnw bodies;
tySequence__b89aLriiJnVTD186H6zNIgg* exports;
tySequence__b89aLriiJnVTD186H6zNIgg* hidden;
tySequence__REuPuHuSlOkZ0Q5oqzDrQg* reexports;
tySequence__b89aLriiJnVTD186H6zNIgg* compilerProcs;
tySequence__48JTohSgTy339bRxHzUD8KA* converters;
tySequence__48JTohSgTy339bRxHzUD8KA* methods;
tySequence__48JTohSgTy339bRxHzUD8KA* trmacros;
tySequence__48JTohSgTy339bRxHzUD8KA* pureEnums;
tySequence__I9aQmO9asXXWJ58UI9c8BCSzA* macroUsages;
tySequence__NyaOkf8ZwxP6rkRF5TOkew* typeInstCache;
tySequence__L9bOt8CaTEmIjgtuZvp6syg* procInstCache;
tySequence__im8UB2GsZvUaQ4a1wKGWhQ* attachedOps;
tySequence__xxnXDLpoqBo8zJzP9b1073g* methodsPerType;
tySequence__NyaOkf8ZwxP6rkRF5TOkew* enumToStringProcs;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* emittedTypeInfo;
tySet_tyEnum_ModuleBackendFlag__fgnyOEZ7Q9aYVj8O59afcT4g backendFlags;
tySequence__DfmUmNgVGnYaiV1I6227tw* syms;
tySequence__t8Uv4lEJ4lkuECvP9c6JMhA* types;
tyObject_BiTable__SMd2CpsYscvX1veKoGcqmg strings;
tyObject_BiTable__DyMEQOe8VsqcG49bIhU69bBQ numbers;
tyObject_PackedConfig__McwvRupqDAJbGrinIDFZJQ cfg;
};
struct tyObject_Table__CE4eiu6FavV1vmUiTXQ70g {
tySequence__9bT7o0CflHuiE4VhmtqBPCw* data;
NI counter;
};
struct tyObject_LoadedModule__14iJKkvOiWT62KF2D8f9c5w {
tyEnum_ModuleStatus__MgSLMPwZ4GVYYz7Kn9bmm6Q status;
NIM_BOOL symsInit;
NIM_BOOL typesInit;
NIM_BOOL loadedButAliveSetChanged;
tyObject_PackedModule__ZSxNoR2V6oK5xosmtvhjNQ fromDisk;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* syms;
tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A* types;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* module;
tyObject_Table__CE4eiu6FavV1vmUiTXQ70g iface;
tyObject_Table__CE4eiu6FavV1vmUiTXQ70g ifaceHidden;
};
typedef NU8 tySet_tyEnum_TLookupFlag__ObWMY5GMSl1GiMcrKaAhKQ;
struct tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q {
NI32 module;
NI32 symId;
NI32 typeId_0;
NIM_BOOL sealed;
};
typedef NCSTRING tyUncheckedArray__nvS6J9clHMUMHfoZd8Ad2zg[1];
typedef NU8 tySet_tyEnum_CfileFlag__Vl9c9ayddDuXiWtnWTsEYGsA;
struct tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg {
NimStringDesc* nimname;
NimStringDesc* cname;
NimStringDesc* obj;
tySet_tyEnum_CfileFlag__Vl9c9ayddDuXiWtnWTsEYGsA flags;
NimStringDesc* customArgs;
};
struct tyTuple__7q7q3E6Oj24ZNVJb9aonhAg {
NimStringDesc* Field0;
NimStringDesc* Field1;
NimStringDesc* Field2;
};
typedef NimStringDesc* tyArray__sMpvt1sOxOJ3LFGulnbeMQ[4];
typedef NU8 tySet_tyEnum_TInfoCCProp__49cn73TjZ7Rt9b8QCAU8tLNg;
struct tyTuple__yByxe8FSFNTgs4tcAkTYag {
NimStringDesc* Field0;
NimStringDesc* Field1;
NimStringDesc* Field2;
NimStringDesc* Field3;
NimStringDesc* Field4;
NimStringDesc* Field5;
NimStringDesc* Field6;
NimStringDesc* Field7;
NimStringDesc* Field8;
NimStringDesc* Field9;
NimStringDesc* Field10;
NimStringDesc* Field11;
NimStringDesc* Field12;
NimStringDesc* Field13;
NimStringDesc* Field14;
NimStringDesc* Field15;
NimStringDesc* Field16;
NimStringDesc* Field17;
NimStringDesc* Field18;
NimStringDesc* Field19;
NimStringDesc* Field20;
tySet_tyEnum_TInfoCCProp__49cn73TjZ7Rt9b8QCAU8tLNg Field21;
};
typedef tyTuple__yByxe8FSFNTgs4tcAkTYag tyArray__sa9aJ6U8e9b7Bj4Yq8itsR8w[11];
struct tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw {
NI depthLevel;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA symbols;
tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* parent;
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* allowPrivateAccess;
};
typedef NU8 tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg;
struct tyObject_TProcCon__s5jyYR8yL1QmFqiHICzU9aQ {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* resultSym;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* selfSym;
NI nestedLoopCounter;
NI nestedBlockCounter;
tyObject_TProcCon__s5jyYR8yL1QmFqiHICzU9aQ* next;
NIM_BOOL mappingExists;
tyObject_TIdTable__9aiv9bp2t5icFNINcg9c4xi1Q mapping;
tySequence__1I3cxybVrOXM64KW2dfERQ* caseContext;
tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ* localBindStmts;
};
typedef NU8 tyEnum_ImportMode__OHfXXgrGOSWpZv16VYg4yQ;
struct tyObject_ImportedModule__kyodd8HBOgfP30dipCL3JQ {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* m;
tyEnum_ImportMode__OHfXXgrGOSWpZv16VYg4yQ mode;
union{
struct {tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA imported;
} _mode_2;
struct {tyObject_PackedSet__IhxwDBRi51nGrosBGFKcsA exceptSet;
} _mode_3;
};
};
struct tyObject_TIdPair__AdFnD2YdADPeuJbG2YJ4vg {
tyObject_TIdObj__KUwfjfUQEwGHguQbTcXu7w* key;
RootObj* val;
};
struct tyObject_TInstantiationPair__HkXM4cJmOpk8zFcmq9c9c3gQ {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* genericSym;
tyObject_TInstantiation__5LqgVn6Tq9ainQRK7TQAQxA* inst;
};
struct tyTuple__KNXySARiHvEh2wA9asnyYmw {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* Field0;
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q Field1;
};
struct tyTuple__1v9bKyksXWMsm0vNwmZ4EuQ {
NI Field0;
NI Field1;
};
struct tyTuple__NAaJgGVgNmlGoqmiWxdOHQ {
NI Field0;
tyTuple__1v9bKyksXWMsm0vNwmZ4EuQ Field1;
};
struct tyTuple__KvKIqRIx9anKcDMu8DPSkHw {
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q Field0;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* Field1;
};
struct tyTuple__Y6Ewh3MCxsjd1bsriN6Gag {
NI Field0;
NI Field1;
tySequence__vGU8AyGT6KxtLJwEg0BpNw* Field2;
};
struct tyObject_Iface__uvkV248cZcsEQKaQm7C9aEA {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* module;
tySequence__vv5mGmK03BCr5e3LTZA5Hw* converters;
tySequence__vv5mGmK03BCr5e3LTZA5Hw* patterns;
tySequence__vv5mGmK03BCr5e3LTZA5Hw* pureEnums;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA interf;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA interfHidden;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* uniqueName;
};
struct tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ {
NU32 module;
NI32 item;
};
struct tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ {
NI module;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ packed_0;
};
struct tyObject_LazyType__Q19c34D32PKyTKlx6R6yODg {
tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ id;
tyObject_TType__facALICuu8zUj0hjvbTLFg* typ;
};
struct tyTuple__l7R9cf53SDCcRmz9aWTyEKqQ {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tySequence__O5RcspOP32YJ4YtU5ppxxA* Field2;
};
struct tyObject_LazyInstantiation__rlce0Sj8mBfLfm69c2yVTZg {
NI module;
tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ sym;
tySequence__ipEvhpHAmm8ZCn9bZAOdNYA* concreteTypes;
tyObject_TInstantiation__5LqgVn6Tq9ainQRK7TQAQxA* inst;
};
struct tyTuple__o67sDX0wYbEuhI9cJYAbDtg {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tySequence__Or1y9bNpmj8PM8AcK9c9cg7RA* Field2;
};
struct tyTuple__9aNnDWBFMF44sfFinBpMT4Q {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* Field2;
};
struct tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA {
tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ id;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym;
};
struct tyTuple__VrD6plbUKJjYKM0lCr3hGQ {
NI Field0;
tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA Field1;
};
struct tyTuple__dT8l9anHpNRgQSBAI9ctQ2wg {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tySequence__159bHWBGAOOs6U7OZ9cQlO0g* Field2;
};
struct tyTuple__1ZbjBgxAbnye0IFMZ6w4OA {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA Field2;
};
struct tyTuple__xYhUhS7X82rKTqbT9bRfCnw {
NI Field0;
NimStringDesc* Field1;
NI32 Field2;
};
struct tyTuple__rplX06U9bjhu9asm5pWdgqsA {
NI Field0;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g Field1;
tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA Field2;
};
struct tyTuple__1mtQ8sCEE7DbfIuQciv9b5Q {
NI Field0;
NI32 Field1;
tySequence__48JTohSgTy339bRxHzUD8KA* Field2;
};
struct tyTuple__xDU9bZmv1ZbZkJDaATBekIQ {
NI Field0;
NI32 Field1;
NI32 Field2;
};
struct tyTuple__a9bBCAQ2tegdUQVlHYxdJ2A {
tySequence__eHqUwlHGGaPw0TDPDeL79cQ* Field0;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* Field1;
};
typedef NU8 tyArray__qtqsWM5aXmcpMIVmvq3kAA[16];
struct tyTuple__3i6hlQmqrn6m7tuVN8FHjQ {
NI Field0;
tyArray__qtqsWM5aXmcpMIVmvq3kAA Field1;
tyObject_TType__facALICuu8zUj0hjvbTLFg* Field2;
};
struct tyTuple__OJFzEczluV8Jmo9bRpBfkzw {
NI Field0;
NI Field1;
tyArray__qtqsWM5aXmcpMIVmvq3kAA Field2;
};
struct tyTuple__2SGm9aGCXuo7XSQ9bqD29axXw {
NI Field0;
NimStringDesc* Field1;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* Field2;
};
struct tyTuple__F3gkSrMB1qp2Tvf9bixVXwg {
NI Field0;
NimStringDesc* Field1;
NI64 Field2;
};
struct tyObject_BTree__VZdzO0Tlflp7WMN4gS8oPg {
tyObject_NodecolonObjectType___dNELmBSmY7nthjhZupWO6g* root;
NI entries;
};
struct tyTuple__wcNatyuf8WOqAhGLhSvgiw {
NI Field0;
NimStringDesc* Field1;
tyObject_BTree__VZdzO0Tlflp7WMN4gS8oPg Field2;
};
typedef N_NIMCALL_PTR(tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w*, tyProc__jkSFMhvPZ1AdGcvT2dK9a2w) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* module, tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q* idgen);
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__A7Sdoem70tRxSEmKrf9cmyg) (tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w* p, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* topLevelStmt);
typedef N_NIMCALL_PTR(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, tyProc__EAEKmBUgKFg29agoUGtzDEQ) (tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* graph, tyObject_TPassContext__Hb6rFM0ecvtlLf2kv9aU75w* p, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
struct tyTuple__4o9cW9aUwdGqgZI9bSHHYnbaQ {
tyProc__jkSFMhvPZ1AdGcvT2dK9a2w Field0;
tyProc__A7Sdoem70tRxSEmKrf9cmyg Field1;
tyProc__EAEKmBUgKFg29agoUGtzDEQ Field2;
NIM_BOOL Field3;
};
struct tyTuple__z822nu9bFF1AlQnLrHjdwpA {
tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q Field0;
NimStringDesc* Field1;
};
struct tyObject_TFileInfo__GE3hAakXKOEpch4ap3zXAw {
NimStringDesc* fullPath;
NimStringDesc* projPath;
NimStringDesc* shortName;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* quotedName;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* quotedFullName;
tySequence__sM4lkSb7zS6F7OVMvW9cffQ* lines;
NimStringDesc* dirtyFile;
NimStringDesc* hash;
NIM_BOOL dirty;
};
struct tyTuple__QeWl6B6ffS4pU6WWrtcrDw {
NI Field0;
NimStringDesc* Field1;
};
struct tyObject_StackTraceEntry__oLyohQ7O2XOvGnflOss8EA {
NCSTRING procname;
NI line;
NCSTRING filename;
};
struct tyTuple__UvldbCB6B9ayi9bGYW7vJNLA {
NI Field0;
NI32 Field1;
NU32 Field2;
};
struct tyTuple__0q9cmhneJEKnQERTpXXdz6Q {
NU32 Field0;
NimStringDesc* Field1;
};
struct tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg {
NU16 line;
NI16 col;
NU32 file;
};
struct tyObject_PackedNode__7lDGAZiNp4zbO65GEpoKow {
tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind;
tySet_tyEnum_TNodeFlag__jyh9acXHkhZANSSvPIY7ZLg flags;
NI32 operand;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ typeId_0;
tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg info;
};
struct tyTuple__Izx9aRSX9a0diDXD84jOS9aMQ {
NU32 Field0;
NI32 Field1;
};
struct tyTuple__Q7r9caOmeWqQGZCIBHhGRUA {
NU32 Field0;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field1;
};
struct tyTuple__7Wlwbz8zSe7Udyf7mmsd9cg {
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field0;
tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg Field1;
};
struct tyTuple__XyJ8LOAZzVVXSsmt09b8uWw {
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field0;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field1;
};
struct tyObject_PackedInstantiation__39cWRURu69agjI9c1ohiUmxiA {
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ key;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ sym;
tySequence__vC9cvg0R8tfBaOXXi3sfMzw* concreteTypes;
};
struct tyTuple__9aoobCDZB4x41HJSOmh0mwA {
tyEnum_TTypeAttachedOp__Rp5P9bWYldQTLkZ7DytmxOg Field0;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field1;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field2;
};
struct tyTuple__g0Q6Qx15nK53ce9aLo7YyrA {
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field0;
NI Field1;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ Field2;
};
struct tyObject_PackedLib__oa01YzfeXO9bbIDH9cIki4Hw {
tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ kind;
NIM_BOOL generated;
NIM_BOOL isOverriden;
NU32 name;
NI32 path;
};
struct tyObject_PackedSym__XjVn21MwvH8ij6CfopYZWw {
tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw kind;
NU32 name;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ typ;
tySet_tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw flags;
tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg magic;
tyObject_PackedLineInfo__Q9bbXLBurHo2r5TyF6UBshg info;
NI32 ast;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ owner;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ guard;
NI bitsize;
NI alignment;
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options;
NI position;
NI offset;
NU32 externalName;
tySet_tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA locFlags;
tyObject_PackedLib__oa01YzfeXO9bbIDH9cIki4Hw annex;
NI32 constraint;
};
struct tyObject_PackedType__IhXsK7mrwumUBtEqbZ2BqA {
tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag kind;
tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA callConv;
tySet_tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw flags;
tySequence__vC9cvg0R8tfBaOXXi3sfMzw* types;
NI32 n;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ sym;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ owner;
NI64 size;
NI16 align;
NI16 paddingAtEnd;
NI16 lockLevel;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ typeInst;
NI32 nonUniqueId;
};
struct tyTuple__8x6vq4Dc9aLvKX9actMeR9avQ {
NI Field0;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* Field1;
tySequence__vC9cvg0R8tfBaOXXi3sfMzw* Field2;
};
struct tyTuple__FyNGItFCBJSXLJ9aJSzlX9aw {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* Field0;
NI Field1;
};
struct tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ {
TGenericSeq Sup;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* data[SEQ_DECL_SIZE];
};
struct tySequence__arD7Tw6eD6lvOczWZl9buNg {
TGenericSeq Sup;
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* data[SEQ_DECL_SIZE];
};
struct tySequence__eiMlYcU7NrAOGD2H36QOOQ {
TGenericSeq Sup;
tyObject_ImportedModule__kyodd8HBOgfP30dipCL3JQ data[SEQ_DECL_SIZE];
};
struct tySequence__eHqUwlHGGaPw0TDPDeL79cQ {
TGenericSeq Sup;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* data[SEQ_DECL_SIZE];
};
struct tySequence__oYkV9aFZe0MXcEAprJaOUsA {
TGenericSeq Sup;
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w* data[SEQ_DECL_SIZE];
};
struct tySequence__Mh9agqM29bm9aP5AUL1x7dZGA {
TGenericSeq Sup;
tyObject_TIdPair__AdFnD2YdADPeuJbG2YJ4vg data[SEQ_DECL_SIZE];
};
struct tySequence__Bre9bNyuQOg1EJKitjSzn8w {
TGenericSeq Sup;
tyObject_TrunkcolonObjectType___POcWT53G7t0BSUjc31o0iA* data[SEQ_DECL_SIZE];
};
struct tySequence__jWKvSdankQPoT5bw9cBU9aiw {
TGenericSeq Sup;
tyObject_TInstantiationPair__HkXM4cJmOpk8zFcmq9c9c3gQ data[SEQ_DECL_SIZE];
};
struct tySequence__xSqu3cxq5WeFlOO3YgE6yA {
TGenericSeq Sup;
tyTuple__KNXySARiHvEh2wA9asnyYmw data[SEQ_DECL_SIZE];
};
struct tySequence__Bis5AbpONWcIRrPyPJS8Yw {
TGenericSeq Sup;
tyTuple__NAaJgGVgNmlGoqmiWxdOHQ data[SEQ_DECL_SIZE];
};
struct tySequence__E8pi9b5QNahsURYzXMjh3qw {
TGenericSeq Sup;
tyTuple__47w2DboNEPf69aPgubZdd7Q data[SEQ_DECL_SIZE];
};
struct tySequence__vGU8AyGT6KxtLJwEg0BpNw {
TGenericSeq Sup;
tyTuple__KvKIqRIx9anKcDMu8DPSkHw data[SEQ_DECL_SIZE];
};
struct tySequence__Hkw5zrAn53wlKDHdJF1GFA {
TGenericSeq Sup;
tyTuple__Y6Ewh3MCxsjd1bsriN6Gag data[SEQ_DECL_SIZE];
};
struct tySequence__4mZLwkxT8rbt9bf3wXrXYNQ {
TGenericSeq Sup;
tyObject_Iface__uvkV248cZcsEQKaQm7C9aEA data[SEQ_DECL_SIZE];
};
struct tySequence__rQHmYk1HzcwNxKBymIFHpA {
TGenericSeq Sup;
tyObject_LoadedModule__14iJKkvOiWT62KF2D8f9c5w data[SEQ_DECL_SIZE];
};
struct tySequence__XMM60DtBsc6xYsIpNANkrA {
TGenericSeq Sup;
tyObject_PackedEncoder__B9cE9a0GbvqWW9aHf4N7RAaIw data[SEQ_DECL_SIZE];
};
struct tySequence__O5RcspOP32YJ4YtU5ppxxA {
TGenericSeq Sup;
tyObject_LazyType__Q19c34D32PKyTKlx6R6yODg data[SEQ_DECL_SIZE];
};
struct tySequence__ChDZ6dokJ9aj9cg3KBoCU5vg {
TGenericSeq Sup;
tyTuple__l7R9cf53SDCcRmz9aWTyEKqQ data[SEQ_DECL_SIZE];
};
struct tySequence__Or1y9bNpmj8PM8AcK9c9cg7RA {
TGenericSeq Sup;
tyObject_LazyInstantiation__rlce0Sj8mBfLfm69c2yVTZg data[SEQ_DECL_SIZE];
};
struct tySequence__mWRMiYLthG9coLjkbElCxkw {
TGenericSeq Sup;
tyTuple__o67sDX0wYbEuhI9cJYAbDtg data[SEQ_DECL_SIZE];
};
struct tySequence__bTDCDwD2P7TodzbAefLcSw {
TGenericSeq Sup;
tyTuple__9aNnDWBFMF44sfFinBpMT4Q data[SEQ_DECL_SIZE];
};
struct tySequence__159bHWBGAOOs6U7OZ9cQlO0g {
TGenericSeq Sup;
tyTuple__VrD6plbUKJjYKM0lCr3hGQ data[SEQ_DECL_SIZE];
};
struct tySequence__3MPVXAHA08SszBrU4ffqEg {
TGenericSeq Sup;
tyTuple__dT8l9anHpNRgQSBAI9ctQ2wg data[SEQ_DECL_SIZE];
};
struct tySequence__YCf5zJHm4JI06qpmKwPUWg {
TGenericSeq Sup;
tyTuple__1ZbjBgxAbnye0IFMZ6w4OA data[SEQ_DECL_SIZE];
};
struct tySequence__7lEisrXlQEzwtUKW5pzRCw {
TGenericSeq Sup;
tyTuple__xYhUhS7X82rKTqbT9bRfCnw data[SEQ_DECL_SIZE];
};
struct tySequence__61s9cbAniKuBrdHwBhMDfQg {
TGenericSeq Sup;
tyTuple__rplX06U9bjhu9asm5pWdgqsA data[SEQ_DECL_SIZE];
};
struct tySequence__48JTohSgTy339bRxHzUD8KA {
TGenericSeq Sup;
NI32 data[SEQ_DECL_SIZE];
};
struct tySequence__fdmz6VkIf1ewwrssKYqRFg {
TGenericSeq Sup;
tyTuple__1mtQ8sCEE7DbfIuQciv9b5Q data[SEQ_DECL_SIZE];
};
struct tySequence__kxu4GK0onha2t9bo86mdVAg {
TGenericSeq Sup;
tyTuple__xDU9bZmv1ZbZkJDaATBekIQ data[SEQ_DECL_SIZE];
};
struct tySequence__s9byh6WFJ16lPMcmqdaMTHA {
TGenericSeq Sup;
tyTuple__a9bBCAQ2tegdUQVlHYxdJ2A data[SEQ_DECL_SIZE];
};
struct tySequence__1U9bG8RcAedEeYkQLZjVFKA {
TGenericSeq Sup;
tyTuple__3i6hlQmqrn6m7tuVN8FHjQ data[SEQ_DECL_SIZE];
};
struct tySequence__fIB1rTQ55aFonoft9a9bmljQ {
TGenericSeq Sup;
tyTuple__OJFzEczluV8Jmo9bRpBfkzw data[SEQ_DECL_SIZE];
};
struct tySequence__23SMqauuRsbDANhthj9bWlA {
TGenericSeq Sup;
tyTuple__2SGm9aGCXuo7XSQ9bqD29axXw data[SEQ_DECL_SIZE];
};
struct tySequence__squ9b9bUH4OLHf6cEMrt6hVA {
TGenericSeq Sup;
tyTuple__F3gkSrMB1qp2Tvf9bixVXwg data[SEQ_DECL_SIZE];
};
struct tySequence__pHNq3oXj9av2sEUdqaqeZjw {
TGenericSeq Sup;
tyTuple__wcNatyuf8WOqAhGLhSvgiw data[SEQ_DECL_SIZE];
};
struct tySequence__MAQKEADohlpnXTModtugbQ {
TGenericSeq Sup;
tyTuple__4o9cW9aUwdGqgZI9bSHHYnbaQ data[SEQ_DECL_SIZE];
};
struct tySequence__tNFrR3kRuS1FSwuiLGoSSA {
TGenericSeq Sup;
tyTuple__z822nu9bFF1AlQnLrHjdwpA data[SEQ_DECL_SIZE];
};
struct tySequence__Zi9cGbCWofbtABoHJ5RbLNQ {
TGenericSeq Sup;
tyObject_TFileInfo__GE3hAakXKOEpch4ap3zXAw data[SEQ_DECL_SIZE];
};
struct tySequence__4eRCaZmrYLLw2k30GPTiMw {
TGenericSeq Sup;
tyTuple__QeWl6B6ffS4pU6WWrtcrDw data[SEQ_DECL_SIZE];
};
struct tySequence__sM4lkSb7zS6F7OVMvW9cffQ {
TGenericSeq Sup;
NimStringDesc* data[SEQ_DECL_SIZE];
};
struct tySequence__pK3qSsBZwdXd6qyUMkd5Jw {
TGenericSeq Sup;
tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg data[SEQ_DECL_SIZE];
};
struct tySequence__9aZVGG5Gtti9cC9bqRpXCtA3A {
TGenericSeq Sup;
tyObject_TType__facALICuu8zUj0hjvbTLFg* data[SEQ_DECL_SIZE];
};
struct tySequence__uB9b75OUPRENsBAu4AnoePA {
TGenericSeq Sup;
tyObject_StackTraceEntry__oLyohQ7O2XOvGnflOss8EA data[SEQ_DECL_SIZE];
};
struct tySequence__9cnx3zXnWzeclW8Ko4oUgAQ {
TGenericSeq Sup;
tyTuple__UvldbCB6B9ayi9bGYW7vJNLA data[SEQ_DECL_SIZE];
};
struct tySequence__PXIzfWocnrafGz5p3CP5LA {
TGenericSeq Sup;
tyTuple__0q9cmhneJEKnQERTpXXdz6Q data[SEQ_DECL_SIZE];
};
struct tySequence__9bAGqSvkAaFL9bWjsEPslrFA {
TGenericSeq Sup;
NU32 data[SEQ_DECL_SIZE];
};
struct tySequence__29bS0n2QNyO1R7e0qMMOvLA {
TGenericSeq Sup;
tyObject_PackedNode__7lDGAZiNp4zbO65GEpoKow data[SEQ_DECL_SIZE];
};
struct tySequence__b89aLriiJnVTD186H6zNIgg {
TGenericSeq Sup;
tyTuple__Izx9aRSX9a0diDXD84jOS9aMQ data[SEQ_DECL_SIZE];
};
struct tySequence__REuPuHuSlOkZ0Q5oqzDrQg {
TGenericSeq Sup;
tyTuple__Q7r9caOmeWqQGZCIBHhGRUA data[SEQ_DECL_SIZE];
};
struct tySequence__I9aQmO9asXXWJ58UI9c8BCSzA {
TGenericSeq Sup;
tyTuple__7Wlwbz8zSe7Udyf7mmsd9cg data[SEQ_DECL_SIZE];
};
struct tySequence__NyaOkf8ZwxP6rkRF5TOkew {
TGenericSeq Sup;
tyTuple__XyJ8LOAZzVVXSsmt09b8uWw data[SEQ_DECL_SIZE];
};
struct tySequence__L9bOt8CaTEmIjgtuZvp6syg {
TGenericSeq Sup;
tyObject_PackedInstantiation__39cWRURu69agjI9c1ohiUmxiA data[SEQ_DECL_SIZE];
};
struct tySequence__im8UB2GsZvUaQ4a1wKGWhQ {
TGenericSeq Sup;
tyTuple__9aoobCDZB4x41HJSOmh0mwA data[SEQ_DECL_SIZE];
};
struct tySequence__xxnXDLpoqBo8zJzP9b1073g {
TGenericSeq Sup;
tyTuple__g0Q6Qx15nK53ce9aLo7YyrA data[SEQ_DECL_SIZE];
};
struct tySequence__DfmUmNgVGnYaiV1I6227tw {
TGenericSeq Sup;
tyObject_PackedSym__XjVn21MwvH8ij6CfopYZWw data[SEQ_DECL_SIZE];
};
struct tySequence__t8Uv4lEJ4lkuECvP9c6JMhA {
TGenericSeq Sup;
tyObject_PackedType__IhXsK7mrwumUBtEqbZ2BqA data[SEQ_DECL_SIZE];
};
struct tySequence__IHUFRsFxZNv7YydiUO2esQ {
TGenericSeq Sup;
NI64 data[SEQ_DECL_SIZE];
};
struct tySequence__vC9cvg0R8tfBaOXXi3sfMzw {
TGenericSeq Sup;
tyObject_PackedItemId__FzcXUzSZ9cNfGYsfibgjWlQ data[SEQ_DECL_SIZE];
};
struct tySequence__9bT7o0CflHuiE4VhmtqBPCw {
TGenericSeq Sup;
tyTuple__8x6vq4Dc9aLvKX9actMeR9avQ data[SEQ_DECL_SIZE];
};
struct tySequence__1I3cxybVrOXM64KW2dfERQ {
TGenericSeq Sup;
tyTuple__FyNGItFCBJSXLJ9aJSzlX9aw data[SEQ_DECL_SIZE];
};
struct tySequence__vv5mGmK03BCr5e3LTZA5Hw {
TGenericSeq Sup;
tyObject_LazySym__rhF4Xi6CELPmWy539c1l6fA data[SEQ_DECL_SIZE];
};
struct tySequence__ipEvhpHAmm8ZCn9bZAOdNYA {
TGenericSeq Sup;
tyObject_FullId__pfGm9bmVgXcP2kl6OfHhZgQ data[SEQ_DECL_SIZE];
};
static N_INLINE(void, asgnRef)(void** dest, void* src);
static N_INLINE(void, incRef__system_5338)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(NI, pluspercent___system_696)(NI x, NI y);
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__system_5300)(void* usr);
static N_INLINE(NI, minuspercent___system_716)(NI x, NI y);
static N_INLINE(void, decRef__system_5345)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(NIM_BOOL, ltpercent___system_1005)(NI x, NI y);
static N_INLINE(void, rtlAddZCT__system_5343)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
N_LIB_PRIVATE N_NOINLINE(void, addZCT__system_5294)(tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w* s, tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
N_LIB_PRIVATE N_NIMCALL(TGenericSeq*, setLengthSeqV2)(TGenericSeq* s, TNimType* typ, NI newLen);
N_LIB_PRIVATE N_NIMCALL(void, unsureAsgnRef)(void** dest, void* src);
static N_INLINE(NI, safeLen__ast_3191)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
static N_INLINE(NI, len__ast_3198)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, pragmaRec__pragmas_2524)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL isStatement);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, singlePragma__pragmas_1610)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI* i, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL comesFromPush, NIM_BOOL isStatement);
N_LIB_PRIVATE N_NIMCALL(void, processNote__pragmas_663)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw, whichKeyword__idents_214)(tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* id);
N_LIB_PRIVATE N_NIMCALL(tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w, findStr__commands_321)(NimStringDesc* s, tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w default_0);
N_LIB_PRIVATE N_NIMCALL(void, invalidPragma__pragmas_148)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NOINLINE(void, liMessage__msgs_1118)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w msg, NimStringDesc* arg, tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw eh, tyTuple__kN8up2W6YKc5YA9avn5mV5w info2, NIM_BOOL isRaw);
static N_INLINE(void, appendString)(NimStringDesc* dest, NimStringDesc* src);
static N_INLINE(void, copyMem__system_1727)(void* dest, void* source, NI size);
static N_INLINE(void, nimCopyMem)(void* dest, void* source, NI size);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, renderTree__renderer_46)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TRenderFlag__wrPgUo1ExBlHvFnXN2nSHw renderFlags);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, rawNewString)(NI space);
N_LIB_PRIVATE N_NIMCALL(tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w, findStr__commands_352)(NimStringDesc* s, tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w default_0);
N_LIB_PRIVATE N_NIMCALL(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw, whichPragma__trees_244)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, pragmaRaisesOrTags__pragmas_1331)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, processExc__pragmas_1334)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* x);
N_LIB_PRIVATE N_NIMCALL(tyObject_TType__facALICuu8zUj0hjvbTLFg*, makeTypeFromExpr__semdata_804)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TType__facALICuu8zUj0hjvbTLFg*, skipTypes__ast_3735)(tyObject_TType__facALICuu8zUj0hjvbTLFg* t, tySet_tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag kinds);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isMetaType__ast_3495)(tyObject_TType__facALICuu8zUj0hjvbTLFg* t);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, semCustomPragma__pragmas_1525)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newTree__ast_3392)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** children, NI childrenLen_0);
static N_INLINE(void, nimZeroMem)(void* p, NI size);
static N_INLINE(void, nimSetMem__systemZmemory_7)(void* a, int v, NI size);
N_LIB_PRIVATE N_NIMCALL(void, transitionSonsKind__ast_4359)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyEnum_TNodeKind__Dq0DNfMwTBUf7hLFKKDU7g kind);
N_LIB_PRIVATE N_NIMCALL(tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA*, considerQuotedIdent__lookups_28)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* origin);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, strTableGet__astalgo_3390)(tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA t, tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* name);
N_LIB_PRIVATE N_NIMCALL(void, styleCheckUse__linter_192)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, pragma__pragmas_123)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL isStatement);
N_LIB_PRIVATE N_NIMCALL(void, X5BX5Deq___pragmas_1672)(tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ** s, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** b, NI bLen_0);
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___pureZunicode_840)(NI a, NI b);
N_LIB_PRIVATE N_NIMCALL(void, checkPragmaUse__linter_240)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw w, NimStringDesc* pragmaName);
N_LIB_PRIVATE N_NIMCALL(void, makeExternExport__pragmas_272)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, setExternName__pragmas_238)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
static N_INLINE(NIM_BOOL, eqStrings)(NimStringDesc* a, NimStringDesc* b);
static N_INLINE(NIM_BOOL, equalMem__system_1735)(void* a, void* b, NI size);
static N_INLINE(int, nimCmpMem)(void* a, void* b, NI size);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, rope__ropes_109)(NimStringDesc* s);
static N_INLINE(NIM_BOOL, contains__pureZos_651)(NIM_CHAR* a, NI aLen_0, NIM_CHAR item);
static N_INLINE(NI, find__pureZos_656)(NIM_CHAR* a, NI aLen_0, NIM_CHAR item);
static N_INLINE(void, pushSafePoint)(TSafePoint* s);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nsuFormatSingleElem)(NimStringDesc* formatstr, NimStringDesc* a);
static N_INLINE(void, popSafePoint)(void);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isObj)(TNimType* obj, TNimType* subclass);
static N_INLINE(Exception*, nimBorrowCurrentException)(void);
static N_INLINE(void, popCurrentException)(void);
N_LIB_PRIVATE N_NIMCALL(void, reraiseException)(void);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, getOptionalStr__pragmas_392)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc* defaultStr);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, expectStrLit__pragmas_371)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, getStrLitNode__pragmas_354)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NOINLINE(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newEmptyStrNode__pragmas_350)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newNodeIT__ast_3378)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyObject_TType__facALICuu8zUj0hjvbTLFg* typ);
N_LIB_PRIVATE N_NIMCALL(tyObject_TType__facALICuu8zUj0hjvbTLFg*, getSysType__magicsys_60)(tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* g, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag kind);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, reprEnum)(NI e, TNimType* typ);
N_LIB_PRIVATE N_NIMCALL(void, cppDefine__options_2499)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* c, NimStringDesc* define);
N_LIB_PRIVATE N_NIMCALL(void, recordPragma__pragmas_129)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc** args, NI argsLen_0);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newNodeI__ast_3356)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, add__ast_4797)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* father, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* son);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newStrNode__ast_3817)(NimStringDesc* strVal, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, addPragmaComputation__semdata_618)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, makeExternImport__pragmas_259)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, processImportCompilerProc__pragmas_281)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, processImportCpp__pragmas_298)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, getModule__astalgo_216)(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, contains__pureZstrutils_1635)(NimStringDesc* s, tySet_tyChar__nmiMWKVIe46vacnhAFrQvw chars);
N_LIB_PRIVATE N_NIMCALL(void, processImportObjC__pragmas_328)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(NI, expectIntLit__pragmas_375)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(NI16, floatInt64Align__options_4700)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isPowerOfTwo__pureZmath_173)(NI x);
N_LIB_PRIVATE N_NIMCALL(void, noVal__pragmas_1213)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, processEffectsOf__pragmas_1570)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner);
N_LIB_PRIVATE N_NIMCALL(void, nimGCvisit)(void* d, NI op);
static N_NIMCALL(void, Marker_tyRef__b333ORV1UJUlL6q84XcNlQ)(void* p, NI op);
N_LIB_PRIVATE N_NOINLINE(void*, newObj)(TNimType* typ, NI size);
N_LIB_PRIVATE N_CLOSURE(void, processParam__pragmas_1574)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, void* ClE_0);
N_LIB_PRIVATE N_NIMCALL(void, pragmaNoForward__pragmas_502)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw flag);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isTurnedOn__pragmas_467)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, processMagic__pragmas_405)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, substr__system_7785)(NimStringDesc* s, NI first);
N_LIB_PRIVATE N_NIMCALL(tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA*, getLib__pragmas_544)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ kind, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* path);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, exprStructuralEquivalent__trees_56)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* a, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* b, NIM_BOOL strictSymEquality);
N_LIB_PRIVATE N_NIMCALL(tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA*, newLib__semdata_724)(tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ kind);
N_LIB_PRIVATE N_NIMCALL(TGenericSeq*, incrSeqV3)(TGenericSeq* s, TNimType* typ);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isDynlibOverride__options_4677)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* lib);
N_LIB_PRIVATE N_NIMCALL(void, addToLib__semdata_730)(tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* lib, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(void, processDynLib__pragmas_621)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, expectDynlibNode__pragmas_591)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
static N_INLINE(tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**, X5BX5D___semdata_344)(tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** s, NI sLen_0, NI i);
N_LIB_PRIVATE N_NIMCALL(void, markCompilerProc__pragmas_1425)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, registerCompilerProc__magicsys_154)(tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* g, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, addCompilerProc__icZic_2411)(tyObject_PackedEncoder__B9cE9a0GbvqWW9aHf4N7RAaIw* c, tyObject_PackedModule__ZSxNoR2V6oK5xosmtvhjNQ* m, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, deprecatedStmt__pragmas_1444)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* outerPragma);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, qualifiedLookUp__lookups_1233)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TLookupFlag__ObWMY5GMSl1GiMcrKaAhKQ flags);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, newSym__ast_3445)(tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw symKind, tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* name, tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g id, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg options);
static N_INLINE(tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g, nextSymId__ast_3132)(tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q* x);
static N_INLINE(void, addInterfaceDecl__lookups_879)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(void, addInterfaceDeclAt__lookups_875)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* scope, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newSymNode__ast_3716)(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(void, typeBorrow__pragmas_1404)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
static N_INLINE(NIM_BOOL, isRoutine__ast_4676)(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, processDefine__pragmas_1032)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, defineSymbol__condsyms_4)(tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* symbols, NimStringDesc* symbol, NimStringDesc* value);
N_LIB_PRIVATE N_NIMCALL(void, processUndef__pragmas_1048)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, undefSymbol__condsyms_8)(tyObject_StringTableObj__V5PVrt9bIxZEeV7lfvqqtNg* symbols, NimStringDesc* symbol);
N_LIB_PRIVATE N_NIMCALL(void, processCompile__pragmas_1073)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, getStrLit__pragmas_1083)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI i);
static N_INLINE(NimStringDesc*, slash___pureZos_121)(NimStringDesc* head, NimStringDesc* tail);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nosjoinPath)(NimStringDesc* head, NimStringDesc* tail);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nosparentDir)(NimStringDesc* path);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, toFullPath__msgs_538)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NI32 fileIdx);
static N_INLINE(NCSTRING, nimToCStringConv)(NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, cstrToNimstr)(NCSTRING str);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, nosfileExists)(NimStringDesc* filename);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, completeCfilePath__extccomp_713)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* cfile, NIM_BOOL createSubDir);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nosextractFilename)(NimStringDesc* path);
N_LIB_PRIVATE N_NIMCALL(void, docompile__pragmas_1076)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it, NimStringDesc* src, NimStringDesc* dest, NimStringDesc* customArgs);
N_LIB_PRIVATE N_NIMCALL(void, splitFile__pathutils_26)(NimStringDesc* x, tyTuple__7q7q3E6Oj24ZNVJb9aonhAg* Result);
N_LIB_PRIVATE N_NIMCALL(void, addExternalFileToCompile__extccomp_1066)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg* c);
N_LIB_PRIVATE N_NIMCALL(void, nimLeaveFinally)(void);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, nosisAbsolute)(NimStringDesc* path);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, findFile__options_4490)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* f, NIM_BOOL suppressStdlib);
static N_INLINE(NIM_BOOL, isEmpty__options_4495)(NimStringDesc* x);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, toObjFile__extccomp_718)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* filename);
N_LIB_PRIVATE N_NIMCALL(void, processLink__pragmas_1129)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, relativeFile__pragmas_1064)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc* ext);
N_LIB_PRIVATE N_NIMCALL(void, nossplitFile)(NimStringDesc* path, tyTuple__7q7q3E6Oj24ZNVJb9aonhAg* Result);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nosaddFileExt)(NimStringDesc* filename, NimStringDesc* ext);
N_LIB_PRIVATE N_NIMCALL(void, addExternalFileToLink__extccomp_754)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* filename);
N_LIB_PRIVATE N_NIMCALL(void, addLinkOption__extccomp_690)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* option);
N_LIB_PRIVATE N_NIMCALL(void, addCompileOption__extccomp_693)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* option);
N_LIB_PRIVATE N_NIMCALL(void, addLocalCompileOption__extccomp_738)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* option, NimStringDesc* nimfile);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, toFullPathConsiderDirty__msgs_571)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NI32 fileIdx);
N_LIB_PRIVATE N_NIMCALL(void, processPush__pragmas_991)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI start);
N_LIB_PRIVATE N_NIMCALL(tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w*, pushOptionEntry__semdata_462)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, tryProcessOption__pragmas_924)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions);
N_LIB_PRIVATE N_NIMCALL(void, processExperimental__pragmas_881)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ, parseEnum__commands_1294)(NimStringDesc* s);
static N_INLINE(NIM_BOOL, isTopLevel__semdata_1091)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
static N_INLINE(tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg, pragmaToOptions__pragmas_878)(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw w);
N_LIB_PRIVATE N_NIMCALL(void, onOff__pragmas_487)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg op, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions);
N_LIB_PRIVATE N_NIMCALL(void, processCallConv__pragmas_523)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA, wordToCallConv__pragmas_454)(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw sw);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nsuNormalize)(NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(void, processPop__pragmas_1026)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, popOptionEntry__semdata_477)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
N_LIB_PRIVATE N_NIMCALL(void, processPragma__pragmas_1277)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI i);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newTreeI__ast_3420)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** children, NI childrenLen_0);
N_LIB_PRIVATE N_NIMCALL(tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ*, X5BX5D___pragmas_1308)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** s, NI sLen_0, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x);
N_LIB_PRIVATE N_NIMCALL(void*, newSeq)(TNimType* typ, NI len);
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___stdZenumutils_80)(NI a, NI b);
N_LIB_PRIVATE N_NIMCALL(void, strTableAdd__astalgo_3332)(tyObject_TStrTable__f07aOS3dr28kGa5wcE29aFA* t, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* n);
N_LIB_PRIVATE N_NIMCALL(void, processCodegenDecl__pragmas_401)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(void, processOption__pragmas_987)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions);
N_LIB_PRIVATE N_NIMCALL(void, pragmaEmit__pragmas_1175)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newNodeI__ast_3360)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, NI children);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, semAsmOrEmit__pragmas_1133)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* con, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NIM_CHAR marker);
N_LIB_PRIVATE N_NIMCALL(NI, nsuFindChar)(NimStringDesc* s, NIM_CHAR sub, NI start, NI last);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, substr__system_7773)(NimStringDesc* s, NI first, NI last);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newStrNode__ast_3813)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, NimStringDesc* strVal);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, searchInScopes__lookups_423)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* s, NIM_BOOL* ambiguous);
N_LIB_PRIVATE N_NIMCALL(tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA*, getIdent__idents_143)(tyObject_IdentCachecolonObjectType___TzLHS09bRH9a0TYLs39cqcNaw* ic, NimStringDesc* identifier);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, nimCharToStr)(NIM_CHAR x);
N_LIB_PRIVATE N_NIMCALL(void, illFormedAstLocal__semdata_1074)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf);
N_LIB_PRIVATE N_NIMCALL(void, pragmaUnroll__pragmas_1223)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newIntNode__ast_3723)(tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw kind, NI64 intVal);
N_LIB_PRIVATE N_NIMCALL(void, pragmaLine__pragmas_1235)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(NI32, fileInfoIdx__msgs_376)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NimStringDesc* filename);
N_LIB_PRIVATE N_NIMCALL(tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q, getInfoContext__msgs_516)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, NI index);
N_LIB_PRIVATE N_NIMCALL(void, pragmaLockStmt__pragmas_1360)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it);
N_LIB_PRIVATE N_NIMCALL(NI16, pragmaLocks__pragmas_1388)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, pragmaGuard__pragmas_1492)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it, tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw kind);
N_LIB_PRIVATE N_NIMCALL(void, registerNimScriptSymbol__magicsys_157)(tyObject_ModuleGraphcolonObjectType___RZI3hCs0FTPYx8StfC81qQ* g, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, pragmaProposition__pragmas_155)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(void, pragmaEnsures__pragmas_169)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n);
N_LIB_PRIVATE N_NIMCALL(tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw*, openScope__lookups_69)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, getCurrOwner__semdata_315)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
static N_INLINE(void, addDecl__lookups_845)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
static N_INLINE(void, addDeclAt__lookups_837)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* scope, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym);
N_LIB_PRIVATE N_NIMCALL(void, addDeclAt__lookups_815)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* scope, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
N_LIB_PRIVATE N_NIMCALL(void, closeScope__lookups_101)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c);
N_LIB_PRIVATE N_NIMCALL(void, illegalCustomPragma__pragmas_151)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s);
N_LIB_PRIVATE N_NIMCALL(void, implicitPragmas__pragmas_2394)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas);
N_LIB_PRIVATE N_NIMCALL(void, pushInfoContext__msgs_490)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, NimStringDesc* detail);
N_LIB_PRIVATE N_NIMCALL(void, internalErrorImpl__msgs_1431)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, NimStringDesc* errMsg, tyTuple__kN8up2W6YKc5YA9avn5mV5w info2);
N_LIB_PRIVATE N_NIMCALL(void, popInfoContext__msgs_507)(tyObject_ConfigRefcolonObjectType___LaK09ayL9alwKUad7rts0rTw* conf);
N_LIB_PRIVATE N_NIMCALL(void, mergePragmas__pragmas_2378)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* pragmas);
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, copyTree__ast_4431)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* src);
N_LIB_PRIVATE N_NIMCALL(void, overwriteLineInfo__pragmas_2369)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info);
extern TNimType NTItnodeseq__ehmV9bTklH2Gt9cXHV9c0HLeQ_;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_2, "invalid pragma: ", 16);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_4, "/home/runner/work/nightlies/nightlies/nim/compiler/pragmas.nim", 62);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_3 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 110),
((NI) 12)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_5, "a \'cast\' pragma cannot be pushed", 32);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_6 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 812),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_7, "\'cast\' pragma only allowed in a statement context", 49);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_8 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 814),
((NI) 16)}
;
static NIM_CONST tySet_tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag TM__tPA3StZ6VsKyoznyrIfFxg_10 = {
0x10, 0x09, 0xe0, 0x00, 0x00, 0xe0, 0x80, 0x00,
0x00}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_11, "invalid type for raises/tags list", 33);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_12 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 654),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_13, "recursive dependency: ", 22);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_14 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 831),
((NI) 17)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_15, "$1", 2);
extern TNimType NTIvalueerror__yoNlBGx0D2tRizIdhQuENw_;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_17, "invalid extern name: \'", 22);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_18, "\'. (Forgot to escape \'$\'\?)", 26);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_19 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 158),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_20, "string literal expected", 23);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_21 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 204),
((NI) 14)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_22 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 212),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_23, "exportcpp requires `cpp` backend, got: ", 39);
extern TNimType NTItbackend__4OBsgZ9cscH2JLUE5Wcz01g_;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_24 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 847),
((NI) 22)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_25, "cppdefine", 9);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_26, "`importjs` pragma requires the JavaScript target", 48);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_27 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 871),
((NI) 20)}
;
static NIM_CONST tySet_tyChar__nmiMWKVIe46vacnhAFrQvw TM__tPA3StZ6VsKyoznyrIfFxg_28 = {
0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_29, "`importjs` for routines requires a pattern", 42);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_30 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 876),
((NI) 20)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_31, "integer literal expected", 24);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_32 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 221),
((NI) 14)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_33 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 226),
((NI) 20)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_34, "size may only be 1, 2, 4 or 8", 29);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_35 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 891),
((NI) 20)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_36, "power of two expected", 21);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_37 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 897),
((NI) 20)}
;
extern TNimType NTIrootobj__ytyiCJqK439aF9cIibuRVpAg_;
N_LIB_PRIVATE TNimType NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_;
extern TNimType NTIint__xHTZrq9aYs6boc9bCba0JbpQ_;
extern TNimType NTIpsym__dG2QVH5Z69aMUY38zTqWxaA_;
N_LIB_PRIVATE TNimType NTIrefobject__b333ORV1UJUlL6q84XcNlQ_;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_39, "parameter name expected", 23);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_40 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 794),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_41, "parameter cannot be declared as .effectsOf", 42);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_42 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 789),
((NI) 18)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_43 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 791),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_46, "\'on\' or \'off\' expected", 22);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_47 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 260),
((NI) 12)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_48, "use {.experimental: \"codeReordering\".} instead; ", 48);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_49, "{.noForward.}", 13);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_50, "{.reorder.}", 11);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_51, " is deprecated", 14);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_52 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 275),
((NI) 9)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_53 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 239),
((NI) 14)}
;
extern TNimType NTItmagic__shZhZOdbVC5nnFvcXQAImg_;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_54 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 248),
((NI) 30)}
;
extern TNimType NTIseqLplibT__arD7Tw6eD6lvOczWZl9buNg_;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_55, ".noreturn with return type not allowed", 38);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_56 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 967),
((NI) 20)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_57 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 302),
((NI) 14)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_58 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 312),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_59, "FlowVar", 7);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_60, "annotation to deprecated not supported here", 43);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_61 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 996),
((NI) 22)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_62, "list of key:value pairs expected", 32);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_63 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 719),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_64, "the .deprecated pragma is unreliable for routines", 49);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_65 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 724),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_66, "key:value pair expected", 23);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_67 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 732),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_68, "a type can only borrow `.` for now", 34);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_69 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 698),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_70, "hint", 4);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_71 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1054),
((NI) 15)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_72, "warning", 7);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_73 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1058),
((NI) 15)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_74, "error", 5);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_75 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1071),
((NI) 20)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_76 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1072),
((NI) 22)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_77, "true", 4);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_78 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 510),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_80, "compile", 7);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_81, "\'.compile\' pragma takes up 2 arguments", 38);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_82 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 529),
((NI) 18)}
;
extern NIM_CONST tyArray__sa9aJ6U8e9b7Bj4Yq8itsR8w CC__extccomp_508;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_83, "link", 4);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_84, "passl", 5);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_85, "passc", 5);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_86, "localpassl", 10);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_87, "\'push\' cannot have arguments", 28);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_88 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 449),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_90, "Code reordering experimental pragma only valid at toplevel", 58);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_91 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 400),
((NI) 24)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_92, "unknown experimental feature", 28);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_93 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 404),
((NI) 18)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_94 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 406),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_95, "calling convention expected", 27);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_96 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 285),
((NI) 20)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_97 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 287),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_98, "speed", 5);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_99, "size", 4);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_100, "none", 4);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_101, "\'none\', \'speed\' or \'size\' expected", 34);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_102 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 439),
((NI) 26)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_103, "{.pop.} without a corresponding {.push.}", 40);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_104 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 467),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_105, "option expected", 15);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_106 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 445),
((NI) 14)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_107 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 585),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_108, "empty \'asm\' statement", 21);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_109 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 553),
((NI) 16)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_110 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 599),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_111, "`{.union.}` is not implemented for js backend.", 46);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_112 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1148),
((NI) 20)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_113 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 625),
((NI) 18)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_114 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 627),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_115, "tuple expected", 14);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_116 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 632),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_117, "locks pragma takes a list of expressions", 40);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_118 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 672),
((NI) 16)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_119, "unknown", 7);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_120, "invalid string literal for locks pragma (only allowed string is \"unknown\")", 74);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_121 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 686),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_122, "integer must be within 0..1000", 30);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_123 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 690),
((NI) 18)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_124, "bitsize needs to be positive", 28);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_125 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1193),
((NI) 22)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_126, "\'experimental\' pragma only valid as toplevel statement or in a \'push\' environment", 81);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_127 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1209),
((NI) 20)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_128, "\'.this\' pragma is deprecated", 28);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_129 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1214),
((NI) 17)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_130, "self", 4);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_131 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1217),
((NI) 17)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_132, "\'this\' pragma is allowed to have zero or one arguments", 54);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_133 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1219),
((NI) 20)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_134, "proposition expected", 20);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_135 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 116),
((NI) 14)}
;
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_136 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 122),
((NI) 14)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_137, "result", 6);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_138, "cannot attach a custom pragma to \'", 34);
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_139, "\'", 1);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_140 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 112),
((NI) 12)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_141, "implicitPragmas", 15);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_142 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1277),
((NI) 25)}
;
STRING_LITERAL(TM__tPA3StZ6VsKyoznyrIfFxg_143, ".dynlib requires .exportc", 25);
static NIM_CONST tyTuple__kN8up2W6YKc5YA9avn5mV5w TM__tPA3StZ6VsKyoznyrIfFxg_144 = {((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_4),
((NI) 1283),
((NI) 16)}
;
extern tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ gch__system_5247;
extern TSafePoint* excHandler__system_2565;
extern TSafePoint* excHandler__system_2565;
extern TSafePoint* excHandler__system_2565;
extern TSafePoint* excHandler__system_2565;
extern Exception* currException__system_2566;
extern Exception* currException__system_2566;
extern Exception* currException__system_2566;
static N_INLINE(NI, pluspercent___system_696)(NI x, NI y) {
NI result;
result = (NI)0;
result = ((NI) ((NU)((NU64)(((NU) (x))) + (NU64)(((NU) (y))))));
return result;
}
static N_INLINE(void, incRef__system_5338)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) {
(*c).refcount = pluspercent___system_696((*c).refcount, ((NI) 8));
}
static N_INLINE(NI, minuspercent___system_716)(NI x, NI y) {
NI result;
result = (NI)0;
result = ((NI) ((NU)((NU64)(((NU) (x))) - (NU64)(((NU) (y))))));
return result;
}
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__system_5300)(void* usr) {
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* result;
NI T1_;
result = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T1_ = (NI)0;
T1_ = minuspercent___system_716(((NI) (ptrdiff_t) (usr)), ((NI) 16));
result = ((tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*) (T1_));
return result;
}
static N_INLINE(NIM_BOOL, ltpercent___system_1005)(NI x, NI y) {
NIM_BOOL result;
result = (NIM_BOOL)0;
result = ((NU64)(((NU) (x))) < (NU64)(((NU) (y))));
return result;
}
static N_INLINE(void, rtlAddZCT__system_5343)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) {
addZCT__system_5294((&gch__system_5247.zct), c);
}
static N_INLINE(void, decRef__system_5345)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) {
(*c).refcount = minuspercent___system_716((*c).refcount, ((NI) 8));
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = ltpercent___system_1005((*c).refcount, ((NI) 8));
if (!T3_) goto LA4_;
rtlAddZCT__system_5343(c);
}
LA4_: ;
}
static N_INLINE(void, asgnRef)(void** dest, void* src) {
{
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T5_;
if (!!((src == NIM_NIL))) goto LA3_;
T5_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T5_ = usrToCell__system_5300(src);
incRef__system_5338(T5_);
}
LA3_: ;
{
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T10_;
if (!!(((*dest) == NIM_NIL))) goto LA8_;
T10_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T10_ = usrToCell__system_5300((*dest));
decRef__system_5345(T10_);
}
LA8_: ;
(*dest) = src;
}
N_LIB_PRIVATE N_NIMCALL(void, X5BX5Deq___pragmas_1672)(tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ** s, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** b, NI bLen_0) {
NI a;
NI L;
a = x.a;
L = (NI)((NI)(x.b - a) + ((NI) 1));
{
if (!(L == bLen_0)) goto LA3_;
{
NI i;
NI i_2;
i = (NI)0;
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < L)) goto LA7;
i = i_2;
asgnRef((void**) (&(*s)->data[(NI)(i + a)]), b[i]);
i_2 += ((NI) 1);
} LA7: ;
}
}
}
goto LA1_;
LA3_: ;
{
NI shiftX60gensym643_;
NI newLenX60gensym643_;
NI T9_;
shiftX60gensym643_ = (NI)(bLen_0 - ((((NI) 0) >= L) ? ((NI) 0) : L));
T9_ = ((*s) ? (*s)->Sup.len : 0);
newLenX60gensym643_ = (NI)(T9_ + shiftX60gensym643_);
{
if (!(((NI) 0) < shiftX60gensym643_)) goto LA12_;
unsureAsgnRef((void**) (&(*s)), (tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ*) setLengthSeqV2(&((*s))->Sup, (&NTItnodeseq__ehmV9bTklH2Gt9cXHV9c0HLeQ_), ((NI) (newLenX60gensym643_))));
{
NI iX60gensym643_;
NI colontmp_;
NI colontmp__2;
NI res;
iX60gensym643_ = (NI)0;
colontmp_ = (NI)0;
colontmp__2 = (NI)0;
colontmp_ = (NI)(newLenX60gensym643_ - ((NI) 1));
colontmp__2 = (NI)(a + bLen_0);
res = colontmp_;
{
while (1) {
if (!(colontmp__2 <= res)) goto LA16;
iX60gensym643_ = res;
asgnRef((void**) (&(*s)->data[iX60gensym643_]), (*s)->data[(NI)(iX60gensym643_ - shiftX60gensym643_)]);
res -= ((NI) 1);
} LA16: ;
}
}
}
goto LA10_;
LA12_: ;
{
{
NI iX60gensym643__2;
NI colontmp__3;
NI colontmp__4;
NI res_2;
iX60gensym643__2 = (NI)0;
colontmp__3 = (NI)0;
colontmp__4 = (NI)0;
colontmp__3 = (NI)(a + bLen_0);
colontmp__4 = (NI)(newLenX60gensym643_ - ((NI) 1));
res_2 = colontmp__3;
{
while (1) {
if (!(res_2 <= colontmp__4)) goto LA20;
iX60gensym643__2 = res_2;
asgnRef((void**) (&(*s)->data[iX60gensym643__2]), (*s)->data[(NI)(iX60gensym643__2 - shiftX60gensym643_)]);
res_2 += ((NI) 1);
} LA20: ;
}
}
unsureAsgnRef((void**) (&(*s)), (tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ*) setLengthSeqV2(&((*s))->Sup, (&NTItnodeseq__ehmV9bTklH2Gt9cXHV9c0HLeQ_), ((NI) (newLenX60gensym643_))));
}
LA10_: ;
{
NI iX60gensym643__3;
NI colontmp__5;
NI i_3;
iX60gensym643__3 = (NI)0;
colontmp__5 = (NI)0;
colontmp__5 = bLen_0;
i_3 = ((NI) 0);
{
while (1) {
if (!(i_3 < colontmp__5)) goto LA23;
iX60gensym643__3 = i_3;
asgnRef((void**) (&(*s)->data[(NI)(a + iX60gensym643__3)]), b[iX60gensym643__3]);
i_3 += ((NI) 1);
} LA23: ;
}
}
}
LA1_: ;
}
static N_INLINE(NI, len__ast_3198)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NI result;
NI T1_;
result = (NI)0;
T1_ = ((*n)._kind_6.sons ? (*n)._kind_6.sons->Sup.len : 0);
result = T1_;
return result;
}
static N_INLINE(NI, safeLen__ast_3191)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NI result;
result = (NI)0;
{
if (!((*n).kind >= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 0) && (*n).kind <= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 23))) goto LA3_;
result = ((NI) 0);
}
goto LA1_;
LA3_: ;
{
result = len__ast_3198(n);
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, getPragmaVal__pragmas_95)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* procAst, tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw name) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* p;
{ result = NIM_NIL;
p = (*procAst)._kind_6.sons->data[((NI) 4)];
{
if (!((*p).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 1))) goto LA3_;
result = ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL);
goto BeforeRet_;
}
LA3_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
it = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(p);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA8;
i = i_2;
it = (*p)._kind_6.sons->data[i];
{
NIM_BOOL T11_;
NIM_BOOL T12_;
NIM_BOOL T13_;
NI T15_;
T11_ = (NIM_BOOL)0;
T12_ = (NIM_BOOL)0;
T13_ = (NIM_BOOL)0;
T13_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T13_)) goto LA14_;
T15_ = (NI)0;
T15_ = len__ast_3198(it);
T13_ = (T15_ == ((NI) 2));
LA14_: ;
T12_ = T13_;
if (!(T12_)) goto LA16_;
T12_ = ((*(*it)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA16_: ;
T11_ = T12_;
if (!(T11_)) goto LA17_;
T11_ = ((*(*(*it)._kind_6.sons->data[((NI) 0)])._kind_5.ident).id == name);
LA17_: ;
if (!T11_) goto LA18_;
result = (*it)._kind_6.sons->data[((NI) 1)];
goto BeforeRet_;
}
LA18_: ;
i_2 += ((NI) 1);
} LA8: ;
}
}
}
}BeforeRet_: ;
return result;
}
static N_INLINE(void, nimCopyMem)(void* dest, void* source, NI size) {
void* T1_;
T1_ = (void*)0;
T1_ = memcpy(dest, source, ((size_t) (size)));
}
static N_INLINE(void, copyMem__system_1727)(void* dest, void* source, NI size) {
nimCopyMem(dest, source, size);
}
static N_INLINE(void, appendString)(NimStringDesc* dest, NimStringDesc* src) {
{
if (!!((src == ((NimStringDesc*) NIM_NIL)))) goto LA3_;
copyMem__system_1727(((void*) ((&(*dest).data[(*dest).Sup.len]))), ((void*) ((*src).data)), ((NI) ((NI)((*src).Sup.len + ((NI) 1)))));
(*dest).Sup.len += (*src).Sup.len;
}
LA3_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, invalidPragma__pragmas_148)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NimStringDesc* T1_;
NimStringDesc* T2_;
T1_ = NIM_NIL;
T2_ = NIM_NIL;
T2_ = renderTree__renderer_46(n, 4);
T1_ = rawNewString((T2_ ? T2_->Sup.len : 0) + 16);
appendString(T1_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_2));
appendString(T1_, T2_);
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), T1_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_3, NIM_FALSE);
}
N_LIB_PRIVATE N_NIMCALL(void, processNote__pragmas_663)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NIM_BOOL T4_;
NIM_BOOL T5_;
NIM_BOOL T6_;
NIM_BOOL T7_;
NI T9_;
NI T12_;
tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug nk;
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw T17_;
T3_ = (NIM_BOOL)0;
T4_ = (NIM_BOOL)0;
T5_ = (NIM_BOOL)0;
T6_ = (NIM_BOOL)0;
T7_ = (NIM_BOOL)0;
T7_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T7_)) goto LA8_;
T9_ = (NI)0;
T9_ = len__ast_3198(n);
T7_ = (T9_ == ((NI) 2));
LA8_: ;
T6_ = T7_;
if (!(T6_)) goto LA10_;
T6_ = ((*(*n)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 42));
LA10_: ;
T5_ = T6_;
if (!(T5_)) goto LA11_;
T12_ = (NI)0;
T12_ = len__ast_3198((*n)._kind_6.sons->data[((NI) 0)]);
T5_ = (T12_ == ((NI) 2));
LA11_: ;
T4_ = T5_;
if (!(T4_)) goto LA13_;
T4_ = ((*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA13_: ;
T3_ = T4_;
if (!(T3_)) goto LA14_;
T3_ = ((*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA14_: ;
if (!T3_) goto LA15_;
nk = (tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug)0;
T17_ = (tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw)0;
T17_ = whichKeyword__idents_214((*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 0)])._kind_5.ident);
switch (T17_) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 124):
{
tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w xX60gensym128_;
xX60gensym128_ = findStr__commands_321((*(*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 1)])._kind_5.ident).s, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0));
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* xX60gensym128__2;
if (!!((xX60gensym128_ == ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0)))) goto LA21_;
nk = ((tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug) (xX60gensym128_));
xX60gensym128__2 = (*c).semConstBoolExpr(c, (*n)._kind_6.sons->data[((NI) 1)]);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), xX60gensym128__2);
{
NIM_BOOL T25_;
T25_ = (NIM_BOOL)0;
T25_ = ((*xX60gensym128__2).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6));
if (!(T25_)) goto LA26_;
T25_ = !(((*xX60gensym128__2)._kind_1.intVal == IL64(0)));
LA26_: ;
if (!T25_) goto LA27_;
(*(*(*c).graph).config).notes[(NU)((nk- 16))>>3] |=(1U<<((nk- 16)&7U));
}
goto LA23_;
LA27_: ;
{
(*(*(*c).graph).config).notes[(NU)((nk- 16))>>3] &= ~(1U<<((nk- 16)&7U));
}
LA23_: ;
}
goto LA19_;
LA21_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA19_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 123):
{
tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w xX60gensym137_;
xX60gensym137_ = findStr__commands_352((*(*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 1)])._kind_5.ident).s, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0));
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* xX60gensym137__2;
if (!!((xX60gensym137_ == ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0)))) goto LA34_;
nk = ((tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug) (xX60gensym137_));
xX60gensym137__2 = (*c).semConstBoolExpr(c, (*n)._kind_6.sons->data[((NI) 1)]);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), xX60gensym137__2);
{
NIM_BOOL T38_;
T38_ = (NIM_BOOL)0;
T38_ = ((*xX60gensym137__2).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6));
if (!(T38_)) goto LA39_;
T38_ = !(((*xX60gensym137__2)._kind_1.intVal == IL64(0)));
LA39_: ;
if (!T38_) goto LA40_;
(*(*(*c).graph).config).notes[(NU)((nk- 16))>>3] |=(1U<<((nk- 16)&7U));
}
goto LA36_;
LA40_: ;
{
(*(*(*c).graph).config).notes[(NU)((nk- 16))>>3] &= ~(1U<<((nk- 16)&7U));
}
LA36_: ;
}
goto LA32_;
LA34_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA32_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 125):
{
tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w xX60gensym146_;
xX60gensym146_ = findStr__commands_352((*(*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 1)])._kind_5.ident).s, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0));
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* xX60gensym146__2;
if (!!((xX60gensym146_ == ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0)))) goto LA47_;
nk = ((tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug) (xX60gensym146_));
xX60gensym146__2 = (*c).semConstBoolExpr(c, (*n)._kind_6.sons->data[((NI) 1)]);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), xX60gensym146__2);
{
NIM_BOOL T51_;
T51_ = (NIM_BOOL)0;
T51_ = ((*xX60gensym146__2).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6));
if (!(T51_)) goto LA52_;
T51_ = !(((*xX60gensym146__2)._kind_1.intVal == IL64(0)));
LA52_: ;
if (!T51_) goto LA53_;
(*(*(*c).graph).config).warningAsErrors[(NU)((nk- 16))>>3] |=(1U<<((nk- 16)&7U));
}
goto LA49_;
LA53_: ;
{
(*(*(*c).graph).config).warningAsErrors[(NU)((nk- 16))>>3] &= ~(1U<<((nk- 16)&7U));
}
LA49_: ;
}
goto LA45_;
LA47_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA45_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 126):
{
tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w xX60gensym155_;
xX60gensym155_ = findStr__commands_321((*(*(*(*n)._kind_6.sons->data[((NI) 0)])._kind_6.sons->data[((NI) 1)])._kind_5.ident).s, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0));
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* xX60gensym155__2;
if (!!((xX60gensym155_ == ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 0)))) goto LA60_;
nk = ((tyEnum_TMsgKind__7VIi6mabc7hDxpCmSMYIug) (xX60gensym155_));
xX60gensym155__2 = (*c).semConstBoolExpr(c, (*n)._kind_6.sons->data[((NI) 1)]);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), xX60gensym155__2);
{
NIM_BOOL T64_;
T64_ = (NIM_BOOL)0;
T64_ = ((*xX60gensym155__2).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6));
if (!(T64_)) goto LA65_;
T64_ = !(((*xX60gensym155__2)._kind_1.intVal == IL64(0)));
LA65_: ;
if (!T64_) goto LA66_;
(*(*(*c).graph).config).warningAsErrors[(NU)((nk- 16))>>3] |=(1U<<((nk- 16)&7U));
}
goto LA62_;
LA66_: ;
{
(*(*(*c).graph).config).warningAsErrors[(NU)((nk- 16))>>3] &= ~(1U<<((nk- 16)&7U));
}
LA62_: ;
}
goto LA58_;
LA60_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA58_: ;
}
break;
default:
{
invalidPragma__pragmas_148(c, n);
}
break;
}
}
goto LA1_;
LA15_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, processExc__pragmas_1334)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* x) {
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = (*c).hasUnresolvedArgs.ClE_0? (*c).hasUnresolvedArgs.ClP_0(c, x, (*c).hasUnresolvedArgs.ClE_0):((TM__tPA3StZ6VsKyoznyrIfFxg_9)((*c).hasUnresolvedArgs.ClP_0))(c, x);
if (!T3_) goto LA4_;
asgnRef((void**) (&(*x).typ), makeTypeFromExpr__semdata_804(c, x));
}
goto LA1_;
LA4_: ;
{
tyObject_TType__facALICuu8zUj0hjvbTLFg* t;
tyObject_TType__facALICuu8zUj0hjvbTLFg* T7_;
T7_ = NIM_NIL;
T7_ = (*c).semTypeNode(c, x, ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
t = skipTypes__ast_3735(T7_, TM__tPA3StZ6VsKyoznyrIfFxg_10);
{
NIM_BOOL T10_;
NIM_BOOL T12_;
T10_ = (NIM_BOOL)0;
T10_ = !(((*t).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 17)));
if (!(T10_)) goto LA11_;
T12_ = (NIM_BOOL)0;
T12_ = isMetaType__ast_3495(t);
T10_ = !(T12_);
LA11_: ;
if (!T10_) goto LA13_;
liMessage__msgs_1118((*(*c).graph).config, (*x).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_11), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_12, NIM_FALSE);
}
LA13_: ;
asgnRef((void**) (&(*x).typ), t);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaRaisesOrTags__pragmas_1331)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
it = (*n)._kind_6.sons->data[((NI) 1)];
{
if (!!(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 39) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41)))) goto LA10_;
processExc__pragmas_1334(c, it);
}
goto LA8_;
LA10_: ;
{
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* e;
e = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(it);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA16;
i = i_2;
e = (*it)._kind_6.sons->data[i];
processExc__pragmas_1334(c, e);
i_2 += ((NI) 1);
} LA16: ;
}
}
}
}
LA8_: ;
}
goto LA1_;
LA6_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA1_: ;
}
static N_INLINE(void, nimSetMem__systemZmemory_7)(void* a, int v, NI size) {
void* T1_;
T1_ = (void*)0;
T1_ = memset(a, v, ((size_t) (size)));
}
static N_INLINE(void, nimZeroMem)(void* p, NI size) {
nimSetMem__systemZmemory_7(p, ((int) 0), size);
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, semCustomPragma__pragmas_1525)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* callNode;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* r;
{ result = NIM_NIL;
callNode = NIM_NIL;
{
tyArray__jlWPjgtbdjE069arIWHC9c9bg T5_;
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 3))) goto LA3_;
nimZeroMem((void*)T5_, sizeof(tyArray__jlWPjgtbdjE069arIWHC9c9bg));
T5_[0] = n;
callNode = newTree__ast_3392(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27), T5_, 1);
}
goto LA1_;
LA3_: ;
{
tyArray__AB6yfoUgfWM2NtGe9bzkCmw T9_;
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34))) goto LA7_;
nimZeroMem((void*)T9_, sizeof(tyArray__AB6yfoUgfWM2NtGe9bzkCmw));
T9_[0] = (*n)._kind_6.sons->data[((NI) 0)];
T9_[1] = (*n)._kind_6.sons->data[((NI) 1)];
callNode = newTree__ast_3392(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27), T9_, 2);
}
goto LA1_;
LA7_: ;
{
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA11_;
callNode = n;
}
goto LA1_;
LA11_: ;
{
invalidPragma__pragmas_148(c, n);
result = n;
goto BeforeRet_;
}
LA1_: ;
r = (*c).semOverloadedCall(c, callNode, n, 262144, 262144);
{
NIM_BOOL T16_;
T16_ = (NIM_BOOL)0;
T16_ = (r == 0);
if (T16_) goto LA17_;
T16_ = !((((*(*(*r)._kind_6.sons->data[((NI) 0)])._kind_4.sym).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 10))&63U)))!=0));
LA17_: ;
if (!T16_) goto LA18_;
invalidPragma__pragmas_148(c, n);
result = n;
goto BeforeRet_;
}
LA18_: ;
result = r;
{
NIM_BOOL T22_;
NI T24_;
T22_ = (NIM_BOOL)0;
T22_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
if (!(T22_)) goto LA23_;
T24_ = (NI)0;
T24_ = len__ast_3198(r);
T22_ = (T24_ == ((NI) 1));
LA23_: ;
if (!T22_) goto LA25_;
result = (*result)._kind_6.sons->data[((NI) 0)];
}
goto LA20_;
LA25_: ;
{
NIM_BOOL T28_;
NI T30_;
T28_ = (NIM_BOOL)0;
T28_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34));
if (!(T28_)) goto LA29_;
T30_ = (NI)0;
T30_ = len__ast_3198(r);
T28_ = (T30_ == ((NI) 2));
LA29_: ;
if (!T28_) goto LA31_;
transitionSonsKind__ast_4359(result, ((tyEnum_TNodeKind__Dq0DNfMwTBUf7hLFKKDU7g) ((*n).kind)));
}
goto LA20_;
LA31_: ;
LA20_: ;
}BeforeRet_: ;
return result;
}
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___pureZunicode_840)(NI a, NI b) {
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA result;
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
result.a = a;
result.b = b;
return result;
}
static N_INLINE(int, nimCmpMem)(void* a, void* b, NI size) {
int result;
result = (int)0;
result = memcmp(a, b, ((size_t) (size)));
return result;
}
static N_INLINE(NIM_BOOL, equalMem__system_1735)(void* a, void* b, NI size) {
NIM_BOOL result;
int T1_;
result = (NIM_BOOL)0;
T1_ = (int)0;
T1_ = nimCmpMem(a, b, size);
result = (T1_ == ((NI32) 0));
return result;
}
static N_INLINE(NIM_BOOL, eqStrings)(NimStringDesc* a, NimStringDesc* b) {
NIM_BOOL result;
NI alen;
NI blen;
{ result = (NIM_BOOL)0;
alen = (a ? a->Sup.len : 0);
blen = (b ? b->Sup.len : 0);
{
if (!(alen == blen)) goto LA3_;
{
if (!(alen == ((NI) 0))) goto LA7_;
result = NIM_TRUE;
goto BeforeRet_;
}
LA7_: ;
result = equalMem__system_1735(((void*) ((&a->data[((NI) 0)]))), ((void*) ((&b->data[((NI) 0)]))), ((NI) (alen)));
goto BeforeRet_;
}
LA3_: ;
}BeforeRet_: ;
return result;
}
static N_INLINE(NI, find__pureZos_656)(NIM_CHAR* a, NI aLen_0, NIM_CHAR item) {
NI result;
{ result = (NI)0;
result = ((NI) 0);
{
NIM_CHAR i;
NI i_2;
i = (NIM_CHAR)0;
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < aLen_0)) goto LA3;
i = a[i_2];
{
if (!((NU8)(i) == (NU8)(item))) goto LA6_;
goto BeforeRet_;
}
LA6_: ;
result += ((NI) 1);
i_2 += ((NI) 1);
} LA3: ;
}
}
result = ((NI) -1);
}BeforeRet_: ;
return result;
}
static N_INLINE(NIM_BOOL, contains__pureZos_651)(NIM_CHAR* a, NI aLen_0, NIM_CHAR item) {
NIM_BOOL result;
NI T1_;
{ result = (NIM_BOOL)0;
T1_ = (NI)0;
T1_ = find__pureZos_656(a, aLen_0, item);
result = (((NI) 0) <= T1_);
goto BeforeRet_;
}BeforeRet_: ;
return result;
}
static N_INLINE(void, pushSafePoint)(TSafePoint* s) {
(*s).prev = excHandler__system_2565;
excHandler__system_2565 = s;
}
static N_INLINE(void, popSafePoint)(void) {
excHandler__system_2565 = (*excHandler__system_2565).prev;
}
static N_INLINE(Exception*, nimBorrowCurrentException)(void) {
Exception* result;
result = NIM_NIL;
result = currException__system_2566;
return result;
}
static N_INLINE(void, popCurrentException)(void) {
asgnRef((void**) (&currException__system_2566), (*currException__system_2566).up);
}
N_LIB_PRIVATE N_NIMCALL(void, setExternName__pragmas_238)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
{
if (!eqStrings(extname, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15))) goto LA3_;
asgnRef((void**) (&(*s).loc.r), rope__ropes_109((*(*s).name).s));
}
goto LA1_;
LA3_: ;
{
NIM_BOOL T6_;
T6_ = (NIM_BOOL)0;
T6_ = contains__pureZos_651(extname->data, (extname ? extname->Sup.len : 0), 36);
if (!!(T6_)) goto LA7_;
asgnRef((void**) (&(*s).loc.r), rope__ropes_109(extname));
}
goto LA1_;
LA7_: ;
{
TSafePoint TM__tPA3StZ6VsKyoznyrIfFxg_16;
NimStringDesc* T10_;
pushSafePoint(&TM__tPA3StZ6VsKyoznyrIfFxg_16);
TM__tPA3StZ6VsKyoznyrIfFxg_16.status = setjmp(TM__tPA3StZ6VsKyoznyrIfFxg_16.context);
if (TM__tPA3StZ6VsKyoznyrIfFxg_16.status == 0) {
T10_ = NIM_NIL;
T10_ = nsuFormatSingleElem(extname, (*(*s).name).s);
asgnRef((void**) (&(*s).loc.r), rope__ropes_109(T10_));
popSafePoint();
}
else {
popSafePoint();
if (isObj(nimBorrowCurrentException()->Sup.m_type, (&NTIvalueerror__yoNlBGx0D2tRizIdhQuENw_))) {
NimStringDesc* T13_;
TM__tPA3StZ6VsKyoznyrIfFxg_16.status = 0;
T13_ = NIM_NIL;
T13_ = rawNewString((extname ? extname->Sup.len : 0) + 48);
appendString(T13_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_17));
appendString(T13_, extname);
appendString(T13_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_18));
liMessage__msgs_1118((*(*c).graph).config, info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), T13_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_19, NIM_FALSE);
popCurrentException();
}
}
if (TM__tPA3StZ6VsKyoznyrIfFxg_16.status != 0) reraiseException();
}
LA1_: ;
{
NIM_BOOL T16_;
NIM_BOOL T18_;
T16_ = (NIM_BOOL)0;
T16_ = ((*(*(*c).graph).config).cmd == ((tyEnum_Command__0zjcIQ623TIRGPdtjLwTFA) 27));
if (!(T16_)) goto LA17_;
T18_ = (NIM_BOOL)0;
T18_ = contains__pureZos_651(extname->data, (extname ? extname->Sup.len : 0), 36);
T16_ = !(T18_);
LA17_: ;
if (!T16_) goto LA19_;
(*s).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 1)) & 15);
}
LA19_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, makeExternExport__pragmas_272)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
setExternName__pragmas_238(c, s, extname, info);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 7)) & 63);
}
N_LIB_PRIVATE N_NOINLINE(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, newEmptyStrNode__pragmas_350)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
tyObject_TType__facALICuu8zUj0hjvbTLFg* T1_;
result = NIM_NIL;
T1_ = NIM_NIL;
T1_ = getSysType__magicsys_60((*c).graph, (*n).info, ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 28));
result = newNodeIT__ast_3378(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20), (*n).info, T1_);
asgnRef((void**) (&(*result)._kind_3.strVal), ((NimStringDesc*) NIM_NIL));
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, getStrLitNode__pragmas_354)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
result = NIM_NIL;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_21, NIM_FALSE);
result = newEmptyStrNode__pragmas_350(c, n);
}
goto LA1_;
LA6_: ;
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semConstExpr(c, (*n)._kind_6.sons->data[((NI) 1)]));
switch ((*(*n)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
result = (*n)._kind_6.sons->data[((NI) 1)];
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_22, NIM_FALSE);
result = newEmptyStrNode__pragmas_350(c, n);
}
break;
}
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, expectStrLit__pragmas_371)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NimStringDesc* result;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T1_;
result = NIM_NIL;
T1_ = NIM_NIL;
T1_ = getStrLitNode__pragmas_354(c, n);
result = copyString((*T1_)._kind_3.strVal);
return result;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, getOptionalStr__pragmas_392)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc* defaultStr) {
NimStringDesc* result;
result = NIM_NIL;
{
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA3_;
result = expectStrLit__pragmas_371(c, n);
}
goto LA1_;
LA3_: ;
{
result = copyString(defaultStr);
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, recordPragma__pragmas_129)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc** args, NI argsLen_0) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* recorded;
recorded = newNodeI__ast_3356(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 163), (*n).info);
{
NI i;
NI colontmp_;
NI res;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = (argsLen_0-1);
res = ((NI) 0);
{
while (1) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T4_;
if (!(res <= colontmp_)) goto LA3;
i = res;
T4_ = NIM_NIL;
T4_ = newStrNode__ast_3817(args[i], (*n).info);
add__ast_4797(recorded, T4_);
res += ((NI) 1);
} LA3: ;
}
}
addPragmaComputation__semdata_618(c, recorded);
}
N_LIB_PRIVATE N_NIMCALL(void, makeExternImport__pragmas_259)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
setExternName__pragmas_238(c, s, extname, info);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*s).flags &= ~(((NU64)1) << ((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63));
}
N_LIB_PRIVATE N_NIMCALL(void, processImportCompilerProc__pragmas_281)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
setExternName__pragmas_238(c, s, extname, info);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*s).flags &= ~(((NU64)1) << ((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63));
(*s).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 7)) & 15);
}
N_LIB_PRIVATE N_NIMCALL(void, processImportCpp__pragmas_298)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
setExternName__pragmas_238(c, s, extname, info);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 32)) & 63);
(*s).flags &= ~(((NU64)1) << ((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63));
{
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* m;
if (!((*(*(*c).graph).config).backend == ((tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g) 1))) goto LA3_;
m = getModule__astalgo_216(s);
(*m).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 32)) & 63);
}
LA3_: ;
(*(*(*c).graph).config).globalOptions |= ((NU64)1)<<((((tyEnum_TGlobalOption__RAfAEZqjnKMDumgyKKc1qw) 35)) & 63);
}
N_LIB_PRIVATE N_NIMCALL(void, processImportObjC__pragmas_328)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s, NimStringDesc* extname, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* m;
setExternName__pragmas_238(c, s, extname, info);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 33)) & 63);
(*s).flags &= ~(((NU64)1) << ((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63));
m = getModule__astalgo_216(s);
(*m).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 33)) & 63);
}
N_LIB_PRIVATE N_NIMCALL(NI, expectIntLit__pragmas_375)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NI result;
result = (NI)0;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_31), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_32, NIM_FALSE);
}
goto LA1_;
LA6_: ;
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semConstExpr(c, (*n)._kind_6.sons->data[((NI) 1)]));
switch ((*(*n)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6) ... ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 10):
{
result = ((NI) ((*(*n)._kind_6.sons->data[((NI) 1)])._kind_1.intVal));
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_31), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_33, NIM_FALSE);
}
break;
}
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, noVal__pragmas_1213)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (((NI) 1) < T5_);
LA4_: ;
if (!T3_) goto LA6_;
invalidPragma__pragmas_148(c, n);
}
LA6_: ;
}
static N_NIMCALL(void, Marker_tyRef__b333ORV1UJUlL6q84XcNlQ)(void* p, NI op) {
tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw* a;
a = (tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw*)p;
nimGCvisit((void*)(*a).owner1, op);
}
N_LIB_PRIVATE N_CLOSURE(void, processParam__pragmas_1574)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, void* ClE_0) {
tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw* colonenvP_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* r;
colonenvP_ = (tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw*) ClE_0;
r = (*c).semExpr(c, n, 0);
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = ((*r).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 3));
if (!(T3_)) goto LA4_;
T3_ = ((*(*r)._kind_4.sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 3));
LA4_: ;
if (!T3_) goto LA5_;
{
if (!((*(*r)._kind_4.sym).owner == (*colonenvP_).owner1)) goto LA9_;
(*(*r)._kind_4.sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 47)) & 63);
}
goto LA7_;
LA9_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_41), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_42, NIM_FALSE);
}
LA7_: ;
}
goto LA1_;
LA5_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_39), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_43, NIM_FALSE);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, processEffectsOf__pragmas_1570)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* owner) {
tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw* colonenv_;
colonenv_ = NIM_NIL;
colonenv_ = (tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw*) newObj((&NTIrefobject__b333ORV1UJUlL6q84XcNlQ_), sizeof(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw));
(*colonenv_).Sup.m_type = (&NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_);
asgnRef((void**) (&(*colonenv_).owner1), owner);
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_39), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_40, NIM_FALSE);
}
goto LA1_;
LA6_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
it = (*n)._kind_6.sons->data[((NI) 1)];
{
if (!((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 39) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41))) goto LA11_;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* x;
x = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(it);
i_2 = ((NI) 0);
{
while (1) {
tyProc__BuyrpAaTYqHepBvBU6qokA T17_;
if (!(i_2 < colontmp_)) goto LA16;
i = i_2;
x = (*it)._kind_6.sons->data[i];
nimZeroMem((void*)(&T17_), sizeof(tyProc__BuyrpAaTYqHepBvBU6qokA));
T17_.ClP_0 = processParam__pragmas_1574; T17_.ClE_0 = colonenv_;
T17_.ClE_0? T17_.ClP_0(c, x, T17_.ClE_0):((TM__tPA3StZ6VsKyoznyrIfFxg_44)(T17_.ClP_0))(c, x);
i_2 += ((NI) 1);
} LA16: ;
}
}
}
}
goto LA9_;
LA11_: ;
{
tyProc__BuyrpAaTYqHepBvBU6qokA T19_;
nimZeroMem((void*)(&T19_), sizeof(tyProc__BuyrpAaTYqHepBvBU6qokA));
T19_.ClP_0 = processParam__pragmas_1574; T19_.ClE_0 = colonenv_;
T19_.ClE_0? T19_.ClP_0(c, it, T19_.ClE_0):((TM__tPA3StZ6VsKyoznyrIfFxg_45)(T19_.ClP_0))(c, it);
}
LA9_: ;
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, isTurnedOn__pragmas_467)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NIM_BOOL result;
{ result = (NIM_BOOL)0;
{
NIM_BOOL T3_;
NI T5_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* x;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
x = (*c).semConstBoolExpr(c, (*n)._kind_6.sons->data[((NI) 1)]);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), x);
{
if (!((*x).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6))) goto LA10_;
result = !(((*x)._kind_1.intVal == IL64(0)));
goto BeforeRet_;
}
LA10_: ;
}
LA6_: ;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_46), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_47, NIM_FALSE);
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaNoForward__pragmas_502)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw flag) {
NimStringDesc* T7_;
NimStringDesc* T8_;
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = isTurnedOn__pragmas_467(c, n);
if (!T3_) goto LA4_;
(*(*c).module).flags |= ((NU64)1)<<((flag) & 63);
(*c).features |= ((NU32)1)<<((((tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ) 9)) & 31);
}
goto LA1_;
LA4_: ;
{
(*(*c).module).flags &= ~(((NU64)1) << ((flag) & 63));
}
LA1_: ;
T7_ = NIM_NIL;
T8_ = NIM_NIL;
{
if (!(flag == ((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 10))) goto LA11_;
T8_ = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_49));
}
goto LA9_;
LA11_: ;
{
T8_ = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_50));
}
LA9_: ;
T7_ = rawNewString((T8_ ? T8_->Sup.len : 0) + 62);
appendString(T7_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_48));
appendString(T7_, T8_);
appendString(T7_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_51));
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 20), T7_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_52, NIM_FALSE);
}
N_LIB_PRIVATE N_NIMCALL(void, processMagic__pragmas_405)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s) {
NimStringDesc* v;
{ {
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_53, NIM_FALSE);
goto BeforeRet_;
}
LA6_: ;
v = NIM_NIL;
{
if (!((*(*n)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2))) goto LA10_;
v = copyString((*(*(*n)._kind_6.sons->data[((NI) 1)])._kind_5.ident).s);
}
goto LA8_;
LA10_: ;
{
v = expectStrLit__pragmas_371(c, n);
}
LA8_: ;
{
tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg m;
m = (tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg)0;
{
tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg v_2;
NI res;
v_2 = (tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg)0;
res = ((NI) 0);
{
while (1) {
if (!(res <= ((NI) 275))) goto LA16;
v_2 = ((tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg) (res));
m = v_2;
{
NimStringDesc* T19_;
T19_ = NIM_NIL;
T19_ = substr__system_7785(reprEnum((NI)m, (&NTItmagic__shZhZOdbVC5nnFvcXQAImg_)), ((NI) 1));
if (!eqStrings(T19_, v)) goto LA20_;
(*s).magic = m;
goto LA13;
}
LA20_: ;
res += ((NI) 1);
} LA16: ;
}
}
} LA13: ;
{
if (!((*s).magic == ((tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg) 0))) goto LA24_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 24), v, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_54, NIM_FALSE);
}
LA24_: ;
}BeforeRet_: ;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA*, getLib__pragmas_544)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ kind, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* path) {
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* result;
NI T11_;
{ result = NIM_NIL;
{
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA** it;
NI i;
NI L;
NI T2_;
it = (tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA**)0;
i = ((NI) 0);
T2_ = ((*c).libs ? (*c).libs->Sup.len : 0);
L = T2_;
{
while (1) {
if (!(i < L)) goto LA4;
it = &(*c).libs->data[i];
{
NIM_BOOL T7_;
T7_ = (NIM_BOOL)0;
T7_ = ((*(*it)).kind == kind);
if (!(T7_)) goto LA8_;
T7_ = exprStructuralEquivalent__trees_56((*(*it)).path, path, NIM_FALSE);
LA8_: ;
if (!T7_) goto LA9_;
result = (*it);
goto BeforeRet_;
}
LA9_: ;
i += ((NI) 1);
} LA4: ;
}
}
result = newLib__semdata_724(kind);
asgnRef((void**) (&(*result).path), path);
asgnRef((void**) (&(*c).libs), (tySequence__arD7Tw6eD6lvOczWZl9buNg*) incrSeqV3((TGenericSeq*)((*c).libs), (&NTIseqLplibT__arD7Tw6eD6lvOczWZl9buNg_)));
T11_ = (*c).libs->Sup.len++;
asgnRef((void**) (&(*c).libs->data[T11_]), result);
{
if (!((*path).kind >= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20) && (*path).kind <= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22))) goto LA14_;
(*result).isOverriden = isDynlibOverride__options_4677((*(*c).graph).config, (*path)._kind_3.strVal);
}
LA14_: ;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, expectDynlibNode__pragmas_591)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
result = NIM_NIL;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_57, NIM_FALSE);
result = newEmptyStrNode__pragmas_350(c, n);
}
goto LA1_;
LA6_: ;
{
result = (*c).semExpr(c, (*n)._kind_6.sons->data[((NI) 1)], 0);
{
NIM_BOOL T11_;
T11_ = (NIM_BOOL)0;
T11_ = ((*result).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 3));
if (!(T11_)) goto LA12_;
T11_ = ((*(*result)._kind_4.sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 10));
LA12_: ;
if (!T11_) goto LA13_;
result = (*(*result)._kind_4.sym).ast;
}
LA13_: ;
{
NIM_BOOL T17_;
T17_ = (NIM_BOOL)0;
T17_ = ((*result).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
if (T17_) goto LA18_;
T17_ = !(((*(*result).typ).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 26) || (*(*result).typ).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 28) || (*(*result).typ).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 25)));
LA18_: ;
if (!T17_) goto LA19_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_58, NIM_FALSE);
result = newEmptyStrNode__pragmas_350(c, n);
}
LA19_: ;
}
LA1_: ;
return result;
}
static N_INLINE(tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**, X5BX5D___semdata_344)(tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** s, NI sLen_0, NI i) {
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** result;
result = (tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**)0;
result = &s[(NI)(sLen_0 - i)];
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processDynLib__pragmas_621)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym) {
{
NIM_BOOL T3_;
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* lib;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T7_;
T3_ = (NIM_BOOL)0;
T3_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T3_) goto LA4_;
T3_ = ((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 6));
LA4_: ;
if (!T3_) goto LA5_;
T7_ = NIM_NIL;
T7_ = expectDynlibNode__pragmas_591(c, n);
lib = getLib__pragmas_544(c, ((tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ) 1), T7_);
{
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** T12_;
if (!!((*lib).isOverriden)) goto LA10_;
T12_ = (tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**)0;
T12_ = X5BX5D___semdata_344((*c).optionStack->data, ((*c).optionStack ? (*c).optionStack->Sup.len : 0), ((NI) 1));
asgnRef((void**) (&(*(*T12_)).dynlib), lib);
}
LA10_: ;
}
goto LA1_;
LA5_: ;
{
{
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* lib_2;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T18_;
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA16_;
T18_ = NIM_NIL;
T18_ = expectDynlibNode__pragmas_591(c, n);
lib_2 = getLib__pragmas_544(c, ((tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ) 1), T18_);
{
if (!!((*lib_2).isOverriden)) goto LA21_;
addToLib__semdata_730(lib_2, sym);
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 4)) & 15);
}
LA21_: ;
}
goto LA14_;
LA16_: ;
{
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 5)) & 15);
}
LA14_: ;
{
NIM_BOOL T26_;
NIM_BOOL T27_;
T26_ = (NIM_BOOL)0;
T27_ = (NIM_BOOL)0;
T27_ = ((520192 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
if (!(T27_)) goto LA28_;
T27_ = !(((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)));
LA28_: ;
T26_ = T27_;
if (!(T26_)) goto LA29_;
T26_ = !((((*(*sym).typ).flags &((NU64)1<<((NU)(((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 42))&63U)))!=0));
LA29_: ;
if (!T26_) goto LA30_;
(*(*sym).typ).callConv = ((tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA) 2);
}
LA30_: ;
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, markCompilerProc__pragmas_1425)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s) {
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*s).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7)));
if (T3_) goto LA4_;
T3_ = !(eqStrings((*(*s).name).s, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_59)));
LA4_: ;
if (!T3_) goto LA5_;
makeExternExport__pragmas_272(c, s, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15), (*s).info);
}
LA5_: ;
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 18)) & 63);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 0)) & 63);
registerCompilerProc__magicsys_154((*c).graph, s);
{
if (!!(((*(*(*c).graph).config).symbolFiles == ((tyEnum_SymbolFilesOption__gBES9bqm1ru9ape8SeMRAFgQ) 0)))) goto LA9_;
addCompilerProc__icZic_2411((&(*(*c).graph).encoders->data[(*(*c).module).position]), (&(*(*c).graph).packed_0->data[(*(*c).module).position].fromDisk), s);
}
LA9_: ;
}
static N_INLINE(tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g, nextSymId__ast_3132)(tyObject_IdGeneratorcolonObjectType___9a3T65u6nPPLrld0SrEa57Q* x) {
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g result;
nimZeroMem((void*)(&result), sizeof(tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g));
(*x).symId += ((NI) 1);
nimZeroMem((void*)(&result), sizeof(tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g));
result.module = (*x).module;
result.item = (*x).symId;
return result;
}
static N_INLINE(void, addInterfaceDecl__lookups_879)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym) {
addInterfaceDeclAt__lookups_875(c, (*c).currentScope, sym);
}
N_LIB_PRIVATE N_NIMCALL(void, deprecatedStmt__pragmas_1444)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* outerPragma) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* pragma;
{ pragma = (*outerPragma)._kind_6.sons->data[((NI) 1)];
{
if (!((*pragma).kind >= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20) && (*pragma).kind <= ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22))) goto LA3_;
(*(*c).module).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 22)) & 63);
asgnRef((void**) (&(*(*c).module).constraint), getStrLitNode__pragmas_354(c, outerPragma));
goto BeforeRet_;
}
LA3_: ;
{
if (!!(((*pragma).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41)))) goto LA7_;
liMessage__msgs_1118((*(*c).graph).config, (*pragma).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_62), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_63, NIM_FALSE);
goto BeforeRet_;
}
LA7_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n;
n = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(pragma);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA12;
i = i_2;
n = (*pragma)._kind_6.sons->data[i];
{
NIM_BOOL T15_;
NI T17_;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* dest;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* src;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* alias;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g T26_;
T15_ = (NIM_BOOL)0;
T15_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T15_)) goto LA16_;
T17_ = (NI)0;
T17_ = len__ast_3198(n);
T15_ = (T17_ == ((NI) 2));
LA16_: ;
if (!T15_) goto LA18_;
dest = qualifiedLookUp__lookups_1233(c, (*n)._kind_6.sons->data[((NI) 1)], 2);
{
NIM_BOOL T22_;
T22_ = (NIM_BOOL)0;
T22_ = (dest == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T22_) goto LA23_;
T22_ = ((520192 &((NU32)1<<((NU)((*dest).kind)&31U)))!=0);
LA23_: ;
if (!T22_) goto LA24_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 67), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_64), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_65, NIM_FALSE);
}
LA24_: ;
src = considerQuotedIdent__lookups_28(c, (*n)._kind_6.sons->data[((NI) 0)], ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL));
T26_ = nextSymId__ast_3132((*c).Sup.idgen);
alias = newSym__ast_3445(((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 25), src, T26_, dest, (*(*n)._kind_6.sons->data[((NI) 0)]).info, (*(*(*c).graph).config).options);
(*alias).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 1)) & 63);
{
if (!(((*dest).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 18))&63U)))!=0)) goto LA29_;
markCompilerProc__pragmas_1425(c, alias);
}
LA29_: ;
addInterfaceDecl__lookups_879(c, alias);
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), newSymNode__ast_3716(dest));
}
goto LA13_;
LA18_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_66), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_67, NIM_FALSE);
}
LA13_: ;
i_2 += ((NI) 1);
} LA12: ;
}
}
}
}BeforeRet_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, typeBorrow__pragmas_1404)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
it = (*n)._kind_6.sons->data[((NI) 1)];
{
if (!!(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 53)))) goto LA10_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_68), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_69, NIM_FALSE);
}
LA10_: ;
}
LA6_: ;
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 32)) & 63);
}
static N_INLINE(NIM_BOOL, isRoutine__ast_4676)(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s) {
NIM_BOOL result;
result = (NIM_BOOL)0;
result = ((520192 &((NU32)1<<((NU)((*s).kind)&31U)))!=0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processDefine__pragmas_1032)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NIM_BOOL T4_;
NI T6_;
T3_ = (NIM_BOOL)0;
T4_ = (NIM_BOOL)0;
T4_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T4_)) goto LA5_;
T6_ = (NI)0;
T6_ = len__ast_3198(n);
T4_ = (T6_ == ((NI) 2));
LA5_: ;
T3_ = T4_;
if (!(T3_)) goto LA7_;
T3_ = ((*(*n)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA7_: ;
if (!T3_) goto LA8_;
defineSymbol__condsyms_4((*(*(*c).graph).config).symbols, (*(*(*n)._kind_6.sons->data[((NI) 1)])._kind_5.ident).s, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_77));
}
goto LA1_;
LA8_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, processUndef__pragmas_1048)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NIM_BOOL T4_;
NI T6_;
T3_ = (NIM_BOOL)0;
T4_ = (NIM_BOOL)0;
T4_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T4_)) goto LA5_;
T6_ = (NI)0;
T6_ = len__ast_3198(n);
T4_ = (T6_ == ((NI) 2));
LA5_: ;
T3_ = T4_;
if (!(T3_)) goto LA7_;
T3_ = ((*(*n)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA7_: ;
if (!T3_) goto LA8_;
undefSymbol__condsyms_8((*(*(*c).graph).config).symbols, (*(*(*n)._kind_6.sons->data[((NI) 1)])._kind_5.ident).s);
}
goto LA1_;
LA8_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, getStrLit__pragmas_1083)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI i) {
NimStringDesc* result;
result = NIM_NIL;
asgnRef((void**) (&(*n)._kind_6.sons->data[i]), (*c).semConstExpr(c, (*n)._kind_6.sons->data[i]));
switch ((*(*n)._kind_6.sons->data[i]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
result = (*(*n)._kind_6.sons->data[i])._kind_3.strVal;
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_78, NIM_FALSE);
result = ((NimStringDesc*) NIM_NIL);
}
break;
}
return result;
}
static N_INLINE(NimStringDesc*, slash___pureZos_121)(NimStringDesc* head, NimStringDesc* tail) {
NimStringDesc* result;
result = NIM_NIL;
result = nosjoinPath(head, tail);
return result;
}
static N_INLINE(NCSTRING, nimToCStringConv)(NimStringDesc* s) {
NCSTRING result;
result = (NCSTRING)0;
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = (s == ((NimStringDesc*) NIM_NIL));
if (T3_) goto LA4_;
T3_ = ((*s).Sup.len == ((NI) 0));
LA4_: ;
if (!T3_) goto LA5_;
result = "";
}
goto LA1_;
LA5_: ;
{
result = ((NCSTRING) ((*s).data));
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, docompile__pragmas_1076)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it, NimStringDesc* src, NimStringDesc* dest, NimStringDesc* customArgs) {
tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg cf;
tyTuple__7q7q3E6Oj24ZNVJb9aonhAg T1_;
tyArray__sMpvt1sOxOJ3LFGulnbeMQ T2_;
nimZeroMem((void*)(&cf), sizeof(tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg));
nimZeroMem((void*)(&cf), sizeof(tyObject_Cfile__i9cKq1ZGd1wgagjUEHLVFtg));
nimZeroMem((void*)(&T1_), sizeof(tyTuple__7q7q3E6Oj24ZNVJb9aonhAg));
splitFile__pathutils_26(src, (&T1_));
cf.nimname = copyString(T1_.Field1);
cf.cname = copyString(src);
cf.obj = copyString(dest);
cf.flags = 2;
cf.customArgs = copyString(customArgs);
addExternalFileToCompile__extccomp_1066((*(*c).graph).config, (&cf));
nimZeroMem((void*)T2_, sizeof(tyArray__sMpvt1sOxOJ3LFGulnbeMQ));
T2_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_80));
T2_[1] = copyString(src);
T2_[2] = copyString(dest);
T2_[3] = copyString(customArgs);
recordPragma__pragmas_129(c, it, T2_, 4);
}
static N_INLINE(NIM_BOOL, isEmpty__options_4495)(NimStringDesc* x) {
NIM_BOOL result;
result = (NIM_BOOL)0;
result = ((x ? x->Sup.len : 0) == ((NI) 0));
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processCompile__pragmas_1073)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
it = (*n)._kind_6.sons->data[((NI) 1)];
}
goto LA1_;
LA6_: ;
{
it = n;
}
LA1_: ;
{
NIM_BOOL T11_;
NI T13_;
NimStringDesc* s;
NimStringDesc* dest;
NimStringDesc* found;
NimStringDesc* T16_;
NimStringDesc* T17_;
T11_ = (NIM_BOOL)0;
T11_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 37) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 160));
if (!(T11_)) goto LA12_;
T13_ = (NI)0;
T13_ = len__ast_3198(it);
T11_ = (T13_ == ((NI) 2));
LA12_: ;
if (!T11_) goto LA14_;
s = getStrLit__pragmas_1083(c, it, ((NI) 0));
dest = getStrLit__pragmas_1083(c, it, ((NI) 1));
T16_ = NIM_NIL;
T16_ = toFullPath__msgs_538((*(*c).graph).config, (*n).info.fileIndex);
T17_ = NIM_NIL;
T17_ = nosparentDir(T16_);
found = slash___pureZos_121(T17_, s);
{
NimStringDesc* f;
glob_t fX60gensym137_;
NI resX60gensym137_;
int T19_;
TSafePoint TM__tPA3StZ6VsKyoznyrIfFxg_79;
f = NIM_NIL;
nimZeroMem((void*)(&fX60gensym137_), sizeof(glob_t));
resX60gensym137_ = (NI)0;
fX60gensym137_.gl_offs = ((NI) 0);
fX60gensym137_.gl_pathc = ((NI) 0);
fX60gensym137_.gl_pathv = ((NCSTRING*) NIM_NIL);
T19_ = (int)0;
T19_ = glob(nimToCStringConv(found), ((int) 0), NIM_NIL, (&fX60gensym137_));
resX60gensym137_ = ((NI) (T19_));
pushSafePoint(&TM__tPA3StZ6VsKyoznyrIfFxg_79);
TM__tPA3StZ6VsKyoznyrIfFxg_79.status = setjmp(TM__tPA3StZ6VsKyoznyrIfFxg_79.context);
if (TM__tPA3StZ6VsKyoznyrIfFxg_79.status == 0) {
{
if (!(resX60gensym137_ == ((NI) 0))) goto LA22_;
{
NI iX60gensym137_;
NI colontmp_;
NI res;
iX60gensym137_ = (NI)0;
colontmp_ = (NI)0;
colontmp_ = (NI)(fX60gensym137_.gl_pathc - ((NI) 1));
res = ((NI) 0);
{
while (1) {
NimStringDesc* pathX60gensym137_;
if (!(res <= colontmp_)) goto LA26;
iX60gensym137_ = res;
pathX60gensym137_ = cstrToNimstr(fX60gensym137_.gl_pathv[iX60gensym137_]);
{
NIM_BOOL T29_;
NimStringDesc* obj;
NimStringDesc* T32_;
NimStringDesc* T33_;
T29_ = (NIM_BOOL)0;
T29_ = nosfileExists(pathX60gensym137_);
if (!T29_) goto LA30_;
f = pathX60gensym137_;
T32_ = NIM_NIL;
T32_ = nosextractFilename(f);
T33_ = NIM_NIL;
T33_ = nsuFormatSingleElem(dest, T32_);
obj = completeCfilePath__extccomp_713((*(*c).graph).config, T33_, NIM_TRUE);
docompile__pragmas_1076(c, it, f, obj, ((NimStringDesc*) NIM_NIL));
}
LA30_: ;
res += ((NI) 1);
} LA26: ;
}
}
}
LA22_: ;
popSafePoint();
}
else {
popSafePoint();
}
{
globfree((&fX60gensym137_));
if (TM__tPA3StZ6VsKyoznyrIfFxg_79.status != 0) nimLeaveFinally();
}
if (TM__tPA3StZ6VsKyoznyrIfFxg_79.status != 0) reraiseException();
}
}
goto LA9_;
LA14_: ;
{
NimStringDesc* s_2;
NimStringDesc* customArgs;
NimStringDesc* found_2;
NimStringDesc* T48_;
NimStringDesc* T49_;
NimStringDesc* obj_2;
NimStringDesc* T66_;
s_2 = ((NimStringDesc*) NIM_NIL);
customArgs = ((NimStringDesc*) NIM_NIL);
{
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 29) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 30) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 31) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 26) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 32))) goto LA39_;
s_2 = getStrLit__pragmas_1083(c, n, ((NI) 1));
{
NI T43_;
T43_ = (NI)0;
T43_ = len__ast_3198(n);
if (!(T43_ <= ((NI) 3))) goto LA44_;
customArgs = getStrLit__pragmas_1083(c, n, ((NI) 2));
}
goto LA41_;
LA44_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_81), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_82, NIM_FALSE);
}
LA41_: ;
}
goto LA37_;
LA39_: ;
{
s_2 = expectStrLit__pragmas_371(c, n);
}
LA37_: ;
T48_ = NIM_NIL;
T48_ = toFullPath__msgs_538((*(*c).graph).config, (*n).info.fileIndex);
T49_ = NIM_NIL;
T49_ = nosparentDir(T48_);
found_2 = slash___pureZos_121(T49_, s_2);
{
NIM_BOOL T52_;
T52_ = (NIM_BOOL)0;
T52_ = nosfileExists(found_2);
if (!!(T52_)) goto LA53_;
{
NIM_BOOL T57_;
T57_ = (NIM_BOOL)0;
T57_ = nosisAbsolute(s_2);
if (!T57_) goto LA58_;
found_2 = copyString(s_2);
}
goto LA55_;
LA58_: ;
{
found_2 = findFile__options_4490((*(*c).graph).config, s_2, NIM_FALSE);
{
NIM_BOOL T63_;
T63_ = (NIM_BOOL)0;
T63_ = isEmpty__options_4495(found_2);
if (!T63_) goto LA64_;
found_2 = copyString(s_2);
}
LA64_: ;
}
LA55_: ;
}
LA53_: ;
T66_ = NIM_NIL;
T66_ = completeCfilePath__extccomp_713((*(*c).graph).config, found_2, NIM_FALSE);
obj_2 = toObjFile__extccomp_718((*(*c).graph).config, T66_);
docompile__pragmas_1076(c, it, found_2, obj_2, customArgs);
}
LA9_: ;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, relativeFile__pragmas_1064)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NimStringDesc* ext) {
NimStringDesc* result;
NimStringDesc* s;
NimStringDesc* T8_;
NimStringDesc* T9_;
result = NIM_NIL;
s = expectStrLit__pragmas_371(c, n);
{
NIM_BOOL T3_;
tyTuple__7q7q3E6Oj24ZNVJb9aonhAg T5_;
T3_ = (NIM_BOOL)0;
T3_ = (((NI) 0) < (ext ? ext->Sup.len : 0));
if (!(T3_)) goto LA4_;
nimZeroMem((void*)(&T5_), sizeof(tyTuple__7q7q3E6Oj24ZNVJb9aonhAg));
nossplitFile(s, (&T5_));
T3_ = ((T5_.Field2 ? T5_.Field2->Sup.len : 0) == 0);
LA4_: ;
if (!T3_) goto LA6_;
s = nosaddFileExt(s, ext);
}
LA6_: ;
T8_ = NIM_NIL;
T8_ = toFullPath__msgs_538((*(*c).graph).config, (*n).info.fileIndex);
T9_ = NIM_NIL;
T9_ = nosparentDir(T8_);
result = slash___pureZos_121(T9_, s);
{
NIM_BOOL T12_;
T12_ = (NIM_BOOL)0;
T12_ = nosfileExists(result);
if (!!(T12_)) goto LA13_;
{
NIM_BOOL T17_;
T17_ = (NIM_BOOL)0;
T17_ = nosisAbsolute(s);
if (!T17_) goto LA18_;
result = copyString(s);
}
goto LA15_;
LA18_: ;
{
result = findFile__options_4490((*(*c).graph).config, s, NIM_FALSE);
{
NIM_BOOL T23_;
T23_ = (NIM_BOOL)0;
T23_ = isEmpty__options_4495(result);
if (!T23_) goto LA24_;
result = copyString(s);
}
LA24_: ;
}
LA15_: ;
}
LA13_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processLink__pragmas_1129)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NimStringDesc* found;
tyArray__Re75IspeoxXy2oCZHwcRrA T1_;
found = relativeFile__pragmas_1064(c, n, CC__extccomp_508[((*(*(*c).graph).config).cCompiler)- 1].Field1);
addExternalFileToLink__extccomp_754((*(*c).graph).config, found);
nimZeroMem((void*)T1_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T1_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_83));
T1_[1] = copyString(found);
recordPragma__pragmas_129(c, n, T1_, 2);
}
static N_INLINE(NIM_BOOL, isTopLevel__semdata_1091)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c) {
NIM_BOOL result;
result = (NIM_BOOL)0;
result = ((*(*c).currentScope).depthLevel <= ((NI) 2));
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processExperimental__pragmas_881)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
(*c).features = ((*c).features | 15);
}
goto LA1_;
LA6_: ;
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semConstExpr(c, (*n)._kind_6.sons->data[((NI) 1)]));
switch ((*(*n)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
TSafePoint TM__tPA3StZ6VsKyoznyrIfFxg_89;
tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ feature;
pushSafePoint(&TM__tPA3StZ6VsKyoznyrIfFxg_89);
TM__tPA3StZ6VsKyoznyrIfFxg_89.status = setjmp(TM__tPA3StZ6VsKyoznyrIfFxg_89.context);
if (TM__tPA3StZ6VsKyoznyrIfFxg_89.status == 0) {
feature = parseEnum__commands_1294((*(*n)._kind_6.sons->data[((NI) 1)])._kind_3.strVal);
(*c).features |= ((NU32)1)<<((feature) & 31);
{
if (!(feature == ((tyEnum_Feature__01UoAKYz1MxZiuG1X2VhNQ) 9))) goto LA12_;
{
NIM_BOOL T16_;
T16_ = (NIM_BOOL)0;
T16_ = isTopLevel__semdata_1091(c);
if (!!(T16_)) goto LA17_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_90), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_91, NIM_FALSE);
}
LA17_: ;
(*(*c).module).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63);
}
LA12_: ;
popSafePoint();
}
else {
popSafePoint();
if (isObj(nimBorrowCurrentException()->Sup.m_type, (&NTIvalueerror__yoNlBGx0D2tRizIdhQuENw_))) {
TM__tPA3StZ6VsKyoznyrIfFxg_89.status = 0;
liMessage__msgs_1118((*(*c).graph).config, (*(*n)._kind_6.sons->data[((NI) 1)]).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_92), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_93, NIM_FALSE);
popCurrentException();
}
}
if (TM__tPA3StZ6VsKyoznyrIfFxg_89.status != 0) reraiseException();
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_94, NIM_FALSE);
}
break;
}
}
LA1_: ;
}
static N_INLINE(tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg, pragmaToOptions__pragmas_878)(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw w) {
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg result;
nimZeroMem((void*)(&result), sizeof(tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg));
switch (w) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 155):
{
result = 3518;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 79):
{
result = 2;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 200):
{
result = 4;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 156):
{
result = 8;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 157):
{
result = 16;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 158):
{
result = 32;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 160):
{
result = 384;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 161):
{
result = 128;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 162):
{
result = 256;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 164):
{
result = 512;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 163):
{
result = 1024;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 167):
{
result = 2048;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 171):
{
result = 8192;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 172):
{
result = 16384;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 132):
{
result = 4096;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 133):
{
result = 131072;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 134):
{
result = 524288;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 141):
{
result = 1;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 77):
{
result = 18874368;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 78):
{
result = 16777216;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 290):
{
result = 1048576;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 216):
{
result = 4194304;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 168):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 169):
{
result = 8388608;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 170):
{
result = 33554432;
}
break;
default:
{
result = 0;
}
break;
}
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, onOff__pragmas_487)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg op, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions) {
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = isTurnedOn__pragmas_467(c, n);
if (!T3_) goto LA4_;
(*resOptions) = ((*resOptions) | op);
}
goto LA1_;
LA4_: ;
{
(*resOptions) = ((*resOptions) & ~ op);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA, wordToCallConv__pragmas_454)(tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw sw) {
tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA result;
result = (tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA)0;
result = ((tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA) ((NI)((NI)(((NI) 0) + sw) - ((NI) 142))));
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processCallConv__pragmas_523)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NIM_BOOL T4_;
NI T6_;
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw sw;
T3_ = (NIM_BOOL)0;
T4_ = (NIM_BOOL)0;
T4_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T4_)) goto LA5_;
T6_ = (NI)0;
T6_ = len__ast_3198(n);
T4_ = (T6_ == ((NI) 2));
LA5_: ;
T3_ = T4_;
if (!(T3_)) goto LA7_;
T3_ = ((*(*n)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA7_: ;
if (!T3_) goto LA8_;
sw = whichKeyword__idents_214((*(*n)._kind_6.sons->data[((NI) 1)])._kind_5.ident);
switch (sw) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 142) ... ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 152):
{
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** T11_;
T11_ = (tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**)0;
T11_ = X5BX5D___semdata_344((*c).optionStack->data, ((*c).optionStack ? (*c).optionStack->Sup.len : 0), ((NI) 1));
(*(*T11_)).defaultCC = wordToCallConv__pragmas_454(sw);
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_95), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_96, NIM_FALSE);
}
break;
}
}
goto LA1_;
LA8_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_95), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_97, NIM_FALSE);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, tryProcessOption__pragmas_924)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions) {
NIM_BOOL result;
{ result = (NIM_BOOL)0;
result = NIM_TRUE;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
result = NIM_FALSE;
}
goto LA1_;
LA6_: ;
{
if (!((*(*n)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 42))) goto LA9_;
processNote__pragmas_663(c, n);
}
goto LA1_;
LA9_: ;
{
if (!!(((*(*n)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2)))) goto LA12_;
result = NIM_FALSE;
}
goto LA1_;
LA12_: ;
{
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw sw;
tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg opts;
sw = whichKeyword__idents_214((*(*n)._kind_6.sons->data[((NI) 0)])._kind_5.ident);
{
if (!(sw == ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 207))) goto LA17_;
processExperimental__pragmas_881(c, n);
result = NIM_TRUE;
goto BeforeRet_;
}
LA17_: ;
opts = pragmaToOptions__pragmas_878(sw);
{
if (!!((opts == 0))) goto LA21_;
onOff__pragmas_487(c, n, opts, resOptions);
}
goto LA19_;
LA21_: ;
{
switch (sw) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 140):
{
processCallConv__pragmas_523(c, n);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 115):
{
processDynLib__pragmas_621(c, n, ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 173):
{
{
if (!!(((*(*n)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2)))) goto LA29_;
invalidPragma__pragmas_148(c, n);
}
goto LA27_;
LA29_: ;
{
NimStringDesc* T32_;
T32_ = NIM_NIL;
T32_ = nsuNormalize((*(*(*n)._kind_6.sons->data[((NI) 1)])._kind_5.ident).s);
if (eqStrings(T32_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_98))) goto LA33_;
if (eqStrings(T32_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_99))) goto LA34_;
if (eqStrings(T32_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_100))) goto LA35_;
goto LA36_;
LA33_: ;
{
(*resOptions) |= ((NU32)1)<<((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 15)) & 31);
(*resOptions) &= ~(((NU32)1) << ((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 16)) & 31));
}
goto LA37_;
LA34_: ;
{
(*resOptions) &= ~(((NU32)1) << ((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 15)) & 31));
(*resOptions) |= ((NU32)1)<<((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 16)) & 31);
}
goto LA37_;
LA35_: ;
{
(*resOptions) &= ~(((NU32)1) << ((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 15)) & 31));
(*resOptions) &= ~(((NU32)1) << ((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 16)) & 31));
}
goto LA37_;
LA36_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_101), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_102, NIM_FALSE);
}
LA37_: ;
}
LA27_: ;
}
break;
default:
{
result = NIM_FALSE;
}
break;
}
}
LA19_: ;
}
LA1_: ;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processPush__pragmas_991)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI start) {
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w* x;
{
if (!((*(*n)._kind_6.sons->data[(NI)(start - ((NI) 1))]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*(*n)._kind_6.sons->data[(NI)(start - ((NI) 1))]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*(*n)._kind_6.sons->data[(NI)(start - ((NI) 1))]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA3_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_87), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_88, NIM_FALSE);
}
LA3_: ;
x = pushOptionEntry__semdata_462(c);
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = len__ast_3198(n);
i_2 = start;
{
while (1) {
if (!(i_2 < colontmp_)) goto LA7;
i = i_2;
{
NIM_BOOL T10_;
T10_ = (NIM_BOOL)0;
T10_ = tryProcessOption__pragmas_924(c, (*n)._kind_6.sons->data[i], (&(*(*(*c).graph).config).options));
if (!!(T10_)) goto LA11_;
{
if (!((*x).otherPragmas == 0)) goto LA15_;
asgnRef((void**) (&(*x).otherPragmas), newNodeI__ast_3356(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 90), (*n).info));
}
LA15_: ;
add__ast_4797((*x).otherPragmas, (*n)._kind_6.sons->data[i]);
}
LA11_: ;
i_2 += ((NI) 1);
} LA7: ;
}
}
{
if (!!((((*(*c).optionStack->data[((NI) 0)]).options &((NU32)1<<((NU)(((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 17))&31U)))!=0))) goto LA19_;
(*(*(*c).graph).config).options &= ~(((NU32)1) << ((((tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg) 17)) & 31));
}
LA19_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, processPop__pragmas_1026)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NI T3_;
T3_ = ((*c).optionStack ? (*c).optionStack->Sup.len : 0);
if (!(T3_ <= ((NI) 1))) goto LA4_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_103), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_104, NIM_FALSE);
}
goto LA1_;
LA4_: ;
{
popOptionEntry__semdata_477(c);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ*, X5BX5D___pragmas_1308)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw** s, NI sLen_0, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x) {
tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ* result;
NI a;
NI L;
result = NIM_NIL;
a = x.a;
L = (NI)((NI)((NI)(sLen_0 - x.b) - a) + ((NI) 1));
result = (tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ*) newSeq((&NTItnodeseq__ehmV9bTklH2Gt9cXHV9c0HLeQ_), ((NI) (L)));
{
NI i;
NI i_2;
i = (NI)0;
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < L)) goto LA3;
i = i_2;
asgnRef((void**) (&result->data[i]), s[(NI)(i + a)]);
i_2 += ((NI) 1);
} LA3: ;
}
}
return result;
}
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___stdZenumutils_80)(NI a, NI b) {
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA result;
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
result.a = a;
result.b = b;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, processPragma__pragmas_1277)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI i) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* userPragma;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g T16_;
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA T17_;
tySequence__ehmV9bTklH2Gt9cXHV9c0HLeQ* T18_;
it = (*n)._kind_6.sons->data[i];
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = safeLen__ast_3191(it);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
invalidPragma__pragmas_148(c, n);
}
goto LA1_;
LA6_: ;
{
NIM_BOOL T9_;
NIM_BOOL T10_;
NI T11_;
T9_ = (NIM_BOOL)0;
T10_ = (NIM_BOOL)0;
T11_ = (NI)0;
T11_ = safeLen__ast_3191(it);
T10_ = !((T11_ == ((NI) 2)));
if (T10_) goto LA12_;
T10_ = !(((*(*it)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2)));
LA12_: ;
T9_ = T10_;
if (T9_) goto LA13_;
T9_ = !(((*(*it)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2)));
LA13_: ;
if (!T9_) goto LA14_;
invalidPragma__pragmas_148(c, n);
}
goto LA1_;
LA14_: ;
LA1_: ;
T16_ = nextSymId__ast_3132((*c).Sup.idgen);
userPragma = newSym__ast_3445(((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 18), (*(*it)._kind_6.sons->data[((NI) 1)])._kind_5.ident, T16_, ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL), (*it).info, (*(*(*c).graph).config).options);
T17_ = dotdot___stdZenumutils_80((NI)(i + ((NI) 1)), ((NI) 1));
T18_ = NIM_NIL;
T18_ = X5BX5D___pragmas_1308((*n)._kind_6.sons->data, ((*n)._kind_6.sons ? (*n)._kind_6.sons->Sup.len : 0), T17_);
asgnRef((void**) (&(*userPragma).ast), newTreeI__ast_3420(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 90), (*n).info, T18_->data, (T18_ ? T18_->Sup.len : 0)));
strTableAdd__astalgo_3332((&(*c).userPragmas), userPragma);
}
N_LIB_PRIVATE N_NIMCALL(void, processCodegenDecl__pragmas_401)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym) {
asgnRef((void**) (&(*sym).constraint), getStrLitNode__pragmas_354(c, n));
}
N_LIB_PRIVATE N_NIMCALL(void, processOption__pragmas_987)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TOption__WspMeQySXNP2XoTWR5MTgg* resOptions) {
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = tryProcessOption__pragmas_924(c, n, resOptions);
if (!!(T3_)) goto LA4_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_105), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_106, NIM_FALSE);
}
LA4_: ;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*, semAsmOrEmit__pragmas_1133)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* con, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NIM_CHAR marker) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* result;
{ result = NIM_NIL;
switch ((*(*n)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw T2_;
NimStringDesc* str;
NI a;
T2_ = (tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw)0;
{
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 89))) goto LA5_;
T2_ = ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 89);
}
goto LA3_;
LA5_: ;
{
T2_ = ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 152);
}
LA3_: ;
result = newNodeI__ast_3356(T2_, (*n).info);
str = copyString((*(*n)._kind_6.sons->data[((NI) 1)])._kind_3.strVal);
{
if (!((str ? str->Sup.len : 0) == 0)) goto LA10_;
liMessage__msgs_1118((*(*con).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_108), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_109, NIM_FALSE);
goto BeforeRet_;
}
LA10_: ;
a = ((NI) 0);
{
while (1) {
NI b;
NimStringDesc* sub;
NI c;
b = nsuFindChar(str, marker, ((NI) (a)), ((NI) 0));
{
if (!(b < ((NI) 0))) goto LA16_;
sub = substr__system_7785(str, a);
}
goto LA14_;
LA16_: ;
{
sub = substr__system_7773(str, a, (NI)(b - ((NI) 1)));
}
LA14_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T23_;
if (!!(((sub ? sub->Sup.len : 0) == 0))) goto LA21_;
T23_ = NIM_NIL;
T23_ = newStrNode__ast_3813(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20), sub);
add__ast_4797(result, T23_);
}
LA21_: ;
{
if (!(b < ((NI) 0))) goto LA26_;
goto LA12;
}
LA26_: ;
c = nsuFindChar(str, marker, ((NI) ((NI)(b + ((NI) 1)))), ((NI) 0));
{
if (!(c < ((NI) 0))) goto LA30_;
sub = substr__system_7785(str, (NI)(b + ((NI) 1)));
}
goto LA28_;
LA30_: ;
{
sub = substr__system_7773(str, (NI)(b + ((NI) 1)), (NI)(c - ((NI) 1)));
}
LA28_: ;
{
NIM_BOOL amb;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* e;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* T37_;
if (!!(((sub ? sub->Sup.len : 0) == 0))) goto LA35_;
amb = NIM_FALSE;
T37_ = NIM_NIL;
T37_ = getIdent__idents_143((*con).cache, sub);
e = searchInScopes__lookups_423(con, T37_, (&amb));
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T42_;
if (!!((e == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA40_;
(*e).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 0)) & 63);
T42_ = NIM_NIL;
T42_ = newSymNode__ast_3716(e);
add__ast_4797(result, T42_);
}
goto LA38_;
LA40_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T44_;
T44_ = NIM_NIL;
T44_ = newStrNode__ast_3813(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20), sub);
add__ast_4797(result, T44_);
}
LA38_: ;
}
goto LA33_;
LA35_: ;
{
NimStringDesc* T46_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T47_;
T46_ = NIM_NIL;
T46_ = nimCharToStr(marker);
T47_ = NIM_NIL;
T47_ = newStrNode__ast_3813(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20), T46_);
add__ast_4797(result, T47_);
}
LA33_: ;
{
if (!(c < ((NI) 0))) goto LA50_;
goto LA12;
}
LA50_: ;
a = (NI)(c + ((NI) 1));
}
} LA12: ;
}
break;
default:
{
illFormedAstLocal__semdata_1074(n, (*(*con).graph).config);
result = newNodeI__ast_3356(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 89), (*n).info);
}
break;
}
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaEmit__pragmas_1175)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_107, NIM_FALSE);
}
goto LA1_;
LA6_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n1;
n1 = (*n)._kind_6.sons->data[((NI) 1)];
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* b;
NI T13_;
if (!((*n1).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41))) goto LA11_;
T13_ = (NI)0;
T13_ = len__ast_3198(n1);
b = newNodeI__ast_3360(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41), (*n1).info, T13_);
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = len__ast_3198(n1);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA16;
i = i_2;
asgnRef((void**) (&(*b)._kind_6.sons->data[i]), (*c).semExpr(c, (*n1)._kind_6.sons->data[i], 0));
i_2 += ((NI) 1);
} LA16: ;
}
}
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), b);
}
goto LA9_;
LA11_: ;
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semConstExpr(c, n1));
switch ((*(*n)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), semAsmOrEmit__pragmas_1133(c, n, 96));
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_110, NIM_FALSE);
}
break;
}
}
LA9_: ;
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaUnroll__pragmas_1223)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
if (!((*(*c).p).nestedLoopCounter <= ((NI) 0))) goto LA3_;
invalidPragma__pragmas_148(c, n);
}
goto LA1_;
LA3_: ;
{
NIM_BOOL T6_;
NI T8_;
NI unrollFactor;
T6_ = (NIM_BOOL)0;
T6_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T6_)) goto LA7_;
T8_ = (NI)0;
T8_ = len__ast_3198(n);
T6_ = (T8_ == ((NI) 2));
LA7_: ;
if (!T6_) goto LA9_;
unrollFactor = expectIntLit__pragmas_375(c, n);
{
NIM_BOOL T13_;
T13_ = (NIM_BOOL)0;
T13_ = ltpercent___system_1005(unrollFactor, ((NI) 32));
if (!T13_) goto LA14_;
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), newIntNode__ast_3723(((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6), ((NI64) (unrollFactor))));
}
goto LA11_;
LA14_: ;
{
invalidPragma__pragmas_148(c, n);
}
LA11_: ;
}
goto LA1_;
LA9_: ;
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaLine__pragmas_1235)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* a;
T3_ = (NIM_BOOL)0;
T3_ = ((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = (T5_ == ((NI) 2));
LA4_: ;
if (!T3_) goto LA6_;
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semConstExpr(c, (*n)._kind_6.sons->data[((NI) 1)]));
a = (*n)._kind_6.sons->data[((NI) 1)];
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* x;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* y;
if (!((*a).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 37) || (*a).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 160))) goto LA10_;
x = (*a)._kind_6.sons->data[((NI) 0)];
y = (*a)._kind_6.sons->data[((NI) 1)];
{
if (!((*x).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34))) goto LA14_;
x = (*x)._kind_6.sons->data[((NI) 1)];
}
LA14_: ;
{
if (!((*y).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34))) goto LA18_;
y = (*y)._kind_6.sons->data[((NI) 1)];
}
LA18_: ;
{
if (!!(((*x).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20)))) goto LA22_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_20), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_113, NIM_FALSE);
}
goto LA20_;
LA22_: ;
{
if (!!(((*y).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 6)))) goto LA25_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_31), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_114, NIM_FALSE);
}
goto LA20_;
LA25_: ;
{
(*n).info.fileIndex = fileInfoIdx__msgs_376((*(*c).graph).config, (*x)._kind_3.strVal);
(*n).info.line = ((NU16) ((*y)._kind_1.intVal));
}
LA20_: ;
}
goto LA8_;
LA10_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_115), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_116, NIM_FALSE);
}
LA8_: ;
}
goto LA1_;
LA6_: ;
{
(*n).info = getInfoContext__msgs_516((*(*c).graph).config, ((NI) -1));
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaLockStmt__pragmas_1360)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(it);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
invalidPragma__pragmas_148(c, it);
}
goto LA1_;
LA6_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n;
n = (*it)._kind_6.sons->data[((NI) 1)];
{
if (!!(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 41)))) goto LA11_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_117), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_118, NIM_FALSE);
}
goto LA9_;
LA11_: ;
{
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = len__ast_3198(n);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA16;
i = i_2;
asgnRef((void**) (&(*n)._kind_6.sons->data[i]), (*c).semExpr(c, (*n)._kind_6.sons->data[i], 0));
i_2 += ((NI) 1);
} LA16: ;
}
}
}
LA9_: ;
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(NI16, pragmaLocks__pragmas_1388)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it) {
NI16 result;
result = (NI16)0;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(it);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
invalidPragma__pragmas_148(c, it);
}
goto LA1_;
LA6_: ;
{
switch ((*(*it)._kind_6.sons->data[((NI) 1)]).kind) {
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 20):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 21):
case ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 22):
{
{
if (!eqStrings((*(*it)._kind_6.sons->data[((NI) 1)])._kind_3.strVal, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_119))) goto LA12_;
result = ((NI16) 1001);
}
goto LA10_;
LA12_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*(*it)._kind_6.sons->data[((NI) 1)]).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_120), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_121, NIM_FALSE);
}
LA10_: ;
}
break;
default:
{
NI x;
x = expectIntLit__pragmas_375(c, it);
{
NIM_BOOL T18_;
T18_ = (NIM_BOOL)0;
T18_ = (x < ((NI) 0));
if (T18_) goto LA19_;
T18_ = (((NI) 1000) < x);
LA19_: ;
if (!T18_) goto LA20_;
liMessage__msgs_1118((*(*c).graph).config, (*(*it)._kind_6.sons->data[((NI) 1)]).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_122), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_123, NIM_FALSE);
}
goto LA16_;
LA20_: ;
{
result = ((NI16) (x));
}
LA16_: ;
}
break;
}
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*, pragmaGuard__pragmas_1492)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it, tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw kind) {
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* result;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n;
{ result = NIM_NIL;
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(it);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
invalidPragma__pragmas_148(c, it);
goto BeforeRet_;
}
LA6_: ;
n = (*it)._kind_6.sons->data[((NI) 1)];
{
if (!((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 3))) goto LA10_;
result = (*n)._kind_4.sym;
}
goto LA8_;
LA10_: ;
{
if (!(kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 19))) goto LA13_;
result = qualifiedLookUp__lookups_1233(c, n, 0);
{
NIM_BOOL T17_;
NIM_BOOL T18_;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* T23_;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g T24_;
T17_ = (NIM_BOOL)0;
T18_ = (NIM_BOOL)0;
T18_ = (result == 0);
if (T18_) goto LA19_;
T18_ = !(((768 &((NU32)1<<((NU)((*result).kind)&31U)))!=0));
LA19_: ;
T17_ = T18_;
if (T17_) goto LA20_;
T17_ = !((((*result).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 3))&63U)))!=0));
LA20_: ;
if (!T17_) goto LA21_;
T23_ = NIM_NIL;
T23_ = considerQuotedIdent__lookups_28(c, n, ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL));
T24_ = nextSymId__ast_3132((*c).Sup.idgen);
result = newSym__ast_3445(((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 0), T23_, T24_, ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL), (*n).info, (*(*(*c).graph).config).options);
}
LA21_: ;
}
goto LA8_;
LA13_: ;
{
result = qualifiedLookUp__lookups_1233(c, n, 2);
}
LA8_: ;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaProposition__pragmas_155)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_134), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_135, NIM_FALSE);
}
goto LA1_;
LA6_: ;
{
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semExpr(c, (*n)._kind_6.sons->data[((NI) 1)], 0));
}
LA1_: ;
}
static N_INLINE(void, addDeclAt__lookups_837)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* scope, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym) {
addDeclAt__lookups_815(c, scope, sym, (*sym).info);
}
static N_INLINE(void, addDecl__lookups_845)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym) {
addDeclAt__lookups_837(c, (*c).currentScope, sym);
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaEnsures__pragmas_169)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = !(((*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*n).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28)));
if (T3_) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(n);
T3_ = !((T5_ == ((NI) 2)));
LA4_: ;
if (!T3_) goto LA6_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_134), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_136, NIM_FALSE);
}
goto LA1_;
LA6_: ;
{
tyObject_TScope__1cQRXW6aAknk7ywAwjH3nw* T9_;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* o;
T9_ = NIM_NIL;
T9_ = openScope__lookups_69(c);
o = getCurrOwner__semdata_315(c);
{
NIM_BOOL T12_;
NIM_BOOL T13_;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* T18_;
tyObject_ItemId__ozxAxZLHTQ9c3akTzYvt67g T19_;
T12_ = (NIM_BOOL)0;
T13_ = (NIM_BOOL)0;
T13_ = ((520192 &((NU32)1<<((NU)((*o).kind)&31U)))!=0);
if (!(T13_)) goto LA14_;
T13_ = !(((*o).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)));
LA14_: ;
T12_ = T13_;
if (!(T12_)) goto LA15_;
T12_ = !(((*(*o).typ).sons->data[((NI) 0)] == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)));
LA15_: ;
if (!T12_) goto LA16_;
T18_ = NIM_NIL;
T18_ = getIdent__idents_143((*c).cache, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_137));
T19_ = nextSymId__ast_3132((*c).Sup.idgen);
s = newSym__ast_3445(((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 11), T18_, T19_, o, (*n).info, 0);
asgnRef((void**) (&(*s).typ), (*(*o).typ).sons->data[((NI) 0)]);
(*s).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 0)) & 63);
addDecl__lookups_845(c, s);
}
LA16_: ;
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 1)]), (*c).semExpr(c, (*n)._kind_6.sons->data[((NI) 1)], 0));
closeScope__lookups_101(c);
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, illegalCustomPragma__pragmas_151)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* s) {
NimStringDesc* T1_;
T1_ = NIM_NIL;
T1_ = rawNewString(((*(*s).name).s ? (*(*s).name).s->Sup.len : 0) + 35);
appendString(T1_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_138));
appendString(T1_, (*(*s).name).s);
appendString(T1_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_139));
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), T1_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_140, NIM_FALSE);
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, singlePragma__pragmas_1610)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, NI* i, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL comesFromPush, NIM_BOOL isStatement) {
NIM_BOOL result;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* key;
tyObject_TIdent__1LTsGP7bSxg45u9aHcxh6OA* ident;
tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* userPragma;
{ result = (NIM_BOOL)0;
it = (*n)._kind_6.sons->data[(*i)];
{
NIM_BOOL T3_;
NI T5_;
T3_ = (NIM_BOOL)0;
T3_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T3_)) goto LA4_;
T5_ = (NI)0;
T5_ = len__ast_3198(it);
T3_ = (((NI) 1) < T5_);
LA4_: ;
if (!T3_) goto LA6_;
key = (*it)._kind_6.sons->data[((NI) 0)];
}
goto LA1_;
LA6_: ;
{
key = it;
}
LA1_: ;
{
if (!((*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 42))) goto LA11_;
processNote__pragmas_663(c, it);
goto BeforeRet_;
}
goto LA9_;
LA11_: ;
{
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw T23_;
if (!((*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 61))) goto LA14_;
{
if (!comesFromPush) goto LA18_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_5), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_6, NIM_FALSE);
}
goto LA16_;
LA18_: ;
{
if (!!(isStatement)) goto LA21_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_7), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_8, NIM_FALSE);
}
goto LA16_;
LA21_: ;
LA16_: ;
T23_ = (tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw)0;
T23_ = whichPragma__trees_244((*key)._kind_6.sons->data[((NI) 1)]);
switch (T23_) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 174):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 179):
{
pragmaRaisesOrTags__pragmas_1331(c, (*key)._kind_6.sons->data[((NI) 1)]);
}
break;
default:
{
}
break;
}
goto BeforeRet_;
}
goto LA9_;
LA14_: ;
{
if (!!(((*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2) || (*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 3) || (*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 53) || (*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 57) || (*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 56)))) goto LA27_;
asgnRef((void**) (&(*n)._kind_6.sons->data[(*i)]), semCustomPragma__pragmas_1525(c, it));
goto BeforeRet_;
}
goto LA9_;
LA27_: ;
LA9_: ;
ident = considerQuotedIdent__lookups_28(c, key, ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL));
userPragma = strTableGet__astalgo_3390((*c).userPragmas, ident);
{
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA T42_;
NI T43_;
if (!!((userPragma == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA31_;
{
if (!!(((49152 & (*(*(*c).graph).config).globalOptions) == 0))) goto LA35_;
styleCheckUse__linter_192((*(*c).graph).config, (*key).info, userPragma);
}
LA35_: ;
(*c).instCounter += ((NI) 1);
{
NimStringDesc* T41_;
if (!(((NI) 100) < (*c).instCounter)) goto LA39_;
T41_ = NIM_NIL;
T41_ = rawNewString(((*(*userPragma).name).s ? (*(*userPragma).name).s->Sup.len : 0) + 22);
appendString(T41_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_13));
appendString(T41_, (*(*userPragma).name).s);
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), T41_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 2), TM__tPA3StZ6VsKyoznyrIfFxg_14, NIM_FALSE);
}
LA39_: ;
pragma__pragmas_123(c, sym, (*userPragma).ast, validPragmas, isStatement);
T42_ = dotdot___pureZunicode_840((*i), (*i));
X5BX5Deq___pragmas_1672((&(*n)._kind_6.sons), T42_, (*(*userPragma).ast)._kind_6.sons->data, ((*(*userPragma).ast)._kind_6.sons ? (*(*userPragma).ast)._kind_6.sons->Sup.len : 0));
T43_ = (NI)0;
T43_ = len__ast_3198((*userPragma).ast);
(*i) += (NI)(T43_ - ((NI) 1));
(*c).instCounter -= ((NI) 1);
}
goto LA29_;
LA31_: ;
{
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw k;
k = whichKeyword__idents_214(ident);
{
if (!((validPragmas[(NU)(k)>>3] &(1U<<((NU)(k)&7U)))!=0)) goto LA47_;
{
if (!!(((49152 & (*(*(*c).graph).config).globalOptions) == 0))) goto LA51_;
checkPragmaUse__linter_240((*(*c).graph).config, (*key).info, k, (*ident).s);
}
LA51_: ;
switch (k) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 98):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 99):
{
NimStringDesc* T54_;
T54_ = NIM_NIL;
T54_ = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
makeExternExport__pragmas_272(c, sym, T54_, (*it).info);
{
if (!(k == ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 99))) goto LA57_;
{
NimStringDesc* T63_;
if (!!(((*(*(*c).graph).config).backend == ((tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g) 2)))) goto LA61_;
T63_ = NIM_NIL;
T63_ = rawNewString((reprEnum((NI)(*(*(*c).graph).config).backend, (&NTItbackend__4OBsgZ9cscH2JLUE5Wcz01g_)) ? reprEnum((NI)(*(*(*c).graph).config).backend, (&NTItbackend__4OBsgZ9cscH2JLUE5Wcz01g_))->Sup.len : 0) + 39);
appendString(T63_, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_23));
appendString(T63_, reprEnum((NI)(*(*(*c).graph).config).backend, (&NTItbackend__4OBsgZ9cscH2JLUE5Wcz01g_)));
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), T63_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_24, NIM_FALSE);
}
goto LA59_;
LA61_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 8)) & 63);
}
LA59_: ;
}
LA57_: ;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 0)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 96):
{
NimStringDesc* name;
tyArray__Re75IspeoxXy2oCZHwcRrA T66_;
name = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
cppDefine__options_2499((*(*c).graph).config, name);
nimZeroMem((void*)T66_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T66_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_25));
T66_[1] = copyString(name);
recordPragma__pragmas_129(c, it, T66_, 2);
makeExternImport__pragmas_259(c, sym, name, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 95):
{
NimStringDesc* name_2;
tyArray__Re75IspeoxXy2oCZHwcRrA T68_;
name_2 = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
cppDefine__options_2499((*(*c).graph).config, name_2);
nimZeroMem((void*)T68_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T68_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_25));
T68_[1] = copyString(name_2);
recordPragma__pragmas_129(c, it, T68_, 2);
processImportCompilerProc__pragmas_281(c, sym, name_2, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 238):
{
NimStringDesc* T70_;
T70_ = NIM_NIL;
T70_ = expectStrLit__pragmas_371(c, it);
setExternName__pragmas_238(c, sym, T70_, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 211):
{
{
if (!((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 18))) goto LA74_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 11)) & 63);
}
goto LA72_;
LA74_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA72_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 92):
{
NimStringDesc* T78_;
T78_ = NIM_NIL;
T78_ = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
processImportCpp__pragmas_298(c, sym, T78_, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 93):
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 27)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 97):
{
NimStringDesc* name_3;
{
if (!!(((*(*(*c).graph).config).backend == ((tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g) 3)))) goto LA83_;
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_26), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_27, NIM_FALSE);
}
LA83_: ;
name_3 = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 32)) & 63);
{
NIM_BOOL T87_;
NIM_BOOL T89_;
T87_ = (NIM_BOOL)0;
T87_ = ((520192 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
if (!(T87_)) goto LA88_;
T89_ = (NIM_BOOL)0;
T89_ = contains__pureZstrutils_1635(name_3, TM__tPA3StZ6VsKyoznyrIfFxg_28);
T87_ = !(T89_);
LA88_: ;
if (!T87_) goto LA90_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_29), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_30, NIM_FALSE);
}
LA90_: ;
setExternName__pragmas_238(c, sym, name_3, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 94):
{
NimStringDesc* T93_;
T93_ = NIM_NIL;
T93_ = getOptionalStr__pragmas_392(c, it, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_15));
processImportObjC__pragmas_328(c, sym, T93_, (*it).info);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 177):
{
NI size;
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA97_;
invalidPragma__pragmas_148(c, it);
}
LA97_: ;
size = expectIntLit__pragmas_375(c, it);
switch (size) {
case ((NI) 1):
case ((NI) 2):
case ((NI) 4):
{
(*(*sym).typ).size = ((NI64) (size));
(*(*sym).typ).align = ((NI16) (size));
}
break;
case ((NI) 8):
{
(*(*sym).typ).size = IL64(8);
(*(*sym).typ).align = floatInt64Align__options_4700((*(*c).graph).config);
}
break;
default:
{
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_34), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_35, NIM_FALSE);
}
break;
}
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 104):
{
NI alignment;
alignment = expectIntLit__pragmas_375(c, it);
{
NIM_BOOL T105_;
T105_ = (NIM_BOOL)0;
T105_ = isPowerOfTwo__pureZmath_173(alignment);
if (!(T105_)) goto LA106_;
T105_ = (((NI) 0) < alignment);
LA106_: ;
if (!T105_) goto LA107_;
(*sym)._kind_2.alignment = (((*sym)._kind_2.alignment >= alignment) ? (*sym)._kind_2.alignment : alignment);
}
goto LA103_;
LA107_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_36), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_37, NIM_FALSE);
}
LA103_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 105):
{
noVal__pragmas_1213(c, it);
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 3)) & 15);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 106):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 215):
{
noVal__pragmas_1213(c, it);
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA114_;
{
NIM_BOOL T118_;
T118_ = (NIM_BOOL)0;
T118_ = (k == ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 106));
if (!(T118_)) goto LA119_;
T118_ = ((520192 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
LA119_: ;
if (!T118_) goto LA120_;
invalidPragma__pragmas_148(c, it);
}
goto LA116_;
LA120_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 11)) & 63);
}
LA116_: ;
}
LA114_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 273):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 9)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 83):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 41)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 252):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 10)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 84):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 46)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 85):
{
processEffectsOf__pragmas_1570(c, it, sym);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 213):
{
noVal__pragmas_1213(c, it);
(*sym).flags = ((*sym).flags | 67108872);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 185):
{
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 188):
{
pragmaNoForward__pragmas_502(c, it, ((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 10));
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 189):
{
pragmaNoForward__pragmas_502(c, it, ((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4));
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 74):
{
processMagic__pragmas_405(c, it, sym);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 193):
{
noVal__pragmas_1213(c, it);
{
if (!comesFromPush) goto LA136_;
{
if (!((12288 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0)) goto LA140_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 28)) & 63);
}
LA140_: ;
}
goto LA134_;
LA136_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 28)) & 63);
}
LA134_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 217):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 3)) & 63);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 11)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 113):
{
noVal__pragmas_1213(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 88):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 29)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 108):
{
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* lib;
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T147_;
T147_ = NIM_NIL;
T147_ = getStrLitNode__pragmas_354(c, it);
lib = getLib__pragmas_544(c, ((tyEnum_TLibKind__9b8v60kso59bBaw9cp8B9a9apKQ) 0), T147_);
addToLib__semdata_730(lib, sym);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6)) & 63);
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 6)) & 15);
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 3)) & 15);
{
if (!((*sym).loc.r == ((tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*) NIM_NIL))) goto LA150_;
asgnRef((void**) (&(*sym).loc.r), rope__ropes_109((*(*sym).name).s));
}
LA150_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 109):
{
noVal__pragmas_1213(c, it);
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA155_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 12)) & 63);
{
if (!!(((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)))) goto LA159_;
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 1)) & 63);
}
LA159_: ;
}
LA155_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 107):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 13)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 111):
{
noVal__pragmas_1213(c, it);
{
if (!!(((*(*(*c).graph).config).exc == ((tyEnum_ExceptionSystem__1mkAogyaDAT7g9cQjzsgKLQ) 4)))) goto LA165_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 16)) & 63);
}
LA165_: ;
{
if (!!(((*(*sym).typ).sons->data[((NI) 0)] == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)))) goto LA169_;
liMessage__msgs_1118((*(*c).graph).config, (*(*(*(*sym).ast)._kind_6.sons->data[((NI) 3)])._kind_6.sons->data[((NI) 0)]).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_55), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_56, NIM_FALSE);
}
LA169_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 191):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 39)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 112):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 5)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 115):
{
processDynLib__pragmas_621(c, it, sym);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 116):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 117):
{
tyArray__Re75IspeoxXy2oCZHwcRrA T175_;
noVal__pragmas_1213(c, it);
cppDefine__options_2499((*(*c).graph).config, (*(*sym).name).s);
nimZeroMem((void*)T175_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T175_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_25));
T175_[1] = copyString((*(*sym).name).s);
recordPragma__pragmas_129(c, it, T175_, 2);
{
if (!!((((*sym).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 2))&63U)))!=0))) goto LA178_;
markCompilerProc__pragmas_1425(c, sym);
}
LA178_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 165):
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 38)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 118):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 19)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 223):
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 23)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 138):
{
{
NIM_BOOL T186_;
T186_ = (NIM_BOOL)0;
T186_ = !((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)));
if (!(T186_)) goto LA187_;
T186_ = ((521088 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
LA187_: ;
if (!T186_) goto LA188_;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T194_;
if (!((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA192_;
T194_ = NIM_NIL;
T194_ = getStrLitNode__pragmas_354(c, it);
(void)(T194_);
}
LA192_: ;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 22)) & 63);
}
goto LA184_;
LA188_: ;
{
NIM_BOOL T196_;
T196_ = (NIM_BOOL)0;
T196_ = !((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)));
if (!(T196_)) goto LA197_;
T196_ = !(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 6)));
LA197_: ;
if (!T196_) goto LA198_;
{
if (!((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA202_;
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_60), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_61, NIM_FALSE);
}
LA202_: ;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 22)) & 63);
}
goto LA184_;
LA198_: ;
{
if (!((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA205_;
deprecatedStmt__pragmas_1444(c, it);
}
goto LA184_;
LA205_: ;
{
(*(*c).module).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 22)) & 63);
}
LA184_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 139):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA211_;
invalidPragma__pragmas_148(c, it);
}
goto LA209_;
LA211_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 0)) & 63);
}
LA209_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 198):
{
{
if (!((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7))) goto LA217_;
typeBorrow__pragmas_1404(c, sym, it);
}
goto LA215_;
LA217_: ;
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 31)) & 63);
}
LA215_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 76):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA223_;
invalidPragma__pragmas_148(c, it);
}
goto LA221_;
LA223_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 2)) & 63);
}
LA221_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 212):
{
noVal__pragmas_1213(c, it);
{
NIM_BOOL T229_;
T229_ = (NIM_BOOL)0;
T229_ = ((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
if (T229_) goto LA230_;
T229_ = (((*(*sym).typ).flags &((NU64)1<<((NU)(((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 2))&63U)))!=0);
LA230_: ;
if (!T229_) goto LA231_;
invalidPragma__pragmas_148(c, it);
}
goto LA227_;
LA231_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 3)) & 63);
}
LA227_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 187):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA237_;
invalidPragma__pragmas_148(c, it);
}
goto LA235_;
LA237_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63);
}
LA235_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 202):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA243_;
invalidPragma__pragmas_148(c, it);
}
goto LA241_;
LA243_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 39)) & 63);
}
LA241_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 203):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA249_;
invalidPragma__pragmas_148(c, it);
}
goto LA247_;
LA249_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 6)) & 63);
}
LA247_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 75):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 26)) & 63);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 19)) & 63);
{
if (!!(((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)))) goto LA255_;
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 7)) & 63);
{
if (!((*(*sym).typ).callConv == ((tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA) 9))) goto LA259_;
(*(*sym).typ).callConv = ((tyEnum_TCallingConvention__yjAJ8w0h1PBaSwSGJ3P7IA) 0);
}
LA259_: ;
}
LA255_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 110):
{
noVal__pragmas_1213(c, it);
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA264_;
{
if (!!(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7)))) goto LA268_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 26)) & 63);
}
LA268_: ;
{
if (!!(((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)))) goto LA272_;
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 7)) & 63);
}
goto LA270_;
LA272_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA270_: ;
}
goto LA262_;
LA264_: ;
{
}
LA262_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 269):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA279_;
invalidPragma__pragmas_148(c, it);
}
goto LA277_;
LA279_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 23)) & 63);
}
LA277_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 124):
{
NimStringDesc* s;
tyArray__Re75IspeoxXy2oCZHwcRrA T283_;
s = expectStrLit__pragmas_371(c, it);
nimZeroMem((void*)T283_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T283_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_70));
T283_[1] = copyString(s);
recordPragma__pragmas_129(c, it, T283_, 2);
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 98), s, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_71, NIM_FALSE);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 123):
{
NimStringDesc* s_2;
tyArray__Re75IspeoxXy2oCZHwcRrA T285_;
s_2 = expectStrLit__pragmas_371(c, it);
nimZeroMem((void*)T285_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T285_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_72));
T285_[1] = copyString(s_2);
recordPragma__pragmas_129(c, it, T285_, 2);
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 67), s_2, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_73, NIM_FALSE);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 122):
{
{
NIM_BOOL T289_;
NIM_BOOL T290_;
NIM_BOOL T292_;
T289_ = (NIM_BOOL)0;
T290_ = (NIM_BOOL)0;
T290_ = !((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)));
if (!(T290_)) goto LA291_;
T292_ = (NIM_BOOL)0;
T292_ = isRoutine__ast_4676(sym);
if (T292_) goto LA293_;
T292_ = ((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7));
LA293_: ;
T290_ = T292_;
LA291_: ;
T289_ = T290_;
if (!(T289_)) goto LA294_;
T289_ = !(isStatement);
LA294_: ;
if (!T289_) goto LA295_;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* T301_;
if (!((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28))) goto LA299_;
T301_ = NIM_NIL;
T301_ = getStrLitNode__pragmas_354(c, it);
(void)(T301_);
}
LA299_: ;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 24)) & 63);
(*sym).flags &= ~(((NU64)1) << ((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 4)) & 63));
}
goto LA287_;
LA295_: ;
{
NimStringDesc* s_3;
tyArray__Re75IspeoxXy2oCZHwcRrA T303_;
s_3 = expectStrLit__pragmas_371(c, it);
nimZeroMem((void*)T303_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T303_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_74));
T303_[1] = copyString(s_3);
recordPragma__pragmas_129(c, it, T303_, 2);
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 15), s_3, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_75, NIM_FALSE);
}
LA287_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 121):
{
NimStringDesc* T305_;
T305_ = NIM_NIL;
T305_ = expectStrLit__pragmas_371(c, it);
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 1), T305_, ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 1), TM__tPA3StZ6VsKyoznyrIfFxg_76, NIM_FALSE);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 130):
{
processDefine__pragmas_1032(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 131):
{
processUndef__pragmas_1048(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 136):
{
processCompile__pragmas_1073(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 135):
{
processLink__pragmas_1129(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 196):
{
NimStringDesc* s_4;
tyArray__Re75IspeoxXy2oCZHwcRrA T311_;
s_4 = expectStrLit__pragmas_371(c, it);
addLinkOption__extccomp_690((*(*c).graph).config, s_4);
nimZeroMem((void*)T311_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T311_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_84));
T311_[1] = copyString(s_4);
recordPragma__pragmas_129(c, it, T311_, 2);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 195):
{
NimStringDesc* s_5;
tyArray__Re75IspeoxXy2oCZHwcRrA T313_;
s_5 = expectStrLit__pragmas_371(c, it);
addCompileOption__extccomp_693((*(*c).graph).config, s_5);
nimZeroMem((void*)T313_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T313_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_85));
T313_[1] = copyString(s_5);
recordPragma__pragmas_129(c, it, T313_, 2);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 197):
{
NimStringDesc* s_6;
NimStringDesc* T315_;
tyArray__Re75IspeoxXy2oCZHwcRrA T316_;
s_6 = expectStrLit__pragmas_371(c, it);
T315_ = NIM_NIL;
T315_ = toFullPathConsiderDirty__msgs_571((*(*c).graph).config, (*sym).info.fileIndex);
addLocalCompileOption__extccomp_738((*(*c).graph).config, s_6, T315_);
nimZeroMem((void*)T316_, sizeof(tyArray__Re75IspeoxXy2oCZHwcRrA));
T316_[0] = copyString(((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_86));
T316_[1] = copyString(s_6);
recordPragma__pragmas_129(c, it, T316_, 2);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 128):
{
processPush__pragmas_991(c, n, (NI)((*i) + ((NI) 1)));
result = NIM_TRUE;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 129):
{
processPop__pragmas_1026(c, it);
result = NIM_TRUE;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 192):
{
{
NIM_BOOL T322_;
T322_ = (NIM_BOOL)0;
T322_ = !((sym == 0));
if (!(T322_)) goto LA323_;
T322_ = ((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 18));
LA323_: ;
if (!T322_) goto LA324_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 10)) & 63);
}
goto LA320_;
LA324_: ;
{
processPragma__pragmas_1277(c, n, (*i));
result = NIM_TRUE;
}
LA320_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 199):
{
noVal__pragmas_1213(c, it);
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA330_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 34)) & 63);
}
LA330_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 194):
{
noVal__pragmas_1213(c, it);
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA335_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 14)) & 63);
}
LA335_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 218):
{
processCodegenDecl__pragmas_401(c, it, sym);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 155):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 79):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 200):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 156):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 157):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 158):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 159):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 167):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 171):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 172):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 132):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 173):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 164):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 163):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 140):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 141):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 77):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 160):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 161):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 162):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 168):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 169):
{
processOption__pragmas_987(c, it, (&(*(*(*c).graph).config).options));
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 133):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 134):
{
{
if (!((86016 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0)) goto LA342_;
processOption__pragmas_987(c, it, (&(*sym).options));
}
goto LA340_;
LA342_: ;
{
processOption__pragmas_987(c, it, (&(*(*(*c).graph).config).options));
}
LA340_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 142) ... ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 152):
{
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA348_;
invalidPragma__pragmas_148(c, it);
}
goto LA346_;
LA348_: ;
{
(*(*sym).typ).callConv = wordToCallConv__pragmas_454(k);
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 42)) & 63);
}
LA346_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 214):
{
pragmaEmit__pragmas_1175(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 204):
{
pragmaUnroll__pragmas_1223(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 205):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 206):
{
noVal__pragmas_1213(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 178):
{
noVal__pragmas_1213(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 101):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA358_;
invalidPragma__pragmas_148(c, it);
}
goto LA356_;
LA358_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 40)) & 63);
}
LA356_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 102):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA364_;
invalidPragma__pragmas_148(c, it);
}
goto LA362_;
LA364_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 41)) & 63);
}
LA362_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 219):
{
noVal__pragmas_1213(c, it);
{
NIM_BOOL T370_;
T370_ = (NIM_BOOL)0;
T370_ = ((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
if (T370_) goto LA371_;
T370_ = !(((*(*sym).typ).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 16) || (*(*sym).typ).kind == ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 49)));
LA371_: ;
if (!T370_) goto LA372_;
invalidPragma__pragmas_148(c, it);
}
goto LA368_;
LA372_: ;
{
(*(*sym).typ).kind = ((tyEnum_TTypeKind__9a3YiReNVD0IJHWFKgXRe9ag) 49);
}
LA368_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 268):
{
{
if (!((*(*(*c).graph).config).backend == ((tyEnum_TBackend__4OBsgZ9cscH2JLUE5Wcz01g) 3))) goto LA378_;
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_111), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_112, NIM_FALSE);
}
goto LA376_;
LA378_: ;
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA383_;
invalidPragma__pragmas_148(c, it);
}
goto LA381_;
LA383_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 1)) & 63);
}
LA381_: ;
}
LA376_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 103):
{
noVal__pragmas_1213(c, it);
{
if (!((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 19))) goto LA389_;
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 21)) & 63);
}
goto LA387_;
LA389_: ;
{
if (!!(((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL)))) goto LA392_;
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 19)) & 63);
}
goto LA387_;
LA392_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA387_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 290):
{
noVal__pragmas_1213(c, it);
{
NIM_BOOL T398_;
T398_ = (NIM_BOOL)0;
T398_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T398_) goto LA399_;
T398_ = ((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
LA399_: ;
if (!T398_) goto LA400_;
processOption__pragmas_987(c, it, (&(*(*(*c).graph).config).options));
}
goto LA396_;
LA400_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 14)) & 63);
}
LA396_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 289):
{
noVal__pragmas_1213(c, it);
{
NIM_BOOL T406_;
T406_ = (NIM_BOOL)0;
T406_ = !(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7)));
if (T406_) goto LA407_;
T406_ = ((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
LA407_: ;
if (!T406_) goto LA408_;
invalidPragma__pragmas_148(c, it);
}
goto LA404_;
LA408_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 13)) & 63);
}
LA404_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 222):
{
noVal__pragmas_1213(c, it);
{
NIM_BOOL T414_;
T414_ = (NIM_BOOL)0;
T414_ = !(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 7)));
if (T414_) goto LA415_;
T414_ = ((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL));
LA415_: ;
if (!T414_) goto LA416_;
invalidPragma__pragmas_148(c, it);
}
goto LA412_;
LA416_: ;
{
(*(*sym).typ).flags |= ((NU64)1)<<((((tyEnum_TTypeFlag__x2m5g1NpbmDig4wLT3Ylhw) 16)) & 63);
}
LA412_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 210):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 209):
{
noVal__pragmas_1213(c, it);
{
if (!(sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL))) goto LA422_;
invalidPragma__pragmas_148(c, it);
}
LA422_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 127):
{
pragmaLine__pragmas_1235(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 174):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 179):
{
pragmaRaisesOrTags__pragmas_1331(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 221):
{
{
if (!(sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL))) goto LA429_;
pragmaLockStmt__pragmas_1360(c, it);
}
goto LA427_;
LA429_: ;
{
if (!((*sym).typ == ((tyObject_TType__facALICuu8zUj0hjvbTLFg*) NIM_NIL))) goto LA432_;
invalidPragma__pragmas_148(c, it);
}
goto LA427_;
LA432_: ;
{
(*(*sym).typ).lockLevel = pragmaLocks__pragmas_1388(c, it);
}
LA427_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 292):
{
{
NIM_BOOL T438_;
T438_ = (NIM_BOOL)0;
T438_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T438_) goto LA439_;
T438_ = !(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 19)));
LA439_: ;
if (!T438_) goto LA440_;
invalidPragma__pragmas_148(c, it);
}
goto LA436_;
LA440_: ;
{
(*sym)._kind_2.bitsize = expectIntLit__pragmas_375(c, it);
{
if (!((*sym)._kind_2.bitsize <= ((NI) 0))) goto LA445_;
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_124), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_125, NIM_FALSE);
}
LA445_: ;
}
LA436_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 220):
{
{
NIM_BOOL T450_;
T450_ = (NIM_BOOL)0;
T450_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T450_) goto LA451_;
T450_ = !(((525056 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0));
LA451_: ;
if (!T450_) goto LA452_;
invalidPragma__pragmas_148(c, it);
}
goto LA448_;
LA452_: ;
{
asgnRef((void**) (&(*sym)._kind_2.guard), pragmaGuard__pragmas_1492(c, it, (*sym).kind));
}
LA448_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 242):
{
{
NIM_BOOL T458_;
T458_ = (NIM_BOOL)0;
T458_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T458_) goto LA459_;
T458_ = !(((768 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0));
LA459_: ;
if (!T458_) goto LA460_;
invalidPragma__pragmas_148(c, it);
}
goto LA456_;
LA460_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 35)) & 63);
}
LA456_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 100):
{
{
if (!(sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL))) goto LA466_;
invalidPragma__pragmas_148(c, it);
}
goto LA464_;
LA466_: ;
{
registerNimScriptSymbol__magicsys_157((*c).graph, sym);
}
LA464_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 207):
{
{
NIM_BOOL T472_;
T472_ = (NIM_BOOL)0;
T472_ = isTopLevel__semdata_1091(c);
if (!!(T472_)) goto LA473_;
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_126), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_127, NIM_FALSE);
}
LA473_: ;
processExperimental__pragmas_881(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 261):
{
{
NIM_BOOL T478_;
NI T480_;
T478_ = (NIM_BOOL)0;
T478_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T478_)) goto LA479_;
T480_ = (NI)0;
T480_ = len__ast_3198(it);
T478_ = (T480_ == ((NI) 2));
LA479_: ;
if (!T478_) goto LA481_;
asgnRef((void**) (&(*c).selfName), considerQuotedIdent__lookups_28(c, (*it)._kind_6.sons->data[((NI) 1)], ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL)));
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 20), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_128), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_129, NIM_FALSE);
}
goto LA476_;
LA481_: ;
{
NIM_BOOL T484_;
NI T486_;
T484_ = (NIM_BOOL)0;
T484_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
if (T484_) goto LA485_;
T486_ = (NI)0;
T486_ = len__ast_3198(it);
T484_ = (T486_ == ((NI) 1));
LA485_: ;
if (!T484_) goto LA487_;
asgnRef((void**) (&(*c).selfName), getIdent__idents_143((*c).cache, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_130)));
liMessage__msgs_1118((*(*c).graph).config, (*n).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 20), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_128), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_131, NIM_FALSE);
}
goto LA476_;
LA487_: ;
{
liMessage__msgs_1118((*(*c).graph).config, (*it).info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_132), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_133, NIM_FALSE);
}
LA476_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 190):
{
noVal__pragmas_1213(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 119):
{
noVal__pragmas_1213(c, it);
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 20)) & 63);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 80):
{
(*sym).magic = ((tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg) 264);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 81):
{
(*sym).magic = ((tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg) 265);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 82):
{
(*sym).magic = ((tyEnum_TMagic__shZhZOdbVC5nnFvcXQAImg) 266);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 120):
{
noVal__pragmas_1213(c, it);
{
if (!(sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL))) goto LA498_;
invalidPragma__pragmas_148(c, it);
}
goto LA496_;
LA498_: ;
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 0)) & 63);
}
LA496_: ;
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 224):
{
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 180):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 182):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 183):
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 184):
{
pragmaProposition__pragmas_155(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 181):
{
pragmaEnsures__pragmas_169(c, it);
}
break;
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 225):
{
(*sym).flags |= ((NU64)1)<<((((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 43)) & 63);
}
break;
default:
{
invalidPragma__pragmas_148(c, it);
}
break;
}
}
goto LA45_;
LA47_: ;
{
NIM_BOOL T507_;
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw T509_;
T507_ = (NIM_BOOL)0;
T507_ = comesFromPush;
if (!(T507_)) goto LA508_;
T509_ = (tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw)0;
T509_ = whichKeyword__idents_214(ident);
T507_ = !((T509_ == ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 0)));
LA508_: ;
if (!T507_) goto LA510_;
}
goto LA45_;
LA510_: ;
{
{
NIM_BOOL T515_;
T515_ = (NIM_BOOL)0;
T515_ = (sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL));
if (T515_) goto LA516_;
T515_ = ((619400 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
LA516_: ;
if (!T515_) goto LA517_;
asgnRef((void**) (&(*n)._kind_6.sons->data[(*i)]), semCustomPragma__pragmas_1525(c, it));
}
goto LA513_;
LA517_: ;
{
if (!!((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)))) goto LA520_;
illegalCustomPragma__pragmas_151(c, it, sym);
}
goto LA513_;
LA520_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA513_: ;
}
LA45_: ;
}
LA29_: ;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaRec__pragmas_2524)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL isStatement) {
NI i;
{ {
if (!(n == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL))) goto LA3_;
goto BeforeRet_;
}
LA3_: ;
i = ((NI) 0);
{
while (1) {
NI T7_;
T7_ = (NI)0;
T7_ = len__ast_3198(n);
if (!(i < T7_)) goto LA6;
{
NIM_BOOL T10_;
T10_ = (NIM_BOOL)0;
T10_ = singlePragma__pragmas_1610(c, sym, n, (&i), validPragmas, NIM_FALSE, isStatement);
if (!T10_) goto LA11_;
goto LA5;
}
LA11_: ;
i += ((NI) 1);
} LA6: ;
} LA5: ;
}BeforeRet_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, overwriteLineInfo__pragmas_2369)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info) {
(*n).info = info;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(n);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA3;
i = i_2;
overwriteLineInfo__pragmas_2369((*n)._kind_6.sons->data[i], info);
i_2 += ((NI) 1);
} LA3: ;
}
}
}
N_LIB_PRIVATE N_NIMCALL(void, mergePragmas__pragmas_2378)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* pragmas) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* pragmas_2;
pragmas_2 = copyTree__ast_4431(pragmas);
overwriteLineInfo__pragmas_2369(pragmas_2, (*n).info);
{
if (!((*(*n)._kind_6.sons->data[((NI) 4)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 1))) goto LA3_;
asgnRef((void**) (&(*n)._kind_6.sons->data[((NI) 4)]), pragmas_2);
}
goto LA1_;
LA3_: ;
{
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* p;
p = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(pragmas_2);
i_2 = ((NI) 0);
{
while (1) {
if (!(i_2 < colontmp_)) goto LA9;
i = i_2;
p = (*pragmas_2)._kind_6.sons->data[i];
add__ast_4797((*n)._kind_6.sons->data[((NI) 4)], p);
i_2 += ((NI) 1);
} LA9: ;
}
}
}
}
LA1_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, implicitPragmas__pragmas_2394)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TLineInfo__WGx4rAexNXnczy1Avn646Q info, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas) {
{
NIM_BOOL T3_;
tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA* lib;
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** T37_;
T3_ = (NIM_BOOL)0;
T3_ = !((sym == ((tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ*) NIM_NIL)));
if (!(T3_)) goto LA4_;
T3_ = !(((*sym).kind == ((tyEnum_TSymKind__cNCW9acsSznmEccl1fgQwkw) 6)));
LA4_: ;
if (!T3_) goto LA5_;
{
tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w** it;
NI i;
NI L;
NI T8_;
it = (tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**)0;
i = ((NI) 0);
T8_ = ((*c).optionStack ? (*c).optionStack->Sup.len : 0);
L = T8_;
{
while (1) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* o;
if (!(i < L)) goto LA10;
it = &(*c).optionStack->data[i];
o = (*(*it)).otherPragmas;
{
NIM_BOOL T13_;
NI i_2;
T13_ = (NIM_BOOL)0;
T13_ = !((o == 0));
if (!(T13_)) goto LA14_;
T13_ = !((((*sym).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 2))&63U)))!=0));
LA14_: ;
if (!T13_) goto LA15_;
pushInfoContext__msgs_490((*(*c).graph).config, info, ((NimStringDesc*) NIM_NIL));
i_2 = ((NI) 0);
{
while (1) {
NI T19_;
T19_ = (NI)0;
T19_ = len__ast_3198(o);
if (!(i_2 < T19_)) goto LA18;
{
NIM_BOOL T22_;
T22_ = (NIM_BOOL)0;
T22_ = singlePragma__pragmas_1610(c, sym, o, (&i_2), validPragmas, NIM_TRUE, NIM_FALSE);
if (!T22_) goto LA23_;
internalErrorImpl__msgs_1431((*(*c).graph).config, info, ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_141), TM__tPA3StZ6VsKyoznyrIfFxg_142);
}
LA23_: ;
i_2 += ((NI) 1);
} LA18: ;
}
popInfoContext__msgs_507((*(*c).graph).config);
{
NIM_BOOL T27_;
T27_ = (NIM_BOOL)0;
T27_ = ((520192 &((NU32)1<<((NU)((*sym).kind)&31U)))!=0);
if (!(T27_)) goto LA28_;
T27_ = !(((*sym).ast == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL)));
LA28_: ;
if (!T27_) goto LA29_;
mergePragmas__pragmas_2378((*sym).ast, o);
}
LA29_: ;
}
LA15_: ;
i += ((NI) 1);
} LA10: ;
}
}
{
NIM_BOOL T33_;
T33_ = (NIM_BOOL)0;
T33_ = (((*sym).loc.flags &((NU16)1<<((NU)(((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 5))&15U)))!=0);
if (!(T33_)) goto LA34_;
T33_ = !((((*sym).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 7))&63U)))!=0));
LA34_: ;
if (!T33_) goto LA35_;
liMessage__msgs_1118((*(*c).graph).config, info, ((tyEnum_TMsgKind__29cbg2fC1z5iM1PAI28kR5w) 14), ((NimStringDesc*) &TM__tPA3StZ6VsKyoznyrIfFxg_143), ((tyEnum_TErrorHandling__q4fXoCN3Xdcm6SS9cUkWkWw) 0), TM__tPA3StZ6VsKyoznyrIfFxg_144, NIM_FALSE);
}
LA35_: ;
T37_ = (tyObject_TOptionEntry__H9ac5KbrDJVwT1zH5O83r7w**)0;
T37_ = X5BX5D___semdata_344((*c).optionStack->data, ((*c).optionStack ? (*c).optionStack->Sup.len : 0), ((NI) 1));
lib = (*(*T37_)).dynlib;
{
NIM_BOOL T40_;
NIM_BOOL T41_;
T40_ = (NIM_BOOL)0;
T41_ = (NIM_BOOL)0;
T41_ = ((80 & (*sym).loc.flags) == 0);
if (!(T41_)) goto LA42_;
T41_ = (((*sym).flags &((NU64)1<<((NU)(((tyEnum_TSymFlag__K9ay6LWMat9bUiT9bIbMxpDHw) 6))&63U)))!=0);
LA42_: ;
T40_ = T41_;
if (!(T40_)) goto LA43_;
T40_ = !((lib == ((tyObject_TLib__NBMxlJ6g3utqUlplqTTHkA*) NIM_NIL)));
LA43_: ;
if (!T40_) goto LA44_;
(*sym).loc.flags |= ((NU16)1)<<((((tyEnum_TLocFlag__o2bqJgR4ceIupnUSpxiudA) 4)) & 15);
addToLib__semdata_730(lib, sym);
{
if (!((*sym).loc.r == ((tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*) NIM_NIL))) goto LA48_;
asgnRef((void**) (&(*sym).loc.r), rope__ropes_109((*(*sym).name).s));
}
LA48_: ;
}
LA44_: ;
}
LA5_: ;
}
N_LIB_PRIVATE N_NIMCALL(void, pragma__pragmas_123)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL isStatement) {
{ {
if (!(n == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL))) goto LA3_;
goto BeforeRet_;
}
LA3_: ;
pragmaRec__pragmas_2524(c, sym, n, validPragmas, isStatement);
implicitPragmas__pragmas_2394(c, sym, (*n).info, validPragmas);
}BeforeRet_: ;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, hasPragma__pragmas_2498)(tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw pragma) {
NIM_BOOL result;
{ result = (NIM_BOOL)0;
{
if (!(n == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL))) goto LA3_;
result = NIM_FALSE;
goto BeforeRet_;
}
LA3_: ;
{
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* p;
p = NIM_NIL;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = safeLen__ast_3191(n);
i_2 = ((NI) 0);
{
while (1) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* key;
if (!(i_2 < colontmp_)) goto LA8;
i = i_2;
p = (*n)._kind_6.sons->data[i];
{
NIM_BOOL T11_;
NI T13_;
T11_ = (NIM_BOOL)0;
T11_ = ((*p).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*p).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*p).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T11_)) goto LA12_;
T13_ = (NI)0;
T13_ = len__ast_3198(p);
T11_ = (((NI) 1) < T13_);
LA12_: ;
if (!T11_) goto LA14_;
key = (*p)._kind_6.sons->data[((NI) 0)];
}
goto LA9_;
LA14_: ;
{
key = p;
}
LA9_: ;
{
NIM_BOOL T19_;
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw T21_;
T19_ = (NIM_BOOL)0;
T19_ = ((*key).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
if (!(T19_)) goto LA20_;
T21_ = (tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw)0;
T21_ = whichKeyword__idents_214((*key)._kind_5.ident);
T19_ = (T21_ == pragma);
LA20_: ;
if (!T19_) goto LA22_;
result = NIM_TRUE;
goto BeforeRet_;
}
LA22_: ;
i_2 += ((NI) 1);
} LA8: ;
}
}
}
result = NIM_FALSE;
goto BeforeRet_;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, pragmaCallable__pragmas_2552)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TSym__nnJKJFyjDGi5mnv8jwfTGQ* sym, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n, tySet_tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw validPragmas, NIM_BOOL isStatement) {
{ {
if (!(n == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL))) goto LA3_;
goto BeforeRet_;
}
LA3_: ;
{
if (!!(((*(*n)._kind_6.sons->data[((NI) 4)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 1)))) goto LA7_;
pragmaRec__pragmas_2524(c, sym, (*n)._kind_6.sons->data[((NI) 4)], validPragmas, isStatement);
}
LA7_: ;
}BeforeRet_: ;
}
N_LIB_PRIVATE N_NIMCALL(NIM_CHAR, pragmaAsm__pragmas_201)(tyObject_TContext__C9bB2okDBl3OKGUBiY5k5Ug* c, tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* n) {
NIM_CHAR result;
result = (NIM_CHAR)0;
result = 0;
{
if (!!((n == ((tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw*) NIM_NIL)))) goto LA3_;
{
NI i;
NI colontmp_;
NI i_2;
i = (NI)0;
colontmp_ = (NI)0;
colontmp_ = len__ast_3198(n);
i_2 = ((NI) 0);
{
while (1) {
tyObject_TNode__bROa11lyF5vxEN9aYNbHmhw* it;
if (!(i_2 < colontmp_)) goto LA7;
i = i_2;
it = (*n)._kind_6.sons->data[i];
{
NIM_BOOL T10_;
NIM_BOOL T11_;
NI T13_;
tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw T17_;
T10_ = (NIM_BOOL)0;
T11_ = (NIM_BOOL)0;
T11_ = ((*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 34) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 27) || (*it).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 28));
if (!(T11_)) goto LA12_;
T13_ = (NI)0;
T13_ = len__ast_3198(it);
T11_ = (T13_ == ((NI) 2));
LA12_: ;
T10_ = T11_;
if (!(T10_)) goto LA14_;
T10_ = ((*(*it)._kind_6.sons->data[((NI) 0)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 2));
LA14_: ;
if (!T10_) goto LA15_;
T17_ = (tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw)0;
T17_ = whichKeyword__idents_214((*(*it)._kind_6.sons->data[((NI) 0)])._kind_5.ident);
switch (T17_) {
case ((tyEnum_TSpecialWord__ycbpMCRV6Cd2eBh3X9biEiw) 201):
{
{
if (!((*(*it)._kind_6.sons->data[((NI) 1)]).kind == ((tyEnum_TNodeKind__G4E4Gxe7oI2Cm03rkiOzQw) 5))) goto LA21_;
result = ((NIM_CHAR) (((NI) (((NI) ((*(*it)._kind_6.sons->data[((NI) 1)])._kind_1.intVal))))));
}
goto LA19_;
LA21_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA19_: ;
}
break;
default:
{
invalidPragma__pragmas_148(c, it);
}
break;
}
}
goto LA8_;
LA15_: ;
{
invalidPragma__pragmas_148(c, it);
}
LA8_: ;
i_2 += ((NI) 1);
} LA7: ;
}
}
}
LA3_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, compiler_pragmasDatInit000)(void) {
static TNimNode* TM__tPA3StZ6VsKyoznyrIfFxg_38_2[2];
static TNimNode TM__tPA3StZ6VsKyoznyrIfFxg_0[3];
NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_.size = sizeof(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw);
NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_.align = NIM_ALIGNOF(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw);
NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_.kind = 17;
NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_.base = (&NTIrootobj__ytyiCJqK439aF9cIibuRVpAg_);
TM__tPA3StZ6VsKyoznyrIfFxg_38_2[0] = &TM__tPA3StZ6VsKyoznyrIfFxg_0[1];
TM__tPA3StZ6VsKyoznyrIfFxg_0[1].kind = 1;
TM__tPA3StZ6VsKyoznyrIfFxg_0[1].offset = offsetof(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw, colonstate_);
TM__tPA3StZ6VsKyoznyrIfFxg_0[1].typ = (&NTIint__xHTZrq9aYs6boc9bCba0JbpQ_);
TM__tPA3StZ6VsKyoznyrIfFxg_0[1].name = ":state";
TM__tPA3StZ6VsKyoznyrIfFxg_38_2[1] = &TM__tPA3StZ6VsKyoznyrIfFxg_0[2];
TM__tPA3StZ6VsKyoznyrIfFxg_0[2].kind = 1;
TM__tPA3StZ6VsKyoznyrIfFxg_0[2].offset = offsetof(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw, owner1);
TM__tPA3StZ6VsKyoznyrIfFxg_0[2].typ = (&NTIpsym__dG2QVH5Z69aMUY38zTqWxaA_);
TM__tPA3StZ6VsKyoznyrIfFxg_0[2].name = "owner1";
TM__tPA3StZ6VsKyoznyrIfFxg_0[0].len = 2; TM__tPA3StZ6VsKyoznyrIfFxg_0[0].kind = 2; TM__tPA3StZ6VsKyoznyrIfFxg_0[0].sons = &TM__tPA3StZ6VsKyoznyrIfFxg_38_2[0];
NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_.node = &TM__tPA3StZ6VsKyoznyrIfFxg_0[0];
NTIrefobject__b333ORV1UJUlL6q84XcNlQ_.size = sizeof(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw*);
NTIrefobject__b333ORV1UJUlL6q84XcNlQ_.align = NIM_ALIGNOF(tyObject_Env_pragmasdotnim_processEffectsOf___xT9cBMj7Bepcw0VSuLvpkZw*);
NTIrefobject__b333ORV1UJUlL6q84XcNlQ_.kind = 22;
NTIrefobject__b333ORV1UJUlL6q84XcNlQ_.base = (&NTIobject__xT9cBMj7Bepcw0VSuLvpkZw_);
NTIrefobject__b333ORV1UJUlL6q84XcNlQ_.marker = Marker_tyRef__b333ORV1UJUlL6q84XcNlQ;
}
|
307618.c | /*
* This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <string.h>
#include <unistd.h>
#include <postgres.h>
#include <fmgr.h>
#include "export.h"
#include "process_utility.h"
#include "compat.h"
#include "event_trigger.h"
#include "cross_module_fn.h"
TS_FUNCTION_INFO_V1(ts_test_ddl_command_hook_reg);
TS_FUNCTION_INFO_V1(ts_test_ddl_command_hook_unreg);
static List *tsl_delayed_execution_list = NIL;
static void
test_ddl_command_start(ProcessUtilityArgs *args)
{
Cache *hcache;
ListCell *cell;
Hypertable *ht;
elog(NOTICE,
"test_ddl_command_start: %d hypertables, query: %s",
list_length(args->hypertable_list),
args->query_string);
/*
* Hypertable oid from those commands is available in hypertable_list but
* cannot be resolved here until standard utility hook will synchronize new
* relation name and schema.
*
* Save hypertable list here for command_end execution to avoid statement
* parsing for second time.
*/
switch (nodeTag(args->parsetree))
{
case T_AlterObjectSchemaStmt:
case T_RenameStmt:
elog(NOTICE, "test_ddl_command_start: wait for ddl_command_end");
tsl_delayed_execution_list = list_copy(args->hypertable_list);
return;
default:
break;
}
hcache = ts_hypertable_cache_pin();
foreach (cell, args->hypertable_list)
{
Oid relid = lfirst_oid(cell);
ht = ts_hypertable_cache_get_entry(hcache, relid, false);
elog(NOTICE,
"test_ddl_command_start: %s.%s",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name));
}
ts_cache_release(hcache);
}
static void
test_ddl_command_end(EventTriggerData *command)
{
Cache *hcache;
ListCell *cell;
Hypertable *ht;
elog(NOTICE, "test_ddl_command_end: %s", command->tag);
if (tsl_delayed_execution_list == NIL)
return;
elog(NOTICE,
"test_ddl_command_end: %d hypertables scheduled",
list_length(tsl_delayed_execution_list));
hcache = ts_hypertable_cache_pin();
foreach (cell, tsl_delayed_execution_list)
{
Oid relid = lfirst_oid(cell);
ht = ts_hypertable_cache_get_entry(hcache, relid, false);
elog(NOTICE,
"test_ddl_command_end: %s.%s",
NameStr(ht->fd.schema_name),
NameStr(ht->fd.table_name));
}
ts_cache_release(hcache);
pfree(tsl_delayed_execution_list);
tsl_delayed_execution_list = NIL;
}
static int
event_trigger_event_cmp(const void *obj1, const void *obj2)
{
const EventTriggerDropObject *obj[] = { *((const EventTriggerDropObject **) obj1),
*((const EventTriggerDropObject **) obj2) };
/* This only orders on object type for simplicity. Thus it is assumed that
* the order of objects with the same type is predictible across
* PostgreSQL versions */
return obj[0]->type - obj[1]->type;
}
static void
test_sql_drop(List *dropped_objects)
{
ListCell *lc;
int num_objects = list_length(dropped_objects);
EventTriggerDropObject **objects = palloc(num_objects * sizeof(EventTriggerDropObject *));
int i = 0;
/* Sort the list of dropped objects for predictible order in tests across
* PostgreSQL versions. Note that PG11 introduced a list_qsort function,
* but it is not available in earlier PostgreSQL versions so we're doing
* our own sorting. */
foreach (lc, dropped_objects)
objects[i++] = lfirst(lc);
qsort(objects, num_objects, sizeof(EventTriggerDropObject *), event_trigger_event_cmp);
for (i = 0; i < num_objects; i++)
{
EventTriggerDropObject *obj = objects[i];
switch (obj->type)
{
case EVENT_TRIGGER_DROP_TABLE_CONSTRAINT:
{
EventTriggerDropTableConstraint *event = (EventTriggerDropTableConstraint *) obj;
elog(NOTICE,
"test_sql_drop: constraint: %s.%s.%s",
event->schema,
event->table,
event->constraint_name);
break;
}
case EVENT_TRIGGER_DROP_INDEX:
{
elog(NOTICE, "test_sql_drop: index");
break;
}
case EVENT_TRIGGER_DROP_TABLE:
{
EventTriggerDropTable *event = (EventTriggerDropTable *) obj;
elog(NOTICE, "test_sql_drop: table: %s.%s", event->schema, event->table_name);
break;
}
case EVENT_TRIGGER_DROP_SCHEMA:
{
EventTriggerDropSchema *event = (EventTriggerDropSchema *) obj;
elog(NOTICE, "test_sql_drop: schema: %s", event->schema);
break;
}
case EVENT_TRIGGER_DROP_TRIGGER:
{
elog(NOTICE, "test_sql_drop: trigger");
break;
}
case EVENT_TRIGGER_DROP_VIEW:
{
elog(NOTICE, "test_sql_drop: view");
break;
}
}
}
}
Datum
ts_test_ddl_command_hook_reg(PG_FUNCTION_ARGS)
{
Assert(ts_cm_functions->ddl_command_start == NULL);
ts_cm_functions->ddl_command_start = test_ddl_command_start;
ts_cm_functions->ddl_command_end = test_ddl_command_end;
ts_cm_functions->sql_drop = test_sql_drop;
PG_RETURN_VOID();
}
Datum
ts_test_ddl_command_hook_unreg(PG_FUNCTION_ARGS)
{
Assert(ts_cm_functions->ddl_command_start == test_ddl_command_start);
ts_cm_functions->ddl_command_start = NULL;
ts_cm_functions->ddl_command_end = NULL;
ts_cm_functions->sql_drop = NULL;
PG_RETURN_VOID();
}
|
501166.c | #include "mini_uart.h"
#include "shell.h"
#include "devtree.h"
#include "cpio.h"
#include "mm.h"
#include "timer.h"
#include "exception.h"
#include "fork.h"
void kernel_main(void)
{
uart_init();
devtree_getaddr();
fdt_traverse(initramfs_callback);
init_mm_reserve();
timer_init();
enable_interrupt();
uart_send_string("OSDI 2022 Spring\n");
copy_process(PF_KTHREAD, (unsigned long)&shell_loop, 0, 0);
while (1) {
kill_zombies();
schedule();
}
} |
76116.c | /**
* WinPR: Windows Portable Runtime
* Virtual GIDS implementation
*
* Copyright 2021 Martin Fleisz <[email protected]>
* Copyright 2021 Thincast Technologies GmbH
*
* 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 <freerdp/config.h>
#include <winpr/wlog.h>
#include <winpr/stream.h>
#include <winpr/collections.h>
#include <openssl/bn.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <zlib.h>
#include "smartcard_virtual_gids.h"
#define TAG CHANNELS_TAG("smartcard.vgids")
#define VGIDS_EFID_MASTER 0xA000
#define VGIDS_EFID_COMMON 0xA010
#define VGIDS_EFID_CARDCF VGIDS_EFID_COMMON
#define VGIDS_EFID_CARDAPPS VGIDS_EFID_COMMON
#define VGIDS_EFID_CMAPFILE VGIDS_EFID_COMMON
#define VGIDS_EFID_CARDID 0xA012
#define VGIDS_EFID_KXC00 VGIDS_EFID_COMMON
#define VGIDS_EFID_CURRENTDF 0x3FFF
#define VGIDS_DO_FILESYSTEMTABLE 0xDF1F
#define VGIDS_DO_KEYMAP 0xDF20
#define VGIDS_DO_CARDID 0xDF20
#define VGIDS_DO_CARDAPPS 0xDF21
#define VGIDS_DO_CARDCF 0xDF22
#define VGIDS_DO_CMAPFILE 0xDF23
#define VGIDS_DO_KXC00 0xDF24
#define VGIDS_CARDID_SIZE 16
#define VGIDS_MAX_PIN_SIZE 127
#define VGIDS_DEFAULT_RETRY_COUNTER 3
#define VGIDS_KEY_TYPE_KEYEXCHANGE 0x9A
#define VGIDS_KEY_TYPE_SIGNATURE 0x9C
#define VGIDS_ALGID_RSA_1024 0x06
#define VGIDS_ALGID_RSA_2048 0x07
#define VGIDS_ALGID_RSA_3072 0x08
#define VGIDS_ALGID_RSA_4096 0x09
#define VGIDS_SE_CRT_AUTH 0xA4
#define VGIDS_SE_CRT_SIGN 0xB6
#define VGIDS_SE_CRT_CONF 0xB8
#define VGIDS_SE_ALGOID_CT_PAD_PKCS1 0x40
#define VGIDS_SE_ALGOID_CT_PAD_OAEP 0x80
#define VGIDS_SE_ALGOID_CT_RSA_1024 0x06
#define VGIDS_SE_ALGOID_CT_RSA_2048 0x07
#define VGIDS_SE_ALGOID_CT_RSA_3072 0x08
#define VGIDS_SE_ALGOID_CT_RSA_4096 0x09
#define VGIDS_SE_ALGOID_DST_PAD_PKCS1 0x40
#define VGIDS_SE_ALGOID_DST_RSA_1024 0x06
#define VGIDS_SE_ALGOID_DST_RSA_2048 0x07
#define VGIDS_SE_ALGOID_DST_RSA_3072 0x08
#define VGIDS_SE_ALGOID_DST_RSA_4096 0x09
#define VGIDS_SE_ALGOID_DST_ECDSA_P192 0x0A
#define VGIDS_SE_ALGOID_DST_ECDSA_P224 0x0B
#define VGIDS_SE_ALGOID_DST_ECDSA_P256 0x0C
#define VGIDS_SE_ALGOID_DST_ECDSA_P384 0x0D
#define VGIDS_SE_ALGOID_DST_ECDSA_P512 0x0E
#define VGIDS_DEFAULT_KEY_REF 0x81
#define ISO_INS_SELECT 0xA4
#define ISO_INS_GETDATA 0xCB
#define ISO_INS_GETRESPONSE 0xC0
#define ISO_INS_MSE 0x22
#define ISO_INS_PSO 0x2A
#define ISO_INS_VERIFY 0x20
#define ISO_STATUS_MORE_DATA 0x6100
#define ISO_STATUS_VERIFYFAILED 0x6300
#define ISO_STATUS_WRONGLC 0x6700
#define ISO_STATUS_COMMANDNOTALLOWED 0x6900
#define ISO_STATUS_SECURITYSTATUSNOTSATISFIED 0x6982
#define ISO_STATUS_AUTHMETHODBLOCKED 0x6983
#define ISO_STATUS_INVALIDCOMMANDDATA 0x6A80
#define ISO_STATUS_FILENOTFOUND 0x6A82
#define ISO_STATUS_INVALIDP1P2 0x6A86
#define ISO_STATUS_INVALIDLC 0x6A87
#define ISO_STATUS_REFERENCEDATANOTFOUND 0x6A88
#define ISO_STATUS_SUCCESS 0x9000
#define ISO_AID_MAX_SIZE 16
#define ISO_FID_MF 0x3F00
struct vgids_ef
{
UINT16 id;
UINT16 dirID;
wStream* data;
};
typedef struct vgids_ef vgidsEF;
struct vgids_se
{
BYTE crt; /* control reference template tag */
BYTE algoId; /* Algorithm ID */
BYTE keyRef; /* Key reference */
};
typedef struct vgids_se vgidsSE;
struct vgids_context
{
UINT16 currentDF;
char* pin;
UINT16 curRetryCounter;
UINT16 retryCounter;
wStream* commandData;
wStream* responseData;
BOOL pinVerified;
vgidsSE currentSE;
X509* certificate;
RSA* publicKey;
RSA* privateKey;
wArrayList* files;
};
/* PKCS 1.5 DER encoded digest information */
#define VGIDS_MAX_DIGEST_INFO 7
static const BYTE g_PKCS1_SHA1[] = { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
static const BYTE g_PKCS1_SHA224[] = { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c };
static const BYTE g_PKCS1_SHA256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
static const BYTE g_PKCS1_SHA384[] = { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 };
static const BYTE g_PKCS1_SHA512[] = { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 };
static const BYTE g_PKCS1_SHA512_224[] = { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60,
0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x05, 0x05, 0x00, 0x04, 0x1c };
static const BYTE g_PKCS1_SHA512_256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x06, 0x05, 0x00, 0x04, 0x20 };
/* Helper struct to map PKCS1.5 digest info to OpenSSL EVP_MD */
struct vgids_digest_info_map
{
const BYTE* info;
size_t infoSize;
const EVP_MD* digest;
};
typedef struct vgids_digest_info_map vgidsDigestInfoMap;
/* MS GIDS AID */
/* xx: Used by the Windows smart card framework for the GIDS version number. This byte must be set
* to the GIDS specification revision number which is either 0x01 or 0x02.
* yy: Reserved for use by the card application (set to 01)
*/
static const BYTE g_MsGidsAID[] = {
0xA0, 0x00, 0x00, 0x03, 0x97, 0x42, 0x54, 0x46, 0x59, 0x02, 0x01
};
/* GIDS APP File Control Parameter:
FD-Byte (82): 38 (not shareable-DF)
Sec Attr (8C): 03 30 30 Create/Delete File(03) Ext/User-Auth (30)
*/
static const BYTE g_GidsAppFCP[] = { 0x62, 0x08, 0x82, 0x01, 0x38, 0x8C, 0x03, 0x03, 0x30, 0x30 };
/* GIDS APP File Control Information:
AppID (4F, Len 0B): A0 00 00 03 97 42 54 46 59 02 01
Discretionary DOs (73, Len 03): 40 01 C0
Supported Auth Protocols (40, Len 01): C0 Mutual/External-Auth
*/
static const BYTE g_GidsAppFCI[] = { 0x61, 0x12, 0x4F, 0x0B, 0xA0, 0x00, 0x00, 0x03, 0x97, 0x42,
0x54, 0x46, 0x59, 0x02, 0x01, 0x73, 0x03, 0x40, 0x01, 0xC0 };
/*
typedef struct
{
BYTE bVersion; // Cache version
BYTE bPinsFreshness; // Card PIN
WORD wContainersFreshness;
WORD wFilesFreshness;
} CARD_CACHE_FILE_FORMAT, *PCARD_CACHE_FILE_FORMAT; */
static const BYTE g_CardCFContents[] = { 0x00, 0x00, 0x01, 0x00, 0x04, 0x00 };
/* {mscp,0,0,0,0} */
static const BYTE g_CardAppsContents[] = { 0x6d, 0x73, 0x63, 0x70, 0x00, 0x00, 0x00, 0x00 };
#pragma pack(push, 1)
/* Type: CONTAINER_MAP_RECORD (taken from Windows Smart Card Minidriver Specification)
This structure describes the format of the Base CSP's
container map file, stored on the card. This is wellknown
logical file wszCONTAINER_MAP_FILE. The file consists of
zero or more of these records. */
#define MAX_CONTAINER_NAME_LEN 39
/* This flag is set in the CONTAINER_MAP_RECORD bFlags
member if the corresponding container is valid and currently
exists on the card. // If the container is deleted, its
bFlags field must be cleared. */
#define CONTAINER_MAP_VALID_CONTAINER 1
/* This flag is set in the CONTAINER_MAP_RECORD bFlags
member if the corresponding container is the default
container on the card. */
#define CONTAINER_MAP_DEFAULT_CONTAINER 2
struct vgids_container_map_entry
{
WCHAR wszGuid[MAX_CONTAINER_NAME_LEN + 1];
BYTE bFlags;
BYTE bReserved;
WORD wSigKeySizeBits;
WORD wKeyExchangeKeySizeBits;
};
typedef struct vgids_container_map_entry vgidsContainerMapEntry;
struct vgids_filesys_table_entry
{
char directory[9];
char filename[9];
UINT16 pad0;
UINT16 dataObjectIdentifier;
UINT16 pad1;
UINT16 fileIdentifier;
UINT16 unknown;
};
typedef struct vgids_filesys_table_entry vgidsFilesysTableEntry;
struct vgids_keymap_record
{
UINT32 state;
BYTE algid;
BYTE keytype;
UINT16 keyref;
UINT16 unknownWithFFFF;
UINT16 unknownWith0000;
};
typedef struct vgids_keymap_record vgidsKeymapRecord;
#pragma pack(pop)
static vgidsEF* vgids_ef_new(vgidsContext* ctx, USHORT id)
{
vgidsEF* ef = calloc(1, sizeof(vgidsEF));
ef->id = id;
ef->data = Stream_New(NULL, 1024);
if (!ef->data)
{
WLog_ERR(TAG, "Failed to create file data stream");
goto create_failed;
}
Stream_SetLength(ef->data, 0);
if (!ArrayList_Append(ctx->files, ef))
{
WLog_ERR(TAG, "Failed to add new ef to file list");
goto create_failed;
}
return ef;
create_failed:
free(ef);
return NULL;
}
static BOOL vgids_write_tlv(wStream* s, UINT16 tag, const BYTE* data, DWORD dataSize)
{
/* A maximum of 5 additional bytes is needed */
if (!Stream_EnsureRemainingCapacity(s, dataSize + 5))
{
WLog_ERR(TAG, "Failed to ensure capacity of DO stream");
return FALSE;
}
/* BER encoding: If the most-significant bit is set (0x80) the length is encoded in the
* remaining bits. So lengths < 128 bytes can be set directly, all others are encoded */
if (tag > 0xFF)
Stream_Write_UINT16_BE(s, tag);
else
Stream_Write_UINT8(s, (BYTE)tag);
if (dataSize < 128)
{
Stream_Write_UINT8(s, (BYTE)dataSize);
}
else if (dataSize < 256)
{
Stream_Write_UINT8(s, 0x81);
Stream_Write_UINT8(s, (BYTE)dataSize);
}
else
{
Stream_Write_UINT8(s, 0x82);
Stream_Write_UINT16_BE(s, (UINT16)dataSize);
}
Stream_Write(s, data, dataSize);
Stream_SealLength(s);
return TRUE;
}
static BOOL vgids_ef_write_do(vgidsEF* ef, UINT16 doID, const BYTE* data, DWORD dataSize)
{
/* Write DO to end of file: 2-Byte ID, 1-Byte Len, Data */
return vgids_write_tlv(ef->data, doID, data, dataSize);
}
static BOOL vgids_ef_read_do(vgidsEF* ef, UINT16 doID, BYTE** data, DWORD* dataSize)
{
/* Read the given DO from the file: 2-Byte ID, 1-Byte Len, Data */
if (!Stream_SetPosition(ef->data, 0))
{
WLog_ERR(TAG, "Failed to seek to front of file");
return FALSE;
}
/* Look for the requested DO */
while (Stream_GetRemainingLength(ef->data) > 3)
{
BYTE len;
size_t curPos;
UINT16 doSize;
UINT16 nextDOID;
curPos = Stream_GetPosition(ef->data);
Stream_Read_UINT16_BE(ef->data, nextDOID);
Stream_Read_UINT8(ef->data, len);
if ((len & 0x80))
{
BYTE lenSize = len & 0x7F;
if (Stream_GetRemainingLength(ef->data) < lenSize)
{
WLog_ERR(TAG, "Remaining length is smaller than constructed tag length");
return FALSE;
}
switch (lenSize)
{
case 1:
Stream_Read_UINT8(ef->data, doSize);
break;
case 2:
Stream_Read_UINT16_BE(ef->data, doSize);
break;
default:
WLog_ERR(TAG, "Unexpected tag length %" PRIu8, lenSize);
return FALSE;
}
}
else
doSize = len;
if (Stream_GetRemainingLength(ef->data) < doSize)
{
WLog_ERR(TAG, "Unexpected end for DO %04" PRIx16, nextDOID);
return FALSE;
}
if (nextDOID == doID)
{
BYTE* outData;
/* Include Tag and length in result */
doSize += (UINT16)(Stream_GetPosition(ef->data) - curPos);
outData = malloc(doSize);
if (!outData)
{
WLog_ERR(TAG, "Failed to allocate output buffer");
return FALSE;
}
Stream_SetPosition(ef->data, curPos);
Stream_Read(ef->data, outData, doSize);
*data = outData;
*dataSize = doSize;
return TRUE;
}
else
{
/* Skip DO */
Stream_SafeSeek(ef->data, doSize);
}
}
return FALSE;
}
static void vgids_ef_free(void* ptr)
{
vgidsEF* ef = ptr;
if (ef)
{
Stream_Free(ef->data, TRUE);
free(ef);
}
}
static BOOL vgids_prepare_fstable(const vgidsFilesysTableEntry* fstable, DWORD numEntries,
BYTE** outData, DWORD* outDataSize)
{
/* Filesystem table:
BYTE unkonwn: 0x01
Array of vgidsFilesysTableEntry
*/
DWORD i;
BYTE* data = malloc(sizeof(vgidsFilesysTableEntry) * numEntries + 1);
if (!data)
{
WLog_ERR(TAG, "Failed to allocate filesystem table data blob");
return FALSE;
}
*data = 0x01;
for (i = 0; i < numEntries; ++i)
memcpy(data + 1 + (sizeof(vgidsFilesysTableEntry) * i), &fstable[i],
sizeof(vgidsFilesysTableEntry));
*outData = data;
*outDataSize = sizeof(vgidsFilesysTableEntry) * numEntries + 1;
return TRUE;
}
static BOOL vgids_prepare_certificate(X509* cert, BYTE** kxc, DWORD* kxcSize)
{
/* Key exchange container:
UINT16 compression version: 0001
UINT16 source size
ZLIB compressed cert
*/
BYTE* i2dParam;
uLongf destSize;
wStream* s = NULL;
BYTE* certData = NULL;
BYTE* comprData = NULL;
int certSize = i2d_X509(cert, NULL);
if (certSize < 0)
{
WLog_ERR(TAG, "Failed to get certificate size");
goto handle_error;
}
certData = malloc(certSize);
comprData = malloc(certSize);
if (!certData || !comprData)
{
WLog_ERR(TAG, "Failed to allocate certificate buffer");
goto handle_error;
}
/* serialize certificate to buffer (out buffer pointer is modified so pass a copy!) */
i2dParam = certData;
if (i2d_X509(cert, &i2dParam) < 0)
{
WLog_ERR(TAG, "Failed to encode X509 certificate to DER");
goto handle_error;
}
/* compress certificate data */
destSize = certSize;
if (compress(comprData, &destSize, certData, certSize) != Z_OK)
{
WLog_ERR(TAG, "Failed to compress certificate data");
goto handle_error;
}
/* Write container data */
s = Stream_New(NULL, destSize + 4);
Stream_Write_UINT16(s, 0x0001);
Stream_Write_UINT16(s, (UINT16)certSize);
Stream_Write(s, comprData, destSize);
Stream_SealLength(s);
*kxc = Stream_Buffer(s);
*kxcSize = (DWORD)Stream_Length(s);
Stream_Free(s, FALSE);
free(certData);
free(comprData);
return TRUE;
handle_error:
Stream_Free(s, TRUE);
free(certData);
free(comprData);
return FALSE;
}
static BYTE vgids_get_algid(vgidsContext* p_Ctx)
{
int modulusSize = RSA_size(p_Ctx->privateKey);
switch (modulusSize)
{
case (1024 / 8):
return VGIDS_ALGID_RSA_1024;
case (2048 / 8):
return VGIDS_ALGID_RSA_2048;
case (3072 / 8):
return VGIDS_ALGID_RSA_3072;
case (4096 / 8):
return VGIDS_ALGID_RSA_4096;
default:
WLog_ERR(TAG, "Failed to determine algid for private key");
break;
}
return 0;
}
static BOOL vgids_prepare_keymap(vgidsContext* context, BYTE** outData, DWORD* outDataSize)
{
/* Key map record table:
BYTE unkonwn (count?): 0x01
Array of vgidsKeymapRecord
*/
BYTE* data;
vgidsKeymapRecord record = {
1, /* state */
0, /* algo */
VGIDS_KEY_TYPE_KEYEXCHANGE, /* keytpe */
(0xB000 | VGIDS_DEFAULT_KEY_REF), /* keyref */
0xFFFF, /* unknown FFFF */
0x0000 /* unknown 0000 */
};
/* Determine algo */
BYTE algid = vgids_get_algid(context);
if (algid == 0)
return FALSE;
data = malloc(sizeof(record) + 1);
if (!data)
{
WLog_ERR(TAG, "Failed to allocate filesystem table data blob");
return FALSE;
}
*data = 0x01;
record.algid = algid;
memcpy(data + 1, &record, sizeof(record));
*outData = data;
*outDataSize = sizeof(record) + 1;
return TRUE;
}
static BOOL vgids_parse_apdu_header(wStream* s, BYTE* cla, BYTE* ins, BYTE* p1, BYTE* p2, BYTE* lc,
BYTE* le)
{
if (Stream_GetRemainingLength(s) < 4)
{
WLog_ERR(TAG, "APDU header with less than 5 bytes");
return FALSE;
}
/* Read and verify APDU data */
if (cla)
Stream_Read_UINT8(s, *cla);
else
Stream_Seek(s, 1);
if (ins)
Stream_Read_UINT8(s, *ins);
else
Stream_Seek(s, 1);
if (p1)
Stream_Read_UINT8(s, *p1);
else
Stream_Seek(s, 1);
if (p2)
Stream_Read_UINT8(s, *p2);
else
Stream_Seek(s, 1);
/* If LC is requested - check remaining length and read as well */
if (lc)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, *lc);
if (Stream_GetRemainingLength(s) < *lc)
{
WLog_ERR(TAG, "The LC byte is greater than the remaining command data");
return FALSE;
}
}
/* read LE */
if (le)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Missing LE byte");
return FALSE;
}
Stream_Read_UINT8(s, *le);
}
return TRUE;
}
static BOOL vgids_create_response(UINT16 status, const BYTE* answer, DWORD answerSize,
BYTE** outData, DWORD* outDataSize)
{
BYTE* out = malloc(answerSize + 2);
if (!out)
{
WLog_ERR(TAG, "Failed to allocate memory for response data");
return FALSE;
}
*outData = out;
if (answer)
{
memcpy(out, answer, answerSize);
out += answerSize;
}
*out = (BYTE)((status >> 8) & 0xFF);
*(out + 1) = (BYTE)(status & 0xFF);
*outDataSize = answerSize + 2;
return TRUE;
}
static BOOL vgids_read_do_fkt(void* data, size_t index, va_list ap)
{
BYTE* response;
DWORD responseSize;
vgidsEF* file = (vgidsEF*)data;
vgidsContext* context = va_arg(ap, vgidsContext*);
UINT16 efID = (UINT16)va_arg(ap, unsigned);
UINT16 doID = (UINT16)va_arg(ap, unsigned);
WINPR_UNUSED(index);
if (efID == 0x3FFF || efID == file->id)
{
/* If the DO was successfully read - abort file enum */
if (vgids_ef_read_do(file, doID, &response, &responseSize))
{
context->responseData = Stream_New(response, (size_t)responseSize);
return FALSE;
}
}
return TRUE;
}
static void vgids_read_do(vgidsContext* context, UINT16 efID, UINT16 doID)
{
ArrayList_ForEach(context->files, vgids_read_do_fkt, context, efID, doID);
}
static void vgids_reset_context_response(vgidsContext* context)
{
Stream_Free(context->responseData, TRUE);
context->responseData = NULL;
}
static void vgids_reset_context_command_data(vgidsContext* context)
{
Stream_Free(context->commandData, TRUE);
context->commandData = NULL;
}
static BOOL vgids_ins_select(vgidsContext* context, wStream* s, BYTE** response,
DWORD* responseSize)
{
BYTE p1, p2, lc;
DWORD resultDataSize = 0;
const BYTE* resultData = NULL;
UINT16 status = ISO_STATUS_SUCCESS;
/* The only select operations performed are either select by AID or select 3FFF (return
* information about the currently selected DF) */
if (!vgids_parse_apdu_header(s, NULL, NULL, &p1, &p2, &lc, NULL))
return FALSE;
/* Check P1 for selection mode */
switch (p1)
{
/* Select by AID */
case 0x04:
{
/* read AID from APDU */
BYTE aid[ISO_AID_MAX_SIZE] = { 0 };
if (lc > ISO_AID_MAX_SIZE)
{
WLog_ERR(TAG, "The LC byte is greater than the maximum AID length");
status = ISO_STATUS_INVALIDLC;
break;
}
/* Check if we select MS GIDS App (only one we know) */
Stream_Read(s, aid, lc);
if (memcmp(aid, g_MsGidsAID, lc) != 0)
{
status = ISO_STATUS_FILENOTFOUND;
break;
}
/* Return FCI or FCP for MsGids App */
switch (p2)
{
/* Return FCI information */
case 0x00:
{
resultData = g_GidsAppFCI;
resultDataSize = sizeof(g_GidsAppFCI);
break;
}
/* Return FCP information */
case 0x04:
{
resultData = g_GidsAppFCP;
resultDataSize = sizeof(g_GidsAppFCP);
break;
}
default:
status = ISO_STATUS_INVALIDP1P2;
break;
}
if (resultData)
context->currentDF = ISO_FID_MF;
break;
}
/* Select by FID */
case 0x00:
{
/* read FID from APDU */
UINT16 fid;
if (lc > 2)
{
WLog_ERR(TAG, "The LC byte for the file ID is greater than 2");
status = ISO_STATUS_INVALIDLC;
break;
}
Stream_Read_UINT16_BE(s, fid);
if (fid != VGIDS_EFID_CURRENTDF || context->currentDF == 0)
{
status = ISO_STATUS_FILENOTFOUND;
break;
}
break;
}
default:
{
/* P1 P2 combination not supported */
status = ISO_STATUS_INVALIDP1P2;
break;
}
}
return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
}
static UINT16 vgids_handle_chained_response(vgidsContext* context, const BYTE** response,
DWORD* responseSize)
{
/* Cap to a maximum of 256 bytes and set status to more data */
UINT16 status = ISO_STATUS_SUCCESS;
DWORD remainingBytes = (DWORD)Stream_Length(context->responseData);
if (remainingBytes > 256)
{
status = ISO_STATUS_MORE_DATA;
remainingBytes = 256;
}
*response = Stream_Buffer(context->responseData);
*responseSize = remainingBytes;
Stream_Seek(context->responseData, remainingBytes);
/* Check if there are more than 256 bytes left or if we can already provide the remaining length
* in the status word */
remainingBytes = (DWORD)(Stream_Length(context->responseData) - remainingBytes);
if (remainingBytes < 256 && remainingBytes != 0)
status |= (remainingBytes & 0xFF);
return status;
}
static BOOL vgids_get_public_key(vgidsContext* context, UINT16 doTag)
{
BYTE* buf = NULL;
wStream* pubKey = NULL;
wStream* response = NULL;
const BIGNUM *n, *e;
int nSize, eSize;
/* Get key components */
RSA_get0_key(context->publicKey, &n, &e, NULL);
nSize = BN_num_bytes(n);
eSize = BN_num_bytes(e);
buf = malloc(nSize > eSize ? nSize : eSize);
if (!buf)
{
WLog_ERR(TAG, "Failed to allocate buffer for public key");
goto handle_error;
}
pubKey = Stream_New(NULL, nSize + eSize + 0x10);
if (!pubKey)
{
WLog_ERR(TAG, "Failed to allocate public key stream");
goto handle_error;
}
response = Stream_New(NULL, Stream_Capacity(pubKey) + 0x10);
if (!response)
{
WLog_ERR(TAG, "Failed to allocate response stream");
goto handle_error;
}
/* write modulus and exponent DOs */
BN_bn2bin(n, buf);
if (!vgids_write_tlv(pubKey, 0x81, buf, nSize))
goto handle_error;
BN_bn2bin(e, buf);
if (!vgids_write_tlv(pubKey, 0x82, buf, eSize))
goto handle_error;
/* write ISO public key template */
if (!vgids_write_tlv(response, doTag, Stream_Buffer(pubKey), (DWORD)Stream_Length(pubKey)))
goto handle_error;
/* set response data */
Stream_SetPosition(response, 0);
context->responseData = response;
free(buf);
Stream_Free(pubKey, TRUE);
return TRUE;
handle_error:
free(buf);
Stream_Free(pubKey, TRUE);
Stream_Free(response, TRUE);
return FALSE;
}
static BOOL vgids_ins_getdata(vgidsContext* context, wStream* s, BYTE** response,
DWORD* responseSize)
{
UINT16 doId;
UINT16 fileId;
BYTE p1, p2, lc;
DWORD resultDataSize = 0;
const BYTE* resultData = NULL;
UINT16 status = ISO_STATUS_SUCCESS;
/* GetData is called a lot!
- To retrieve DOs from files
- To retrieve public key information
*/
if (!vgids_parse_apdu_header(s, NULL, NULL, &p1, &p2, &lc, NULL))
return FALSE;
/* free any previous queried data */
vgids_reset_context_response(context);
/* build up file identifier */
fileId = ((UINT16)p1 << 8) | p2;
/* Do we have a DO reference? */
switch (lc)
{
case 4:
{
BYTE tag, length;
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
if (tag != 0x5C && length != 0x02)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
Stream_Read_UINT16_BE(s, doId);
vgids_read_do(context, fileId, doId);
break;
}
case 0xA:
{
UINT16 pubKeyDO;
BYTE tag, length, keyRef;
/* We want to retrieve the public key? */
if (p1 != 0x3F && p2 != 0xFF)
{
status = ISO_STATUS_INVALIDP1P2;
break;
}
/* read parent tag/length */
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
if (tag != 0x70 || length != 0x08)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
/* read key reference TLV */
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
Stream_Read_UINT8(s, keyRef);
if (tag != 0x84 || length != 0x01 || keyRef != VGIDS_DEFAULT_KEY_REF)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
/* read key value template TLV */
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
if (tag != 0xA5 || length != 0x03)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
Stream_Read_UINT16_BE(s, pubKeyDO);
Stream_Read_UINT8(s, length);
if (pubKeyDO != 0x7F49 || length != 0x80)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
if (Stream_GetRemainingLength(s) < 1)
{
status = ISO_STATUS_INVALIDLC;
break;
}
/* Return public key value */
vgids_get_public_key(context, pubKeyDO);
break;
}
default:
status = ISO_STATUS_INVALIDCOMMANDDATA;
break;
}
/* If we have response data, make it ready for return */
if (context->responseData)
status = vgids_handle_chained_response(context, &resultData, &resultDataSize);
else if (status == ISO_STATUS_SUCCESS)
status = ISO_STATUS_REFERENCEDATANOTFOUND;
return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
}
static BOOL vgids_ins_manage_security_environment(vgidsContext* context, wStream* s,
BYTE** response, DWORD* responseSize)
{
BYTE tag, length;
BYTE p1, p2, lc;
DWORD resultDataSize = 0;
const BYTE* resultData = NULL;
UINT16 status = ISO_STATUS_SUCCESS;
vgids_reset_context_command_data(context);
vgids_reset_context_response(context);
/* Manage security environment prepares the card for performing crypto operations. */
if (!vgids_parse_apdu_header(s, NULL, NULL, &p1, &p2, &lc, NULL))
return FALSE;
/* Check APDU params */
/* P1: Set Computation, decipherment, Internal Auth */
/* P2: Digital Signature (B6), Confidentiality (B8) */
if (p1 != 0x41 && p2 != 0xB6 && p2 != 0xB8)
{
status = ISO_STATUS_INVALIDP1P2;
goto create_response;
}
if (lc != 6)
{
status = ISO_STATUS_WRONGLC;
goto create_response;
}
context->currentSE.crt = p2;
/* parse command buffer */
/* Read algo ID */
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
if (tag != 0x80 || length != 0x01)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
goto create_response;
}
Stream_Read_UINT8(s, context->currentSE.algoId);
/* Read private key reference */
Stream_Read_UINT8(s, tag);
Stream_Read_UINT8(s, length);
if (tag != 0x84 || length != 0x01)
{
status = ISO_STATUS_INVALIDCOMMANDDATA;
goto create_response;
}
Stream_Read_UINT8(s, context->currentSE.keyRef);
create_response:
/* If an error occured reset SE */
if (status != ISO_STATUS_SUCCESS)
memset(&context->currentSE, 0, sizeof(context->currentSE));
return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
}
static BOOL vgids_perform_digital_signature(vgidsContext* context)
{
size_t sigSize, msgSize;
EVP_PKEY_CTX* ctx = NULL;
EVP_PKEY* pk = EVP_PKEY_new();
vgidsDigestInfoMap gidsDigestInfo[VGIDS_MAX_DIGEST_INFO] = {
{ g_PKCS1_SHA1, sizeof(g_PKCS1_SHA1), EVP_sha1() },
{ g_PKCS1_SHA224, sizeof(g_PKCS1_SHA224), EVP_sha224() },
{ g_PKCS1_SHA256, sizeof(g_PKCS1_SHA256), EVP_sha256() },
{ g_PKCS1_SHA384, sizeof(g_PKCS1_SHA384), EVP_sha384() },
{ g_PKCS1_SHA512, sizeof(g_PKCS1_SHA512), EVP_sha512() },
{ g_PKCS1_SHA512_224, sizeof(g_PKCS1_SHA512_224), EVP_sha512_224() },
{ g_PKCS1_SHA512_256, sizeof(g_PKCS1_SHA512_256), EVP_sha512_256() }
};
if (!pk)
{
WLog_ERR(TAG, "Failed to create PKEY");
return FALSE;
}
EVP_PKEY_set1_RSA(pk, context->privateKey);
vgids_reset_context_response(context);
/* for each digest info */
Stream_SetPosition(context->commandData, 0);
for (int i = 0; i < VGIDS_MAX_DIGEST_INFO; ++i)
{
/* have we found our digest? */
const vgidsDigestInfoMap* digest = &gidsDigestInfo[i];
if (Stream_Length(context->commandData) >= digest->infoSize &&
memcmp(Stream_Buffer(context->commandData), digest->info, digest->infoSize) == 0)
{
/* skip digest info and calculate message size */
Stream_Seek(context->commandData, digest->infoSize);
if (Stream_GetRemainingLength(context->commandData) <= 1)
goto sign_failed;
msgSize = Stream_GetRemainingLength(context->commandData);
/* setup signing context */
ctx = EVP_PKEY_CTX_new(pk, NULL);
if (!ctx)
{
WLog_ERR(TAG, "Failed to create signing context");
goto sign_failed;
}
if (EVP_PKEY_sign_init(ctx) <= 0)
{
WLog_ERR(TAG, "Failed to init signing context");
goto sign_failed;
}
/* set padding and signature algo */
if (context->currentSE.algoId & VGIDS_SE_ALGOID_DST_PAD_PKCS1)
{
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0)
{
WLog_ERR(TAG, "Failed to set padding mode");
goto sign_failed;
}
}
if (EVP_PKEY_CTX_set_signature_md(ctx, digest->digest) <= 0)
{
WLog_ERR(TAG, "Failed to set signing mode");
goto sign_failed;
}
/* Determine buffer length */
if (EVP_PKEY_sign(ctx, NULL, &sigSize, Stream_Pointer(context->commandData), msgSize) <=
0)
{
WLog_ERR(TAG, "Failed to determine signature size");
goto sign_failed;
}
context->responseData = Stream_New(NULL, sigSize);
if (!context->responseData)
{
WLog_ERR(TAG, "Failed to allocate signing buffer");
goto sign_failed;
}
/* sign */
if (EVP_PKEY_sign(ctx, Stream_Buffer(context->responseData), &sigSize,
Stream_Pointer(context->commandData), msgSize) <= 0)
{
WLog_ERR(TAG, "Failed to create signature");
goto sign_failed;
}
Stream_SetLength(context->responseData, sigSize);
EVP_PKEY_CTX_free(ctx);
break;
}
}
EVP_PKEY_free(pk);
vgids_reset_context_command_data(context);
return TRUE;
sign_failed:
vgids_reset_context_command_data(context);
vgids_reset_context_response(context);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pk);
return FALSE;
}
static BOOL vgids_perform_decrypt(vgidsContext* context)
{
int res;
int padding = RSA_NO_PADDING;
vgids_reset_context_response(context);
/* determine padding */
if (context->currentSE.algoId & VGIDS_SE_ALGOID_CT_PAD_PKCS1)
padding = RSA_PKCS1_PADDING;
else if (context->currentSE.algoId & VGIDS_SE_ALGOID_CT_PAD_OAEP)
padding = RSA_PKCS1_OAEP_PADDING;
/* init response buffer */
context->responseData = Stream_New(NULL, RSA_size(context->privateKey));
if (!context->responseData)
{
WLog_ERR(TAG, "Failed to create decryption buffer");
goto decrypt_failed;
}
/* Determine buffer length */
res = RSA_private_decrypt((int)Stream_Length(context->commandData),
Stream_Buffer(context->commandData),
Stream_Buffer(context->responseData), context->privateKey, padding);
if (res < 0)
{
WLog_ERR(TAG, "Failed to decrypt data");
goto decrypt_failed;
}
Stream_SetLength(context->responseData, res);
vgids_reset_context_command_data(context);
return TRUE;
decrypt_failed:
vgids_reset_context_command_data(context);
vgids_reset_context_response(context);
return FALSE;
}
static BOOL vgids_ins_perform_security_operation(vgidsContext* context, wStream* s, BYTE** response,
DWORD* responseSize)
{
BYTE cla, p1, p2, lc;
DWORD resultDataSize = 0;
const BYTE* resultData = NULL;
UINT16 status = ISO_STATUS_SUCCESS;
/* Perform security operation */
if (!vgids_parse_apdu_header(s, &cla, NULL, &p1, &p2, &lc, NULL))
return FALSE;
if (lc == 0)
{
status = ISO_STATUS_WRONGLC;
goto create_response;
}
/* Is our default key referenced? */
if (context->currentSE.keyRef != VGIDS_DEFAULT_KEY_REF)
{
status = ISO_STATUS_SECURITYSTATUSNOTSATISFIED;
goto create_response;
}
/* is the pin protecting the key verified? */
if (!context->pinVerified)
{
status = ISO_STATUS_SECURITYSTATUSNOTSATISFIED;
goto create_response;
}
/* Append the data to the context command buffer (PSO might chain command data) */
if (!context->commandData)
{
context->commandData = Stream_New(NULL, lc);
if (!context->commandData)
return FALSE;
}
else
Stream_EnsureRemainingCapacity(context->commandData, lc);
Stream_Write(context->commandData, Stream_Pointer(s), lc);
Stream_SealLength(context->commandData);
/* Check if the correct operation is requested for our current SE */
switch (context->currentSE.crt)
{
case VGIDS_SE_CRT_SIGN:
{
if (p1 != 0x9E || p2 != 0x9A)
{
status = ISO_STATUS_INVALIDP1P2;
break;
}
/* If chaining is over perform op */
if (!(cla & 0x10))
vgids_perform_digital_signature(context);
break;
}
case VGIDS_SE_CRT_CONF:
{
if ((p1 != 0x86 || p2 != 0x80) && (p1 != 0x80 || p2 != 0x86))
{
status = ISO_STATUS_INVALIDP1P2;
break;
}
/* If chaining is over perform op */
if (!(cla & 0x10))
vgids_perform_decrypt(context);
break;
}
default:
status = ISO_STATUS_INVALIDP1P2;
break;
}
/* Do chaining of response data if necessary */
if (status == ISO_STATUS_SUCCESS && context->responseData)
status = vgids_handle_chained_response(context, &resultData, &resultDataSize);
/* Check APDU params */
create_response:
return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
}
static BOOL vgids_ins_getresponse(vgidsContext* context, wStream* s, BYTE** response,
DWORD* responseSize)
{
BYTE p1, p2, le;
DWORD resultDataSize = 0;
const BYTE* resultData = NULL;
DWORD expectedLen, remainingSize;
UINT16 status = ISO_STATUS_SUCCESS;
/* Get response continues data transfer after a previous get data command */
/* Check if there is any data to transfer left */
if (!context->responseData || Stream_GetRemainingLength(context->responseData) < 1)
{
status = ISO_STATUS_COMMANDNOTALLOWED;
goto create_response;
}
if (!vgids_parse_apdu_header(s, NULL, NULL, &p1, &p2, NULL, &le))
return FALSE;
/* Check APDU params */
if (p1 != 00 || p2 != 0x00)
{
status = ISO_STATUS_INVALIDP1P2;
goto create_response;
}
/* LE = 0 means 256 bytes expected */
expectedLen = le;
if (expectedLen == 0)
expectedLen = 256;
/* prepare response size and update offset */
remainingSize = (DWORD)Stream_GetRemainingLength(context->responseData);
if (remainingSize < expectedLen)
expectedLen = remainingSize;
resultData = Stream_Pointer(context->responseData);
resultDataSize = expectedLen;
Stream_Seek(context->responseData, expectedLen);
/* If more data is left return 61XX - otherwise 9000 */
remainingSize = (DWORD)Stream_GetRemainingLength(context->responseData);
if (remainingSize > 0)
{
status = ISO_STATUS_MORE_DATA;
if (remainingSize < 256)
status |= (remainingSize & 0xFF);
}
create_response:
return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
}
static BOOL vgids_ins_verify(vgidsContext* context, wStream* s, BYTE** response,
DWORD* responseSize)
{
BYTE ins, p1, p2, lc;
UINT16 status = ISO_STATUS_SUCCESS;
char pin[VGIDS_MAX_PIN_SIZE + 1] = { 0 };
/* Verify is always called for the application password (PIN) P2=0x80 */
if (!vgids_parse_apdu_header(s, NULL, &ins, &p1, &p2, NULL, NULL))
return FALSE;
/* Check APDU params */
if (p1 != 00 && p2 != 0x80 && p2 != 0x82)
{
status = ISO_STATUS_INVALIDP1P2;
goto create_response;
}
/* shall we reset the security state? */
if (p2 == 0x82)
{
context->pinVerified = FALSE;
goto create_response;
}
/* Check if pin is not already blocked */
if (context->curRetryCounter == 0)
{
status = ISO_STATUS_AUTHMETHODBLOCKED;
goto create_response;
}
/* Read and verify LC */
if (Stream_GetRemainingLength(s) < 1)
{
status = ISO_STATUS_INVALIDLC;
goto create_response;
}
Stream_Read_UINT8(s, lc);
if (Stream_GetRemainingLength(s) < lc || lc > VGIDS_MAX_PIN_SIZE)
{
status = ISO_STATUS_INVALIDLC;
goto create_response;
}
/* read and verify pin */
Stream_Read(s, pin, lc);
if (strcmp(context->pin, pin) != 0)
{
/* retries are encoded in the lowest 4-bit of the status code */
--context->curRetryCounter;
context->pinVerified = FALSE;
status = (ISO_STATUS_VERIFYFAILED | (context->curRetryCounter & 0xFF));
}
else
{
/* reset retry counter and mark pin as verified */
context->curRetryCounter = context->retryCounter;
context->pinVerified = TRUE;
}
create_response:
return vgids_create_response(status, NULL, 0, response, responseSize);
}
vgidsContext* vgids_new()
{
wObject* obj;
vgidsContext* ctx = calloc(1, sizeof(vgidsContext));
ctx->files = ArrayList_New(FALSE);
if (!ctx->files)
{
WLog_ERR(TAG, "Failed to create files array list");
goto create_failed;
}
obj = ArrayList_Object(ctx->files);
obj->fnObjectFree = vgids_ef_free;
return ctx;
create_failed:
vgids_free(ctx);
return NULL;
}
BOOL vgids_init(vgidsContext* ctx, const char* cert, const char* privateKey, const char* pin)
{
DWORD kxcSize;
DWORD keymapSize;
DWORD fsTableSize;
BOOL rc = FALSE;
BIO* certBio = NULL;
BIO* privateKeyBio = NULL;
BYTE* kxc = NULL;
BYTE* keymap = NULL;
BYTE* fsTable = NULL;
EVP_PKEY* pubKey = NULL;
vgidsEF* masterEF = NULL;
vgidsEF* cardidEF = NULL;
vgidsEF* commonEF = NULL;
BYTE cardid[VGIDS_CARDID_SIZE] = { 0 };
vgidsContainerMapEntry cmrec = { { 'P', 'r', 'i', 'v', 'a', 't', 'e', ' ', 'K', 'e', 'y', ' ',
'0', '0' },
CONTAINER_MAP_VALID_CONTAINER |
CONTAINER_MAP_DEFAULT_CONTAINER,
0,
0,
0x00 /* key-size in bits - filled out later */ };
vgidsFilesysTableEntry filesys[] = {
{ "mscp", "", 0, 0, 0, 0xA000, 0 },
{ "", "cardid", 0, 0xDF20, 0, 0xA012, 0 },
{ "", "cardapps", 0, 0xDF21, 0, 0xA010, 0 },
{ "", "cardcf", 0, 0xDF22, 0, 0xA010, 0 },
{ "mscp", "cmapfile", 0, 0xDF23, 0, 0xA010, 0 },
{ "mscp", "kxc00", 0, 0xDF24, 0, 0xA010, 0 },
};
/* Check params */
if (!cert || !privateKey || !pin)
{
WLog_ERR(TAG, "Passed invalid NULL pointer argument");
goto init_failed;
}
/* Convert PEM input to DER certificate/public key/private key */
certBio = BIO_new_mem_buf((const void*)cert, (int)strlen(cert));
if (!certBio)
goto init_failed;
ctx->certificate = PEM_read_bio_X509(certBio, NULL, NULL, NULL);
if (!ctx->certificate)
goto init_failed;
pubKey = X509_get_pubkey(ctx->certificate);
if (!pubKey)
goto init_failed;
ctx->publicKey = EVP_PKEY_get1_RSA(pubKey);
if (!ctx->publicKey)
goto init_failed;
privateKeyBio = BIO_new_mem_buf((const void*)privateKey, (int)strlen(privateKey));
if (!privateKeyBio)
goto init_failed;
ctx->privateKey = PEM_read_bio_RSAPrivateKey(privateKeyBio, NULL, NULL, NULL);
if (!ctx->privateKey)
goto init_failed;
/* create masterfile */
masterEF = vgids_ef_new(ctx, VGIDS_EFID_MASTER);
if (!masterEF)
goto init_failed;
/* create cardid file with cardid DO */
cardidEF = vgids_ef_new(ctx, VGIDS_EFID_CARDID);
if (!cardidEF)
goto init_failed;
RAND_bytes(cardid, sizeof(cardid));
if (!vgids_ef_write_do(cardidEF, VGIDS_DO_CARDID, cardid, sizeof(cardid)))
goto init_failed;
/* create user common file */
commonEF = vgids_ef_new(ctx, VGIDS_EFID_COMMON);
if (!commonEF)
goto init_failed;
/* write card cache DO */
if (!vgids_ef_write_do(commonEF, VGIDS_DO_CARDCF, g_CardCFContents, sizeof(g_CardCFContents)))
goto init_failed;
/* write container map DO */
cmrec.wKeyExchangeKeySizeBits = (WORD)(RSA_size(ctx->privateKey) * 8);
if (!vgids_ef_write_do(commonEF, VGIDS_DO_CMAPFILE, (BYTE*)&cmrec, sizeof(cmrec)))
goto init_failed;
/* write cardapps DO */
if (!vgids_ef_write_do(commonEF, VGIDS_DO_CARDAPPS, g_CardAppsContents,
sizeof(g_CardAppsContents)))
goto init_failed;
/* convert and write certificate to key exchange container */
if (!vgids_prepare_certificate(ctx->certificate, &kxc, &kxcSize))
goto init_failed;
if (!vgids_ef_write_do(commonEF, VGIDS_DO_KXC00, kxc, kxcSize))
goto init_failed;
/* prepare and write file system table */
if (!vgids_prepare_fstable(filesys, ARRAYSIZE(filesys), &fsTable, &fsTableSize))
goto init_failed;
if (!vgids_ef_write_do(masterEF, VGIDS_DO_FILESYSTEMTABLE, fsTable, fsTableSize))
goto init_failed;
/* vgids_prepare_keymap and write to masterEF */
if (!vgids_prepare_keymap(ctx, &keymap, &keymapSize))
goto init_failed;
if (!vgids_ef_write_do(masterEF, VGIDS_DO_KEYMAP, keymap, keymapSize))
goto init_failed;
/* store user pin */
ctx->curRetryCounter = ctx->retryCounter = VGIDS_DEFAULT_RETRY_COUNTER;
ctx->pin = _strdup(pin);
if (!ctx->pin)
goto init_failed;
rc = TRUE;
init_failed:
EVP_PKEY_free(pubKey);
BIO_free_all(certBio);
BIO_free_all(privateKeyBio);
free(kxc);
free(keymap);
free(fsTable);
return rc;
}
BOOL vgids_process_apdu(vgidsContext* context, const BYTE* data, DWORD dataSize, BYTE** response,
DWORD* responseSize)
{
wStream s;
static int x = 1;
/* Check params */
if (!context || !data || !response || !responseSize)
{
WLog_ERR(TAG, "Invalid NULL pointer passed");
return FALSE;
}
if (dataSize < 4)
{
WLog_ERR(TAG, "APDU buffer is less than 4 bytes: %" PRIu32, dataSize);
return FALSE;
}
/* Examine INS byte */
Stream_StaticConstInit(&s, data, dataSize);
if (x++ == 0xe)
x = 0xe + 1;
switch (data[1])
{
case ISO_INS_SELECT:
return vgids_ins_select(context, &s, response, responseSize);
case ISO_INS_GETDATA:
return vgids_ins_getdata(context, &s, response, responseSize);
case ISO_INS_GETRESPONSE:
return vgids_ins_getresponse(context, &s, response, responseSize);
case ISO_INS_MSE:
return vgids_ins_manage_security_environment(context, &s, response, responseSize);
case ISO_INS_PSO:
return vgids_ins_perform_security_operation(context, &s, response, responseSize);
case ISO_INS_VERIFY:
return vgids_ins_verify(context, &s, response, responseSize);
default:
break;
}
/* return command not allowed */
return vgids_create_response(ISO_STATUS_COMMANDNOTALLOWED, NULL, 0, response, responseSize);
}
void vgids_free(vgidsContext* context)
{
if (context)
{
RSA_free(context->privateKey);
RSA_free(context->publicKey);
X509_free(context->certificate);
Stream_Free(context->commandData, TRUE);
Stream_Free(context->responseData, TRUE);
free(context->pin);
ArrayList_Free(context->files);
free(context);
}
}
|
286969.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<arpa/inet.h>
#include"include/lunetta.h"
#include"include/pkt_io.h"
#include"include/ethernet.h"
#include"include/ip.h"
void print_ip_addr(uint32_t *addr) {
uint8_t *ad;
ad = (uint8_t *)addr;
printf("%u.%u.%u.%u\n", *ad, *(ad + 1), *(ad + 2), *(ad + 3));
return;
}
void print_ip_hdr(struct ip_hdr *ip_hdr) {
printf("version: %u\n", ip_hdr->version);
printf("header length: %u (%d byte)\n", ip_hdr->hdr_len, ip_hdr->hdr_len * 4);
printf("type of service: %u\n",ip_hdr->type_of_service);
printf("total length: %u\n", ntohs(ip_hdr->total_len));
printf("identification: 0x%x\n", ntohs(ip_hdr->id));
printf("Time to Live: %u\n", ip_hdr->ttl);
printf("proto: %x\n", ip_hdr->proto);
//printf("Source IP Address: %s\n", inet_ntoa(ip_hdr->src_addr));
//printf("Destination IP Address: %s\n", inet_ntoa(ip_hdr->dest_addr));
printf("src ip: ");
print_ip_addr(&ip_hdr->src_addr);
printf("dest ip: ");
print_ip_addr(&ip_hdr->dest_addr);
//printf("src ip: %x\n", ip_hdr->src_addr);
//printf("dest ip: %x\n", ip_hdr->dest_addr);
return;
}
void rx_ip(uint8_t *packet, uint32_t size, struct port_config *port) {
struct ip_hdr *p = (struct ip_hdr *)packet;
print_ip_hdr(p);
// printf("version: %u\n", p->version);
// printf("header length: %u (%d byte)\n", p->hdr_len, p->hdr_len * 4);
// printf("type of service: %u\n",p->type_of_service);
// printf("total length: %u\n", ntohs(p->total_len));
// printf("identification: 0x%x\n", ntohs(p->id));
// printf("Time to Live: %u\n", p->ttl);
// printf("proto: %x\n", p->proto);
return;
}
|
51650.c |
/* @(#)k_rem_pio2.c 1.3 95/01/18 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* __kernel_rem_pio2(x,y,e0,nx,prec,ipio2)
* double x[],y[]; int e0,nx,prec; int ipio2[];
*
* __kernel_rem_pio2 return the last three digits of N with
* y = x - N*pi/2
* so that |y| < pi/2.
*
* The method is to compute the integer (mod 8) and fraction parts of
* (2/pi)*x without doing the full multiplication. In general we
* skip the part of the product that are known to be a huge integer (
* more accurately, = 0 mod 8 ). Thus the number of operations are
* independent of the exponent of the input.
*
* (2/pi) is represented by an array of 24-bit integers in ipio2[].
*
* Input parameters:
* x[] The input value (must be positive) is broken into nx
* pieces of 24-bit integers in double precision format.
* x[i] will be the i-th 24 bit of x. The scaled exponent
* of x[0] is given in input parameter e0 (i.e., x[0]*2^e0
* match x's up to 24 bits.
*
* Example of breaking a double positive z into x[0]+x[1]+x[2]:
* e0 = ilogb(z)-23
* z = scalbn(z,-e0)
* for i = 0,1,2
* x[i] = floor(z)
* z = (z-x[i])*2**24
*
*
* y[] ouput result in an array of double precision numbers.
* The dimension of y[] is:
* 24-bit precision 1
* 53-bit precision 2
* 64-bit precision 2
* 113-bit precision 3
* The actual value is the sum of them. Thus for 113-bit
* precison, one may have to do something like:
*
* long double t,w,r_head, r_tail;
* t = (long double)y[2] + (long double)y[1];
* w = (long double)y[0];
* r_head = t+w;
* r_tail = w - (r_head - t);
*
* e0 The exponent of x[0]
*
* nx dimension of x[]
*
* prec an integer indicating the precision:
* 0 24 bits (single)
* 1 53 bits (double)
* 2 64 bits (extended)
* 3 113 bits (quad)
*
* ipio2[]
* integer array, contains the (24*i)-th to (24*i+23)-th
* bit of 2/pi after binary point. The corresponding
* floating value is
*
* ipio2[i] * 2^(-24(i+1)).
*
* External function:
* double scalbn(), floor();
*
*
* Here is the description of some local variables:
*
* jk jk+1 is the initial number of terms of ipio2[] needed
* in the computation. The recommended value is 2,3,4,
* 6 for single, double, extended,and quad.
*
* jz local integer variable indicating the number of
* terms of ipio2[] used.
*
* jx nx - 1
*
* jv index for pointing to the suitable ipio2[] for the
* computation. In general, we want
* ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8
* is an integer. Thus
* e0-3-24*jv >= 0 or (e0-3)/24 >= jv
* Hence jv = max(0,(e0-3)/24).
*
* jp jp+1 is the number of terms in PIo2[] needed, jp = jk.
*
* q[] double array with integral value, representing the
* 24-bits chunk of the product of x and 2/pi.
*
* q0 the corresponding exponent of q[0]. Note that the
* exponent for q[i] would be q0-24*i.
*
* PIo2[] double precision array, obtained by cutting pi/2
* into 24 bits chunks.
*
* f[] ipio2[] in floating point
*
* iq[] integer array by breaking up q[] in 24-bits chunk.
*
* fq[] final product of x*(2/pi) in fq[0],..,fq[jk]
*
* ih integer. If >0 it indicates q[] is >= 0.5, hence
* it also indicates the *sign* of the result.
*
*/
/*
* Constants:
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include "math.h"
#ifdef __STDC__
static const int init_jk[] = {2,3,4,6}; /* initial value for jk */
#else
static int init_jk[] = {2,3,4,6};
#endif
#ifdef __STDC__
static const double PIo2[] = {
#else
static double PIo2[] = {
#endif
1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */
7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */
5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */
3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */
1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */
1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */
2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */
2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */
};
#ifdef __STDC__
static const double
#else
static double
#endif
zero = 0.0,
one = 1.0,
two24 = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */
twon24 = 5.96046447753906250000e-08; /* 0x3E700000, 0x00000000 */
#ifdef __STDC__
int __kernel_rem_pio2(double *x, double *y, int e0, int nx, int prec, const int *ipio2)
#else
int __kernel_rem_pio2(x,y,e0,nx,prec,ipio2)
double x[], y[]; int e0,nx,prec; int ipio2[];
#endif
{
int jz,jx,jv,jp,jk,carry,n,iq[20],i,j,k,m,q0,ih;
double z,fw,f[20],fq[20],q[20];
/* initialize jk*/
jk = init_jk[prec];
jp = jk;
/* determine jx,jv,q0, note that 3>q0 */
jx = nx-1;
jv = (e0-3)/24; if(jv<0) jv=0;
q0 = e0-24*(jv+1);
/* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */
j = jv-jx; m = jx+jk;
for(i=0;i<=m;i++,j++) f[i] = (j<0)? zero : (double) ipio2[j];
/* compute q[0],q[1],...q[jk] */
for (i=0;i<=jk;i++) {
for(j=0,fw=0.0;j<=jx;j++) fw += x[j]*f[jx+i-j]; q[i] = fw;
}
jz = jk;
recompute:
/* distill q[] into iq[] reversingly */
for(i=0,j=jz,z=q[jz];j>0;i++,j--) {
fw = (double)((int)(twon24* z));
iq[i] = (int)(z-two24*fw);
z = q[j-1]+fw;
}
/* compute n */
z = scalbn(z,q0); /* actual value of z */
z -= 8.0*floor(z*0.125); /* trim off integer >= 8 */
n = (int) z;
z -= (double)n;
ih = 0;
if(q0>0) { /* need iq[jz-1] to determine n */
i = (iq[jz-1]>>(24-q0)); n += i;
iq[jz-1] -= i<<(24-q0);
ih = iq[jz-1]>>(23-q0);
}
else if(q0==0) ih = iq[jz-1]>>23;
else if(z>=0.5) ih=2;
if(ih>0) { /* q > 0.5 */
n += 1; carry = 0;
for(i=0;i<jz ;i++) { /* compute 1-q */
j = iq[i];
if(carry==0) {
if(j!=0) {
carry = 1; iq[i] = 0x1000000- j;
}
} else iq[i] = 0xffffff - j;
}
if(q0>0) { /* rare case: chance is 1 in 12 */
switch(q0) {
case 1:
iq[jz-1] &= 0x7fffff; break;
case 2:
iq[jz-1] &= 0x3fffff; break;
}
}
if(ih==2) {
z = one - z;
if(carry!=0) z -= scalbn(one,q0);
}
}
/* check if recomputation is needed */
if(z==zero) {
j = 0;
for (i=jz-1;i>=jk;i--) j |= iq[i];
if(j==0) { /* need recomputation */
for(k=1;iq[jk-k]==0;k++); /* k = no. of terms needed */
for(i=jz+1;i<=jz+k;i++) { /* add q[jz+1] to q[jz+k] */
f[jx+i] = (double) ipio2[jv+i];
for(j=0,fw=0.0;j<=jx;j++) fw += x[j]*f[jx+i-j];
q[i] = fw;
}
jz += k;
goto recompute;
}
}
/* chop off zero terms */
if(z==0.0) {
jz -= 1; q0 -= 24;
while(iq[jz]==0) { jz--; q0-=24;}
} else { /* break z into 24-bit if necessary */
z = scalbn(z,-q0);
if(z>=two24) {
fw = (double)((int)(twon24*z));
iq[jz] = (int)(z-two24*fw);
jz += 1; q0 += 24;
iq[jz] = (int) fw;
} else iq[jz] = (int) z ;
}
/* convert integer "bit" chunk to floating-point value */
fw = scalbn(one,q0);
for(i=jz;i>=0;i--) {
q[i] = fw*(double)iq[i]; fw*=twon24;
}
/* compute PIo2[0,...,jp]*q[jz,...,0] */
for(i=jz;i>=0;i--) {
for(fw=0.0,k=0;k<=jp&&k<=jz-i;k++) fw += PIo2[k]*q[i+k];
fq[jz-i] = fw;
}
/* compress fq[] into y[] */
switch(prec) {
case 0:
fw = 0.0;
for (i=jz;i>=0;i--) fw += fq[i];
y[0] = (ih==0)? fw: -fw;
break;
case 1:
case 2:
fw = 0.0;
for (i=jz;i>=0;i--) fw += fq[i];
y[0] = (ih==0)? fw: -fw;
fw = fq[0]-fw;
for (i=1;i<=jz;i++) fw += fq[i];
y[1] = (ih==0)? fw: -fw;
break;
case 3: /* painful */
for (i=jz;i>0;i--) {
fw = fq[i-1]+fq[i];
fq[i] += fq[i-1]-fw;
fq[i-1] = fw;
}
for (i=jz;i>1;i--) {
fw = fq[i-1]+fq[i];
fq[i] += fq[i-1]-fw;
fq[i-1] = fw;
}
for (fw=0.0,i=jz;i>=2;i--) fw += fq[i];
if(ih==0) {
y[0] = fq[0]; y[1] = fq[1]; y[2] = fw;
} else {
y[0] = -fq[0]; y[1] = -fq[1]; y[2] = -fw;
}
}
return n&7;
}
|
526620.c | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
*
* Copyright (C) 1997 University of Chicago.
* See COPYRIGHT notice in top-level directory.
*/
#include "ad_xfs.h"
#include "adio_extern.h"
#include <sys/ioctl.h>
#ifndef HAVE_LSEEK64
#define lseek64 lseek
#endif
void ADIOI_XFS_Fcntl(ADIO_File fd, int flag, ADIO_Fcntl_t * fcntl_struct, int *error_code)
{
int i, err;
#if defined(LINUX) && defined(MPISGI)
struct xfs_flock64 fl;
#else
struct flock64 fl;
#endif
static char myname[] = "ADIOI_XFS_FCNTL";
switch (flag) {
case ADIO_FCNTL_GET_FSIZE:
fcntl_struct->fsize = lseek64(fd->fd_sys, 0, SEEK_END);
if (fcntl_struct->fsize == -1) {
*error_code = MPIO_Err_create_code(MPI_SUCCESS,
MPIR_ERR_RECOVERABLE, myname,
__LINE__, MPI_ERR_IO, "**io",
"**io %s", strerror(errno));
} else
*error_code = MPI_SUCCESS;
break;
case ADIO_FCNTL_SET_DISKSPACE:
i = 0;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = fcntl_struct->diskspace;
#if defined(LINUX) && defined(MPISGI)
err = ioctl(fd->fd_sys, XFS_IOC_RESVSP64, &fl);
#else
err = fcntl(fd->fd_sys, F_RESVSP64, &fl);
#endif
if (err)
i = 1;
if (fcntl_struct->diskspace > lseek64(fd->fd_sys, 0, SEEK_END)) {
/* also need to set the file size */
err = ftruncate64(fd->fd_sys, fcntl_struct->diskspace);
if (err)
i = 1;
}
if (i == 1) {
*error_code = MPIO_Err_create_code(MPI_SUCCESS,
MPIR_ERR_RECOVERABLE, myname,
__LINE__, MPI_ERR_IO, "**io",
"**io %s", strerror(errno));
} else
*error_code = MPI_SUCCESS;
break;
case ADIO_FCNTL_SET_ATOMICITY:
fd->atomicity = (fcntl_struct->atomicity == 0) ? 0 : 1;
*error_code = MPI_SUCCESS;
break;
default:
/* --BEGIN ERROR HANDLING-- */
*error_code = MPIO_Err_create_code(MPI_SUCCESS,
MPIR_ERR_RECOVERABLE,
myname, __LINE__,
MPI_ERR_ARG, "**flag", "**flag %d", flag);
return;
/* --END ERROR HANDLING-- */
}
}
|
766472.c | /* Return true if the process can perform a chroot operation.
Copyright (C) 2017-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <errno.h>
#include <stdio.h>
#include <support/check.h>
#include <support/namespace.h>
#include <support/support.h>
#include <support/xunistd.h>
#include <sys/stat.h>
#include <unistd.h>
static void
callback (void *closure)
{
int *result = closure;
struct stat64 before;
xstat ("/dev", &before);
if (chroot ("/dev") != 0)
{
*result = errno;
return;
}
struct stat64 after;
xstat ("/", &after);
TEST_VERIFY (before.st_dev == after.st_dev);
TEST_VERIFY (before.st_ino == after.st_ino);
*result = 0;
}
bool
support_can_chroot (void)
{
int *result = support_shared_allocate (sizeof (*result));
*result = 0;
support_isolate_in_subprocess (callback, result);
bool ok = *result == 0;
if (!ok)
{
static bool already_warned;
if (!already_warned)
{
already_warned = true;
errno = *result;
printf ("warning: this process does not support chroot: %m\n");
}
}
support_shared_free (result);
return ok;
}
|
852496.c | // SPDX-License-Identifier: GPL-2.0
/* sunvnet.c: Sun LDOM Virtual Network Driver.
*
* Copyright (C) 2007, 2008 David S. Miller <[email protected]>
* Copyright (C) 2016-2017 Oracle. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/etherdevice.h>
#include <linux/mutex.h>
#include <linux/highmem.h>
#include <linux/if_vlan.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/icmpv6.h>
#endif
#include <net/ip.h>
#include <net/icmp.h>
#include <net/route.h>
#include <asm/vio.h>
#include <asm/ldc.h>
#include "sunvnet_common.h"
/* length of time before we decide the hardware is borked,
* and dev->tx_timeout() should be called to fix the problem
*/
#define VNET_TX_TIMEOUT (5 * HZ)
#define DRV_MODULE_NAME "sunvnet"
#define DRV_MODULE_VERSION "2.0"
#define DRV_MODULE_RELDATE "February 3, 2017"
static char version[] =
DRV_MODULE_NAME " " DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")";
MODULE_AUTHOR("David S. Miller ([email protected])");
MODULE_DESCRIPTION("Sun LDOM virtual network driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
/* Ordered from largest major to lowest */
static struct vio_version vnet_versions[] = {
{ .major = 1, .minor = 8 },
{ .major = 1, .minor = 7 },
{ .major = 1, .minor = 6 },
{ .major = 1, .minor = 0 },
};
static void vnet_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version));
}
static u32 vnet_get_msglevel(struct net_device *dev)
{
struct vnet *vp = netdev_priv(dev);
return vp->msg_enable;
}
static void vnet_set_msglevel(struct net_device *dev, u32 value)
{
struct vnet *vp = netdev_priv(dev);
vp->msg_enable = value;
}
static const struct {
const char string[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "rx_packets" },
{ "tx_packets" },
{ "rx_bytes" },
{ "tx_bytes" },
{ "rx_errors" },
{ "tx_errors" },
{ "rx_dropped" },
{ "tx_dropped" },
{ "multicast" },
{ "rx_length_errors" },
{ "rx_frame_errors" },
{ "rx_missed_errors" },
{ "tx_carrier_errors" },
{ "nports" },
};
static int vnet_get_sset_count(struct net_device *dev, int sset)
{
struct vnet *vp = (struct vnet *)netdev_priv(dev);
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(ethtool_stats_keys)
+ (NUM_VNET_PORT_STATS * vp->nports);
default:
return -EOPNOTSUPP;
}
}
static void vnet_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
struct vnet *vp = (struct vnet *)netdev_priv(dev);
struct vnet_port *port;
char *p = (char *)buf;
switch (stringset) {
case ETH_SS_STATS:
memcpy(buf, ðtool_stats_keys, sizeof(ethtool_stats_keys));
p += sizeof(ethtool_stats_keys);
rcu_read_lock();
list_for_each_entry_rcu(port, &vp->port_list, list) {
snprintf(p, ETH_GSTRING_LEN, "p%u.%s-%pM",
port->q_index, port->switch_port ? "s" : "q",
port->raddr);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.rx_packets",
port->q_index);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.tx_packets",
port->q_index);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.rx_bytes",
port->q_index);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.tx_bytes",
port->q_index);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.event_up",
port->q_index);
p += ETH_GSTRING_LEN;
snprintf(p, ETH_GSTRING_LEN, "p%u.event_reset",
port->q_index);
p += ETH_GSTRING_LEN;
}
rcu_read_unlock();
break;
default:
WARN_ON(1);
break;
}
}
static void vnet_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *estats, u64 *data)
{
struct vnet *vp = (struct vnet *)netdev_priv(dev);
struct vnet_port *port;
int i = 0;
data[i++] = dev->stats.rx_packets;
data[i++] = dev->stats.tx_packets;
data[i++] = dev->stats.rx_bytes;
data[i++] = dev->stats.tx_bytes;
data[i++] = dev->stats.rx_errors;
data[i++] = dev->stats.tx_errors;
data[i++] = dev->stats.rx_dropped;
data[i++] = dev->stats.tx_dropped;
data[i++] = dev->stats.multicast;
data[i++] = dev->stats.rx_length_errors;
data[i++] = dev->stats.rx_frame_errors;
data[i++] = dev->stats.rx_missed_errors;
data[i++] = dev->stats.tx_carrier_errors;
data[i++] = vp->nports;
rcu_read_lock();
list_for_each_entry_rcu(port, &vp->port_list, list) {
data[i++] = port->q_index;
data[i++] = port->stats.rx_packets;
data[i++] = port->stats.tx_packets;
data[i++] = port->stats.rx_bytes;
data[i++] = port->stats.tx_bytes;
data[i++] = port->stats.event_up;
data[i++] = port->stats.event_reset;
}
rcu_read_unlock();
}
static const struct ethtool_ops vnet_ethtool_ops = {
.get_drvinfo = vnet_get_drvinfo,
.get_msglevel = vnet_get_msglevel,
.set_msglevel = vnet_set_msglevel,
.get_link = ethtool_op_get_link,
.get_sset_count = vnet_get_sset_count,
.get_strings = vnet_get_strings,
.get_ethtool_stats = vnet_get_ethtool_stats,
};
static LIST_HEAD(vnet_list);
static DEFINE_MUTEX(vnet_list_mutex);
static struct vnet_port *__tx_port_find(struct vnet *vp, struct sk_buff *skb)
{
unsigned int hash = vnet_hashfn(skb->data);
struct hlist_head *hp = &vp->port_hash[hash];
struct vnet_port *port;
hlist_for_each_entry_rcu(port, hp, hash) {
if (!sunvnet_port_is_up_common(port))
continue;
if (ether_addr_equal(port->raddr, skb->data))
return port;
}
list_for_each_entry_rcu(port, &vp->port_list, list) {
if (!port->switch_port)
continue;
if (!sunvnet_port_is_up_common(port))
continue;
return port;
}
return NULL;
}
/* func arg to vnet_start_xmit_common() to get the proper tx port */
static struct vnet_port *vnet_tx_port_find(struct sk_buff *skb,
struct net_device *dev)
{
struct vnet *vp = netdev_priv(dev);
return __tx_port_find(vp, skb);
}
static u16 vnet_select_queue(struct net_device *dev, struct sk_buff *skb,
struct net_device *sb_dev,
select_queue_fallback_t fallback)
{
struct vnet *vp = netdev_priv(dev);
struct vnet_port *port = __tx_port_find(vp, skb);
if (!port)
return 0;
return port->q_index;
}
/* Wrappers to common functions */
static int vnet_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
return sunvnet_start_xmit_common(skb, dev, vnet_tx_port_find);
}
static void vnet_set_rx_mode(struct net_device *dev)
{
struct vnet *vp = netdev_priv(dev);
return sunvnet_set_rx_mode_common(dev, vp);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void vnet_poll_controller(struct net_device *dev)
{
struct vnet *vp = netdev_priv(dev);
return sunvnet_poll_controller_common(dev, vp);
}
#endif
static const struct net_device_ops vnet_ops = {
.ndo_open = sunvnet_open_common,
.ndo_stop = sunvnet_close_common,
.ndo_set_rx_mode = vnet_set_rx_mode,
.ndo_set_mac_address = sunvnet_set_mac_addr_common,
.ndo_validate_addr = eth_validate_addr,
.ndo_tx_timeout = sunvnet_tx_timeout_common,
.ndo_start_xmit = vnet_start_xmit,
.ndo_select_queue = vnet_select_queue,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = vnet_poll_controller,
#endif
};
static struct vnet *vnet_new(const u64 *local_mac,
struct vio_dev *vdev)
{
struct net_device *dev;
struct vnet *vp;
int err, i;
dev = alloc_etherdev_mqs(sizeof(*vp), VNET_MAX_TXQS, 1);
if (!dev)
return ERR_PTR(-ENOMEM);
dev->needed_headroom = VNET_PACKET_SKIP + 8;
dev->needed_tailroom = 8;
for (i = 0; i < ETH_ALEN; i++)
dev->dev_addr[i] = (*local_mac >> (5 - i) * 8) & 0xff;
vp = netdev_priv(dev);
spin_lock_init(&vp->lock);
vp->dev = dev;
INIT_LIST_HEAD(&vp->port_list);
for (i = 0; i < VNET_PORT_HASH_SIZE; i++)
INIT_HLIST_HEAD(&vp->port_hash[i]);
INIT_LIST_HEAD(&vp->list);
vp->local_mac = *local_mac;
dev->netdev_ops = &vnet_ops;
dev->ethtool_ops = &vnet_ethtool_ops;
dev->watchdog_timeo = VNET_TX_TIMEOUT;
dev->hw_features = NETIF_F_TSO | NETIF_F_GSO | NETIF_F_ALL_TSO |
NETIF_F_HW_CSUM | NETIF_F_SG;
dev->features = dev->hw_features;
/* MTU range: 68 - 65535 */
dev->min_mtu = ETH_MIN_MTU;
dev->max_mtu = VNET_MAX_MTU;
SET_NETDEV_DEV(dev, &vdev->dev);
err = register_netdev(dev);
if (err) {
pr_err("Cannot register net device, aborting\n");
goto err_out_free_dev;
}
netdev_info(dev, "Sun LDOM vnet %pM\n", dev->dev_addr);
list_add(&vp->list, &vnet_list);
return vp;
err_out_free_dev:
free_netdev(dev);
return ERR_PTR(err);
}
static struct vnet *vnet_find_or_create(const u64 *local_mac,
struct vio_dev *vdev)
{
struct vnet *iter, *vp;
mutex_lock(&vnet_list_mutex);
vp = NULL;
list_for_each_entry(iter, &vnet_list, list) {
if (iter->local_mac == *local_mac) {
vp = iter;
break;
}
}
if (!vp)
vp = vnet_new(local_mac, vdev);
mutex_unlock(&vnet_list_mutex);
return vp;
}
static void vnet_cleanup(void)
{
struct vnet *vp;
struct net_device *dev;
mutex_lock(&vnet_list_mutex);
while (!list_empty(&vnet_list)) {
vp = list_first_entry(&vnet_list, struct vnet, list);
list_del(&vp->list);
dev = vp->dev;
/* vio_unregister_driver() should have cleaned up port_list */
BUG_ON(!list_empty(&vp->port_list));
unregister_netdev(dev);
free_netdev(dev);
}
mutex_unlock(&vnet_list_mutex);
}
static const char *local_mac_prop = "local-mac-address";
static struct vnet *vnet_find_parent(struct mdesc_handle *hp,
u64 port_node,
struct vio_dev *vdev)
{
const u64 *local_mac = NULL;
u64 a;
mdesc_for_each_arc(a, hp, port_node, MDESC_ARC_TYPE_BACK) {
u64 target = mdesc_arc_target(hp, a);
const char *name;
name = mdesc_get_property(hp, target, "name", NULL);
if (!name || strcmp(name, "network"))
continue;
local_mac = mdesc_get_property(hp, target,
local_mac_prop, NULL);
if (local_mac)
break;
}
if (!local_mac)
return ERR_PTR(-ENODEV);
return vnet_find_or_create(local_mac, vdev);
}
static struct ldc_channel_config vnet_ldc_cfg = {
.event = sunvnet_event_common,
.mtu = 64,
.mode = LDC_MODE_UNRELIABLE,
};
static struct vio_driver_ops vnet_vio_ops = {
.send_attr = sunvnet_send_attr_common,
.handle_attr = sunvnet_handle_attr_common,
.handshake_complete = sunvnet_handshake_complete_common,
};
const char *remote_macaddr_prop = "remote-mac-address";
static int vnet_port_probe(struct vio_dev *vdev, const struct vio_device_id *id)
{
struct mdesc_handle *hp;
struct vnet_port *port;
unsigned long flags;
struct vnet *vp;
const u64 *rmac;
int len, i, err, switch_port;
hp = mdesc_grab();
vp = vnet_find_parent(hp, vdev->mp, vdev);
if (IS_ERR(vp)) {
pr_err("Cannot find port parent vnet\n");
err = PTR_ERR(vp);
goto err_out_put_mdesc;
}
rmac = mdesc_get_property(hp, vdev->mp, remote_macaddr_prop, &len);
err = -ENODEV;
if (!rmac) {
pr_err("Port lacks %s property\n", remote_macaddr_prop);
goto err_out_put_mdesc;
}
port = kzalloc(sizeof(*port), GFP_KERNEL);
err = -ENOMEM;
if (!port)
goto err_out_put_mdesc;
for (i = 0; i < ETH_ALEN; i++)
port->raddr[i] = (*rmac >> (5 - i) * 8) & 0xff;
port->vp = vp;
err = vio_driver_init(&port->vio, vdev, VDEV_NETWORK,
vnet_versions, ARRAY_SIZE(vnet_versions),
&vnet_vio_ops, vp->dev->name);
if (err)
goto err_out_free_port;
err = vio_ldc_alloc(&port->vio, &vnet_ldc_cfg, port);
if (err)
goto err_out_free_port;
netif_napi_add(port->vp->dev, &port->napi, sunvnet_poll_common,
NAPI_POLL_WEIGHT);
INIT_HLIST_NODE(&port->hash);
INIT_LIST_HEAD(&port->list);
switch_port = 0;
if (mdesc_get_property(hp, vdev->mp, "switch-port", NULL))
switch_port = 1;
port->switch_port = switch_port;
port->tso = true;
port->tsolen = 0;
spin_lock_irqsave(&vp->lock, flags);
if (switch_port)
list_add_rcu(&port->list, &vp->port_list);
else
list_add_tail_rcu(&port->list, &vp->port_list);
hlist_add_head_rcu(&port->hash,
&vp->port_hash[vnet_hashfn(port->raddr)]);
sunvnet_port_add_txq_common(port);
spin_unlock_irqrestore(&vp->lock, flags);
dev_set_drvdata(&vdev->dev, port);
pr_info("%s: PORT ( remote-mac %pM%s )\n",
vp->dev->name, port->raddr, switch_port ? " switch-port" : "");
timer_setup(&port->clean_timer, sunvnet_clean_timer_expire_common, 0);
napi_enable(&port->napi);
vio_port_up(&port->vio);
mdesc_release(hp);
return 0;
err_out_free_port:
kfree(port);
err_out_put_mdesc:
mdesc_release(hp);
return err;
}
static int vnet_port_remove(struct vio_dev *vdev)
{
struct vnet_port *port = dev_get_drvdata(&vdev->dev);
if (port) {
del_timer_sync(&port->vio.timer);
napi_disable(&port->napi);
list_del_rcu(&port->list);
hlist_del_rcu(&port->hash);
synchronize_rcu();
del_timer_sync(&port->clean_timer);
sunvnet_port_rm_txq_common(port);
netif_napi_del(&port->napi);
sunvnet_port_free_tx_bufs_common(port);
vio_ldc_free(&port->vio);
dev_set_drvdata(&vdev->dev, NULL);
kfree(port);
}
return 0;
}
static const struct vio_device_id vnet_port_match[] = {
{
.type = "vnet-port",
},
{},
};
MODULE_DEVICE_TABLE(vio, vnet_port_match);
static struct vio_driver vnet_port_driver = {
.id_table = vnet_port_match,
.probe = vnet_port_probe,
.remove = vnet_port_remove,
.name = "vnet_port",
};
static int __init vnet_init(void)
{
pr_info("%s\n", version);
return vio_register_driver(&vnet_port_driver);
}
static void __exit vnet_exit(void)
{
vio_unregister_driver(&vnet_port_driver);
vnet_cleanup();
}
module_init(vnet_init);
module_exit(vnet_exit);
|
741334.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__fgets_68a.c
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-68a.tmpl.c
*/
/*
* @description
* CWE: 617 Reachable Assertion
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Number greater than ASSERT_VALUE
* Sink:
* BadSink : Assert if n is less than or equal to ASSERT_VALUE
* Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <assert.h>
#define ASSERT_VALUE 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
int CWE617_Reachable_Assertion__fgets_68_badData;
int CWE617_Reachable_Assertion__fgets_68_goodG2BData;
#ifndef OMITBAD
/* bad function declaration */
void CWE617_Reachable_Assertion__fgets_68b_badSink();
void CWE617_Reachable_Assertion__fgets_68_bad()
{
int data;
/* Initialize data */
data = -1;
{
char inputBuffer[CHAR_ARRAY_SIZE] = "";
/* POTENTIAL FLAW: Read data from the console using fgets() */
if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
{
/* Convert to int */
data = atoi(inputBuffer);
}
else
{
printLine("fgets() failed.");
}
}
CWE617_Reachable_Assertion__fgets_68_badData = data;
CWE617_Reachable_Assertion__fgets_68b_badSink();
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void CWE617_Reachable_Assertion__fgets_68b_goodG2BSink();
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int data;
/* Initialize data */
data = -1;
/* FIX: Use a value greater than the assert value */
data = ASSERT_VALUE+1;
CWE617_Reachable_Assertion__fgets_68_goodG2BData = data;
CWE617_Reachable_Assertion__fgets_68b_goodG2BSink();
}
void CWE617_Reachable_Assertion__fgets_68_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE617_Reachable_Assertion__fgets_68_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE617_Reachable_Assertion__fgets_68_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
431491.c | /*
* quickfix.c: functions for quickfix mode, using a file with error messages
*/
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include "nvim/vim.h"
#include "nvim/ascii.h"
#include "nvim/quickfix.h"
#include "nvim/buffer.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_cmds2.h"
#include "nvim/ex_docmd.h"
#include "nvim/ex_eval.h"
#include "nvim/ex_getln.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/mark.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/misc2.h"
#include "nvim/memory.h"
#include "nvim/move.h"
#include "nvim/normal.h"
#include "nvim/option.h"
#include "nvim/os_unix.h"
#include "nvim/path.h"
#include "nvim/regexp.h"
#include "nvim/screen.h"
#include "nvim/search.h"
#include "nvim/strings.h"
#include "nvim/ui.h"
#include "nvim/window.h"
#include "nvim/os/os.h"
#include "nvim/os/input.h"
struct dir_stack_T {
struct dir_stack_T *next;
char_u *dirname;
};
static struct dir_stack_T *dir_stack = NULL;
/*
* For each error the next struct is allocated and linked in a list.
*/
typedef struct qfline_S qfline_T;
struct qfline_S {
qfline_T *qf_next; /* pointer to next error in the list */
qfline_T *qf_prev; /* pointer to previous error in the list */
linenr_T qf_lnum; /* line number where the error occurred */
int qf_fnum; /* file number for the line */
int qf_col; /* column where the error occurred */
int qf_nr; /* error number */
char_u *qf_pattern; /* search pattern for the error */
char_u *qf_text; /* description of the error */
char_u qf_viscol; /* set to TRUE if qf_col is screen column */
char_u qf_cleared; /* set to TRUE if line has been deleted */
char_u qf_type; /* type of the error (mostly 'E'); 1 for
:helpgrep */
char_u qf_valid; /* valid error message detected */
};
/*
* There is a stack of error lists.
*/
#define LISTCOUNT 10
typedef struct qf_list_S {
qfline_T *qf_start; /* pointer to the first error */
qfline_T *qf_ptr; /* pointer to the current error */
int qf_count; /* number of errors (0 means no error list) */
int qf_index; /* current index in the error list */
int qf_nonevalid; /* TRUE if not a single valid entry found */
char_u *qf_title; /* title derived from the command that created
* the error list */
} qf_list_T;
struct qf_info_S {
/*
* Count of references to this list. Used only for location lists.
* When a location list window reference this list, qf_refcount
* will be 2. Otherwise, qf_refcount will be 1. When qf_refcount
* reaches 0, the list is freed.
*/
int qf_refcount;
int qf_listcount; /* current number of lists */
int qf_curlist; /* current error list */
qf_list_T qf_lists[LISTCOUNT];
};
static qf_info_T ql_info; /* global quickfix list */
#define FMT_PATTERNS 10 /* maximum number of % recognized */
/*
* Structure used to hold the info of one part of 'errorformat'
*/
typedef struct efm_S efm_T;
struct efm_S {
regprog_T *prog; /* pre-formatted part of 'errorformat' */
efm_T *next; /* pointer to next (NULL if last) */
char_u addr[FMT_PATTERNS]; /* indices of used % patterns */
char_u prefix; /* prefix of this format line: */
/* 'D' enter directory */
/* 'X' leave directory */
/* 'A' start of multi-line message */
/* 'E' error message */
/* 'W' warning message */
/* 'I' informational message */
/* 'C' continuation line */
/* 'Z' end of multi-line message */
/* 'G' general, unspecific message */
/* 'P' push file (partial) message */
/* 'Q' pop/quit file (partial) message */
/* 'O' overread (partial) message */
char_u flags; /* additional flags given in prefix */
/* '-' do not include this line */
/* '+' include whole line in message */
int conthere; /* %> used */
};
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "quickfix.c.generated.h"
#endif
/* Quickfix window check helper macro */
#define IS_QF_WINDOW(wp) (bt_quickfix(wp->w_buffer) && wp->w_llist_ref == NULL)
/* Location list window check helper macro */
#define IS_LL_WINDOW(wp) (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)
/*
* Return location list for window 'wp'
* For location list window, return the referenced location list
*/
#define GET_LOC_LIST(wp) (IS_LL_WINDOW(wp) ? wp->w_llist_ref : wp->w_llist)
/*
* Read the errorfile "efile" into memory, line by line, building the error
* list. Set the error list's title to qf_title.
* Return -1 for error, number of errors for success.
*/
int
qf_init (
win_T *wp,
char_u *efile,
char_u *errorformat,
int newlist, /* TRUE: start a new error list */
char_u *qf_title
)
{
qf_info_T *qi = &ql_info;
if (wp != NULL) {
qi = ll_get_or_alloc_list(wp);
}
return qf_init_ext(qi, efile, curbuf, NULL, errorformat, newlist,
(linenr_T)0, (linenr_T)0,
qf_title);
}
/*
* Read the errorfile "efile" into memory, line by line, building the error
* list.
* Alternative: when "efile" is null read errors from buffer "buf".
* Always use 'errorformat' from "buf" if there is a local value.
* Then "lnumfirst" and "lnumlast" specify the range of lines to use.
* Set the title of the list to "qf_title".
* Return -1 for error, number of errors for success.
*/
static int
qf_init_ext (
qf_info_T *qi,
char_u *efile,
buf_T *buf,
typval_T *tv,
char_u *errorformat,
int newlist, /* TRUE: start a new error list */
linenr_T lnumfirst, /* first line number to use */
linenr_T lnumlast, /* last line number to use */
char_u *qf_title
)
{
char_u *namebuf;
char_u *errmsg;
char_u *pattern;
char_u *fmtstr = NULL;
int col = 0;
bool use_viscol = false;
char_u type = 0;
linenr_T buflnum = lnumfirst;
long lnum = 0L;
int enr = 0;
FILE *fd = NULL;
qfline_T *qfprev = NULL; /* init to make SASC shut up */
char_u *efmp;
efm_T *fmt_first = NULL;
efm_T *fmt_last = NULL;
efm_T *fmt_ptr;
efm_T *fmt_start = NULL;
char_u *efm;
char_u *ptr;
char_u *srcptr;
int len;
int i;
int round;
int idx = 0;
bool multiline = false;
bool multiignore = false;
bool multiscan = false;
int retval = -1; // default: return error flag
char_u *directory = NULL;
char_u *currfile = NULL;
char_u *tail = NULL;
char_u *p_str = NULL;
listitem_T *p_li = NULL;
struct dir_stack_T *file_stack = NULL;
regmatch_T regmatch;
static struct fmtpattern {
char_u convchar;
char *pattern;
} fmt_pat[FMT_PATTERNS] =
{
{'f', ".\\+"}, /* only used when at end */
{'n', "\\d\\+"},
{'l', "\\d\\+"},
{'c', "\\d\\+"},
{'t', "."},
{'m', ".\\+"},
{'r', ".*"},
{'p', "[- .]*"},
{'v', "\\d\\+"},
{'s', ".\\+"}
};
namebuf = xmalloc(CMDBUFFSIZE + 1);
errmsg = xmalloc(CMDBUFFSIZE + 1);
pattern = xmalloc(CMDBUFFSIZE + 1);
if (efile != NULL && (fd = mch_fopen((char *)efile, "r")) == NULL) {
EMSG2(_(e_openerrf), efile);
goto qf_init_end;
}
if (newlist || qi->qf_curlist == qi->qf_listcount)
/* make place for a new list */
qf_new_list(qi, qf_title);
else if (qi->qf_lists[qi->qf_curlist].qf_count > 0)
/* Adding to existing list, find last entry. */
for (qfprev = qi->qf_lists[qi->qf_curlist].qf_start;
qfprev->qf_next != qfprev; qfprev = qfprev->qf_next)
;
/*
* Each part of the format string is copied and modified from errorformat to
* regex prog. Only a few % characters are allowed.
*/
/* Use the local value of 'errorformat' if it's set. */
if (errorformat == p_efm && tv == NULL && *buf->b_p_efm != NUL)
efm = buf->b_p_efm;
else
efm = errorformat;
/*
* Get some space to modify the format string into.
*/
size_t fmtstr_size = 3 * FMT_PATTERNS + 4 * STRLEN(efm);
for (round = FMT_PATTERNS; round > 0; ) {
fmtstr_size += STRLEN(fmt_pat[--round].pattern);
}
#ifdef COLON_IN_FILENAME
fmtstr_size += 12; // "%f" can become twelve chars longer
#else
fmtstr_size += 2; // "%f" can become two chars longer
#endif
fmtstr = xmalloc(fmtstr_size);
while (efm[0] != NUL) {
/*
* Allocate a new eformat structure and put it at the end of the list
*/
fmt_ptr = xcalloc(1, sizeof(efm_T));
if (fmt_first == NULL) /* first one */
fmt_first = fmt_ptr;
else
fmt_last->next = fmt_ptr;
fmt_last = fmt_ptr;
/*
* Isolate one part in the 'errorformat' option
*/
for (len = 0; efm[len] != NUL && efm[len] != ','; ++len)
if (efm[len] == '\\' && efm[len + 1] != NUL)
++len;
/*
* Build regexp pattern from current 'errorformat' option
*/
ptr = fmtstr;
*ptr++ = '^';
round = 0;
for (efmp = efm; efmp < efm + len; ++efmp) {
if (*efmp == '%') {
++efmp;
for (idx = 0; idx < FMT_PATTERNS; ++idx)
if (fmt_pat[idx].convchar == *efmp)
break;
if (idx < FMT_PATTERNS) {
if (fmt_ptr->addr[idx]) {
sprintf((char *)errmsg,
_("E372: Too many %%%c in format string"), *efmp);
EMSG(errmsg);
goto error2;
}
if ((idx
&& idx < 6
&& vim_strchr((char_u *)"DXOPQ",
fmt_ptr->prefix) != NULL)
|| (idx == 6
&& vim_strchr((char_u *)"OPQ",
fmt_ptr->prefix) == NULL)) {
sprintf((char *)errmsg,
_("E373: Unexpected %%%c in format string"), *efmp);
EMSG(errmsg);
goto error2;
}
fmt_ptr->addr[idx] = (char_u)++ round;
*ptr++ = '\\';
*ptr++ = '(';
#ifdef BACKSLASH_IN_FILENAME
if (*efmp == 'f') {
/* Also match "c:" in the file name, even when
* checking for a colon next: "%f:".
* "\%(\a:\)\=" */
STRCPY(ptr, "\\%(\\a:\\)\\=");
ptr += 10;
}
#endif
if (*efmp == 'f' && efmp[1] != NUL) {
if (efmp[1] != '\\' && efmp[1] != '%') {
/* A file name may contain spaces, but this isn't
* in "\f". For "%f:%l:%m" there may be a ":" in
* the file name. Use ".\{-1,}x" instead (x is
* the next character), the requirement that :999:
* follows should work. */
STRCPY(ptr, ".\\{-1,}");
ptr += 7;
} else {
/* File name followed by '\\' or '%': include as
* many file name chars as possible. */
STRCPY(ptr, "\\f\\+");
ptr += 4;
}
} else {
srcptr = (char_u *)fmt_pat[idx].pattern;
while ((*ptr = *srcptr++) != NUL)
++ptr;
}
*ptr++ = '\\';
*ptr++ = ')';
} else if (*efmp == '*') {
if (*++efmp == '[' || *efmp == '\\') {
if ((*ptr++ = *efmp) == '[') { /* %*[^a-z0-9] etc. */
if (efmp[1] == '^')
*ptr++ = *++efmp;
if (efmp < efm + len) {
*ptr++ = *++efmp; /* could be ']' */
while (efmp < efm + len
&& (*ptr++ = *++efmp) != ']')
/* skip */;
if (efmp == efm + len) {
EMSG(_("E374: Missing ] in format string"));
goto error2;
}
}
} else if (efmp < efm + len) /* %*\D, %*\s etc. */
*ptr++ = *++efmp;
*ptr++ = '\\';
*ptr++ = '+';
} else {
/* TODO: scanf()-like: %*ud, %*3c, %*f, ... ? */
sprintf((char *)errmsg,
_("E375: Unsupported %%%c in format string"), *efmp);
EMSG(errmsg);
goto error2;
}
} else if (vim_strchr((char_u *)"%\\.^$~[", *efmp) != NULL)
*ptr++ = *efmp; /* regexp magic characters */
else if (*efmp == '#')
*ptr++ = '*';
else if (*efmp == '>')
fmt_ptr->conthere = TRUE;
else if (efmp == efm + 1) { /* analyse prefix */
if (vim_strchr((char_u *)"+-", *efmp) != NULL)
fmt_ptr->flags = *efmp++;
if (vim_strchr((char_u *)"DXAEWICZGOPQ", *efmp) != NULL)
fmt_ptr->prefix = *efmp;
else {
sprintf((char *)errmsg,
_("E376: Invalid %%%c in format string prefix"), *efmp);
EMSG(errmsg);
goto error2;
}
} else {
sprintf((char *)errmsg,
_("E377: Invalid %%%c in format string"), *efmp);
EMSG(errmsg);
goto error2;
}
} else { /* copy normal character */
if (*efmp == '\\' && efmp + 1 < efm + len)
++efmp;
else if (vim_strchr((char_u *)".*^$~[", *efmp) != NULL)
*ptr++ = '\\'; /* escape regexp atoms */
if (*efmp)
*ptr++ = *efmp;
}
}
*ptr++ = '$';
*ptr = NUL;
if ((fmt_ptr->prog = vim_regcomp(fmtstr, RE_MAGIC + RE_STRING)) == NULL)
goto error2;
/*
* Advance to next part
*/
efm = skip_to_option_part(efm + len); /* skip comma and spaces */
}
if (fmt_first == NULL) { /* nothing found */
EMSG(_("E378: 'errorformat' contains no pattern"));
goto error2;
}
/*
* got_int is reset here, because it was probably set when killing the
* ":make" command, but we still want to read the errorfile then.
*/
got_int = FALSE;
/* Always ignore case when looking for a matching error. */
regmatch.rm_ic = TRUE;
if (tv != NULL) {
if (tv->v_type == VAR_STRING)
p_str = tv->vval.v_string;
else if (tv->v_type == VAR_LIST)
p_li = tv->vval.v_list->lv_first;
}
/*
* Read the lines in the error file one by one.
* Try to recognize one of the error formats in each line.
*/
while (!got_int) {
/* Get the next line. */
if (fd == NULL) {
if (tv != NULL) {
if (tv->v_type == VAR_STRING) {
/* Get the next line from the supplied string */
char_u *p;
if (!*p_str) /* Reached the end of the string */
break;
p = vim_strchr(p_str, '\n');
if (p)
len = (int)(p - p_str + 1);
else
len = (int)STRLEN(p_str);
if (len > CMDBUFFSIZE - 2)
STRLCPY(IObuff, p_str, CMDBUFFSIZE - 1);
else
STRLCPY(IObuff, p_str, len + 1);
p_str += len;
} else if (tv->v_type == VAR_LIST) {
/* Get the next line from the supplied list */
while (p_li && p_li->li_tv.v_type != VAR_STRING)
p_li = p_li->li_next; /* Skip non-string items */
if (!p_li) /* End of the list */
break;
len = (int)STRLEN(p_li->li_tv.vval.v_string);
if (len > CMDBUFFSIZE - 2)
len = CMDBUFFSIZE - 2;
STRLCPY(IObuff, p_li->li_tv.vval.v_string, len + 1);
p_li = p_li->li_next; /* next item */
}
} else {
/* Get the next line from the supplied buffer */
if (buflnum > lnumlast)
break;
STRLCPY(IObuff, ml_get_buf(buf, buflnum++, FALSE),
CMDBUFFSIZE - 1);
}
} else if (fgets((char *)IObuff, CMDBUFFSIZE - 2, fd) == NULL)
break;
IObuff[CMDBUFFSIZE - 2] = NUL; /* for very long lines */
remove_bom(IObuff);
if ((efmp = vim_strrchr(IObuff, '\n')) != NULL)
*efmp = NUL;
#ifdef USE_CRNL
if ((efmp = vim_strrchr(IObuff, '\r')) != NULL)
*efmp = NUL;
#endif
/* If there was no %> item start at the first pattern */
if (fmt_start == NULL)
fmt_ptr = fmt_first;
else {
fmt_ptr = fmt_start;
fmt_start = NULL;
}
// Try to match each part of 'errorformat' until we find a complete
// match or no match.
bool valid = true;
restofline:
for (; fmt_ptr != NULL; fmt_ptr = fmt_ptr->next) {
idx = fmt_ptr->prefix;
if (multiscan && vim_strchr((char_u *)"OPQ", idx) == NULL)
continue;
namebuf[0] = NUL;
pattern[0] = NUL;
if (!multiscan)
errmsg[0] = NUL;
lnum = 0;
col = 0;
use_viscol = false;
enr = -1;
type = 0;
tail = NULL;
regmatch.regprog = fmt_ptr->prog;
int r = vim_regexec(®match, IObuff, (colnr_T)0);
fmt_ptr->prog = regmatch.regprog;
if (r) {
if ((idx == 'C' || idx == 'Z') && !multiline) {
continue;
}
if (vim_strchr((char_u *)"EWI", idx) != NULL) {
type = (char_u)idx;
} else {
type = 0;
}
// Extract error message data from matched line.
// We check for an actual submatch, because "\[" and "\]" in
// the 'errorformat' may cause the wrong submatch to be used.
if ((i = (int)fmt_ptr->addr[0]) > 0) { // %f
if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL) {
continue;
}
// Expand ~/file and $HOME/file to full path.
char_u c = *regmatch.endp[i];
*regmatch.endp[i] = NUL;
expand_env(regmatch.startp[i], namebuf, CMDBUFFSIZE);
*regmatch.endp[i] = c;
if (vim_strchr((char_u *)"OPQ", idx) != NULL
&& !os_path_exists(namebuf)) {
continue;
}
}
if ((i = (int)fmt_ptr->addr[1]) > 0) { /* %n */
if (regmatch.startp[i] == NULL)
continue;
enr = (int)atol((char *)regmatch.startp[i]);
}
if ((i = (int)fmt_ptr->addr[2]) > 0) { /* %l */
if (regmatch.startp[i] == NULL)
continue;
lnum = atol((char *)regmatch.startp[i]);
}
if ((i = (int)fmt_ptr->addr[3]) > 0) { /* %c */
if (regmatch.startp[i] == NULL)
continue;
col = (int)atol((char *)regmatch.startp[i]);
}
if ((i = (int)fmt_ptr->addr[4]) > 0) { /* %t */
if (regmatch.startp[i] == NULL)
continue;
type = *regmatch.startp[i];
}
if (fmt_ptr->flags == '+' && !multiscan) /* %+ */
STRCPY(errmsg, IObuff);
else if ((i = (int)fmt_ptr->addr[5]) > 0) { /* %m */
if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL)
continue;
len = (int)(regmatch.endp[i] - regmatch.startp[i]);
STRLCPY(errmsg, regmatch.startp[i], len + 1);
}
if ((i = (int)fmt_ptr->addr[6]) > 0) { /* %r */
if (regmatch.startp[i] == NULL)
continue;
tail = regmatch.startp[i];
}
if ((i = (int)fmt_ptr->addr[7]) > 0) { /* %p */
char_u *match_ptr;
if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL)
continue;
col = 0;
for (match_ptr = regmatch.startp[i];
match_ptr != regmatch.endp[i]; ++match_ptr) {
++col;
if (*match_ptr == TAB) {
col += 7;
col -= col % 8;
}
}
col++;
use_viscol = true;
}
if ((i = (int)fmt_ptr->addr[8]) > 0) { /* %v */
if (regmatch.startp[i] == NULL)
continue;
col = (int)atol((char *)regmatch.startp[i]);
use_viscol = true;
}
if ((i = (int)fmt_ptr->addr[9]) > 0) { /* %s */
if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL)
continue;
len = (int)(regmatch.endp[i] - regmatch.startp[i]);
if (len > CMDBUFFSIZE - 5)
len = CMDBUFFSIZE - 5;
STRCPY(pattern, "^\\V");
STRNCAT(pattern, regmatch.startp[i], len);
pattern[len + 3] = '\\';
pattern[len + 4] = '$';
pattern[len + 5] = NUL;
}
break;
}
}
multiscan = false;
if (fmt_ptr == NULL || idx == 'D' || idx == 'X') {
if (fmt_ptr != NULL) {
if (idx == 'D') { /* enter directory */
if (*namebuf == NUL) {
EMSG(_("E379: Missing or empty directory name"));
goto error2;
}
if ((directory = qf_push_dir(namebuf, &dir_stack)) == NULL)
goto error2;
} else if (idx == 'X') /* leave directory */
directory = qf_pop_dir(&dir_stack);
}
namebuf[0] = NUL; // no match found, remove file name
lnum = 0; // don't jump to this line
valid = false;
STRCPY(errmsg, IObuff); // copy whole line to error message
if (fmt_ptr == NULL) {
multiline = multiignore = false;
}
} else if (fmt_ptr != NULL) {
/* honor %> item */
if (fmt_ptr->conthere)
fmt_start = fmt_ptr;
if (vim_strchr((char_u *)"AEWI", idx) != NULL) {
multiline = true; // start of a multi-line message
multiignore = false; // reset continuation
} else if (vim_strchr((char_u *)"CZ", idx)
!= NULL) { /* continuation of multi-line msg */
if (qfprev == NULL)
goto error2;
if (*errmsg && !multiignore) {
size_t len = STRLEN(qfprev->qf_text);
qfprev->qf_text = xrealloc(qfprev->qf_text, len + STRLEN(errmsg) + 2);
qfprev->qf_text[len] = '\n';
STRCPY(qfprev->qf_text + len + 1, errmsg);
}
if (qfprev->qf_nr == -1)
qfprev->qf_nr = enr;
if (vim_isprintc(type) && !qfprev->qf_type)
qfprev->qf_type = type; /* only printable chars allowed */
if (!qfprev->qf_lnum)
qfprev->qf_lnum = lnum;
if (!qfprev->qf_col)
qfprev->qf_col = col;
qfprev->qf_viscol = use_viscol;
if (!qfprev->qf_fnum)
qfprev->qf_fnum = qf_get_fnum(directory,
*namebuf
|| directory ? namebuf : currfile
&& valid ? currfile : 0);
if (idx == 'Z') {
multiline = multiignore = false;
}
line_breakcheck();
continue;
} else if (vim_strchr((char_u *)"OPQ", idx) != NULL) {
// global file names
valid = false;
if (*namebuf == NUL || os_path_exists(namebuf)) {
if (*namebuf && idx == 'P') {
currfile = qf_push_dir(namebuf, &file_stack);
} else if (idx == 'Q') {
currfile = qf_pop_dir(&file_stack);
}
*namebuf = NUL;
if (tail && *tail) {
STRMOVE(IObuff, skipwhite(tail));
multiscan = true;
goto restofline;
}
}
}
if (fmt_ptr->flags == '-') { // generally exclude this line
if (multiline) {
multiignore = true; // also exclude continuation lines
}
continue;
}
}
if (qf_add_entry(qi, &qfprev,
directory,
(*namebuf || directory)
? namebuf
: ((currfile && valid) ? currfile : (char_u *)NULL),
0,
errmsg,
lnum,
col,
use_viscol,
pattern,
enr,
type,
valid) == FAIL)
goto error2;
line_breakcheck();
}
if (fd == NULL || !ferror(fd)) {
if (qi->qf_lists[qi->qf_curlist].qf_index == 0) {
/* no valid entry found */
qi->qf_lists[qi->qf_curlist].qf_ptr =
qi->qf_lists[qi->qf_curlist].qf_start;
qi->qf_lists[qi->qf_curlist].qf_index = 1;
qi->qf_lists[qi->qf_curlist].qf_nonevalid = TRUE;
} else {
qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE;
if (qi->qf_lists[qi->qf_curlist].qf_ptr == NULL)
qi->qf_lists[qi->qf_curlist].qf_ptr =
qi->qf_lists[qi->qf_curlist].qf_start;
}
/* return number of matches */
retval = qi->qf_lists[qi->qf_curlist].qf_count;
goto qf_init_ok;
}
EMSG(_(e_readerrf));
error2:
qf_free(qi, qi->qf_curlist);
qi->qf_listcount--;
if (qi->qf_curlist > 0)
--qi->qf_curlist;
qf_init_ok:
if (fd != NULL)
fclose(fd);
for (fmt_ptr = fmt_first; fmt_ptr != NULL; fmt_ptr = fmt_first) {
fmt_first = fmt_ptr->next;
vim_regfree(fmt_ptr->prog);
xfree(fmt_ptr);
}
qf_clean_dir_stack(&dir_stack);
qf_clean_dir_stack(&file_stack);
qf_init_end:
xfree(namebuf);
xfree(errmsg);
xfree(pattern);
xfree(fmtstr);
qf_update_buffer(qi);
return retval;
}
static void qf_store_title(qf_info_T *qi, char_u *title)
{
if (title != NULL) {
char_u *p = xmalloc(STRLEN(title) + 2);
qi->qf_lists[qi->qf_curlist].qf_title = p;
sprintf((char *)p, ":%s", (char *)title);
}
}
/*
* Prepare for adding a new quickfix list.
*/
static void qf_new_list(qf_info_T *qi, char_u *qf_title)
{
int i;
// If the current entry is not the last entry, delete entries beyond
// the current entry. This makes it possible to browse in a tree-like
// way with ":grep'.
while (qi->qf_listcount > qi->qf_curlist + 1)
qf_free(qi, --qi->qf_listcount);
/*
* When the stack is full, remove to oldest entry
* Otherwise, add a new entry.
*/
if (qi->qf_listcount == LISTCOUNT) {
qf_free(qi, 0);
for (i = 1; i < LISTCOUNT; ++i)
qi->qf_lists[i - 1] = qi->qf_lists[i];
qi->qf_curlist = LISTCOUNT - 1;
} else
qi->qf_curlist = qi->qf_listcount++;
memset(&qi->qf_lists[qi->qf_curlist], 0, (size_t)(sizeof(qf_list_T)));
qf_store_title(qi, qf_title);
}
/*
* Free a location list
*/
static void ll_free_all(qf_info_T **pqi)
{
int i;
qf_info_T *qi;
qi = *pqi;
if (qi == NULL)
return;
*pqi = NULL; /* Remove reference to this list */
qi->qf_refcount--;
if (qi->qf_refcount < 1) {
/* No references to this location list */
for (i = 0; i < qi->qf_listcount; ++i)
qf_free(qi, i);
xfree(qi);
}
}
void qf_free_all(win_T *wp)
{
int i;
qf_info_T *qi = &ql_info;
if (wp != NULL) {
/* location list */
ll_free_all(&wp->w_llist);
ll_free_all(&wp->w_llist_ref);
} else
/* quickfix list */
for (i = 0; i < qi->qf_listcount; ++i)
qf_free(qi, i);
}
/// Add an entry to the end of the list of errors.
///
/// @param qi quickfix list
/// @param prevp nonnull pointer (to previously added entry or NULL)
/// @param dir optional directory name
/// @param fname file name or NULL
/// @param bufnum buffer number or zero
/// @param mesg message
/// @param lnum line number
/// @param col column
/// @param vis_col using visual column
/// @param pattern search pattern
/// @param nr error number
/// @param type type character
/// @param valid valid entry
///
/// @returns OK or FAIL.
static int qf_add_entry(qf_info_T *qi, qfline_T **prevp, char_u *dir,
char_u *fname, int bufnum, char_u *mesg, long lnum,
int col, char_u vis_col, char_u *pattern, int nr,
char_u type, char_u valid)
{
qfline_T *qfp = xmalloc(sizeof(qfline_T));
if (bufnum != 0)
qfp->qf_fnum = bufnum;
else
qfp->qf_fnum = qf_get_fnum(dir, fname);
qfp->qf_text = vim_strsave(mesg);
qfp->qf_lnum = lnum;
qfp->qf_col = col;
qfp->qf_viscol = vis_col;
if (pattern == NULL || *pattern == NUL) {
qfp->qf_pattern = NULL;
} else {
qfp->qf_pattern = vim_strsave(pattern);
}
qfp->qf_nr = nr;
if (type != 1 && !vim_isprintc(type)) /* only printable chars allowed */
type = 0;
qfp->qf_type = type;
qfp->qf_valid = valid;
if (qi->qf_lists[qi->qf_curlist].qf_count == 0) {
/* first element in the list */
qi->qf_lists[qi->qf_curlist].qf_start = qfp;
qfp->qf_prev = qfp; /* first element points to itself */
} else {
assert(*prevp);
qfp->qf_prev = *prevp;
(*prevp)->qf_next = qfp;
}
qfp->qf_next = qfp; /* last element points to itself */
qfp->qf_cleared = FALSE;
*prevp = qfp;
++qi->qf_lists[qi->qf_curlist].qf_count;
if (qi->qf_lists[qi->qf_curlist].qf_index == 0 && qfp->qf_valid) {
/* first valid entry */
qi->qf_lists[qi->qf_curlist].qf_index =
qi->qf_lists[qi->qf_curlist].qf_count;
qi->qf_lists[qi->qf_curlist].qf_ptr = qfp;
}
return OK;
}
/*
* Allocate a new location list
*/
static qf_info_T *ll_new_list(void)
{
qf_info_T *qi = xcalloc(1, sizeof(qf_info_T));
qi->qf_refcount++;
return qi;
}
/*
* Return the location list for window 'wp'.
* If not present, allocate a location list
*/
static qf_info_T *ll_get_or_alloc_list(win_T *wp)
{
if (IS_LL_WINDOW(wp))
/* For a location list window, use the referenced location list */
return wp->w_llist_ref;
/*
* For a non-location list window, w_llist_ref should not point to a
* location list.
*/
ll_free_all(&wp->w_llist_ref);
if (wp->w_llist == NULL)
wp->w_llist = ll_new_list(); /* new location list */
return wp->w_llist;
}
/*
* Copy the location list from window "from" to window "to".
*/
void copy_loclist(win_T *from, win_T *to)
{
qf_info_T *qi;
int idx;
int i;
/*
* When copying from a location list window, copy the referenced
* location list. For other windows, copy the location list for
* that window.
*/
if (IS_LL_WINDOW(from))
qi = from->w_llist_ref;
else
qi = from->w_llist;
if (qi == NULL) /* no location list to copy */
return;
/* allocate a new location list */
to->w_llist = ll_new_list();
to->w_llist->qf_listcount = qi->qf_listcount;
/* Copy the location lists one at a time */
for (idx = 0; idx < qi->qf_listcount; idx++) {
qf_list_T *from_qfl;
qf_list_T *to_qfl;
to->w_llist->qf_curlist = idx;
from_qfl = &qi->qf_lists[idx];
to_qfl = &to->w_llist->qf_lists[idx];
/* Some of the fields are populated by qf_add_entry() */
to_qfl->qf_nonevalid = from_qfl->qf_nonevalid;
to_qfl->qf_count = 0;
to_qfl->qf_index = 0;
to_qfl->qf_start = NULL;
to_qfl->qf_ptr = NULL;
if (from_qfl->qf_title != NULL)
to_qfl->qf_title = vim_strsave(from_qfl->qf_title);
else
to_qfl->qf_title = NULL;
if (from_qfl->qf_count) {
qfline_T *from_qfp;
qfline_T *prevp = NULL;
/* copy all the location entries in this list */
for (i = 0, from_qfp = from_qfl->qf_start; i < from_qfl->qf_count;
++i, from_qfp = from_qfp->qf_next) {
if (qf_add_entry(to->w_llist, &prevp,
NULL,
NULL,
0,
from_qfp->qf_text,
from_qfp->qf_lnum,
from_qfp->qf_col,
from_qfp->qf_viscol,
from_qfp->qf_pattern,
from_qfp->qf_nr,
0,
from_qfp->qf_valid) == FAIL) {
qf_free_all(to);
return;
}
/*
* qf_add_entry() will not set the qf_num field, as the
* directory and file names are not supplied. So the qf_fnum
* field is copied here.
*/
prevp->qf_fnum = from_qfp->qf_fnum; /* file number */
prevp->qf_type = from_qfp->qf_type; /* error type */
if (from_qfl->qf_ptr == from_qfp)
to_qfl->qf_ptr = prevp; /* current location */
}
}
to_qfl->qf_index = from_qfl->qf_index; /* current index in the list */
/* When no valid entries are present in the list, qf_ptr points to
* the first item in the list */
if (to_qfl->qf_nonevalid) {
to_qfl->qf_ptr = to_qfl->qf_start;
to_qfl->qf_index = 1;
}
}
to->w_llist->qf_curlist = qi->qf_curlist; /* current list */
}
/*
* get buffer number for file "dir.name"
*/
static int qf_get_fnum(char_u *directory, char_u *fname)
{
if (fname == NULL || *fname == NUL) /* no file name */
return 0;
{
char_u *ptr;
int fnum;
#ifdef BACKSLASH_IN_FILENAME
if (directory != NULL)
slash_adjust(directory);
slash_adjust(fname);
#endif
if (directory != NULL && !vim_isAbsName(fname)) {
ptr = (char_u *)concat_fnames((char *)directory, (char *)fname, TRUE);
/*
* Here we check if the file really exists.
* This should normally be true, but if make works without
* "leaving directory"-messages we might have missed a
* directory change.
*/
if (!os_path_exists(ptr)) {
xfree(ptr);
directory = qf_guess_filepath(fname);
if (directory)
ptr = (char_u *)concat_fnames((char *)directory, (char *)fname, TRUE);
else
ptr = vim_strsave(fname);
}
/* Use concatenated directory name and file name */
fnum = buflist_add(ptr, 0);
xfree(ptr);
return fnum;
}
return buflist_add(fname, 0);
}
}
/*
* push dirbuf onto the directory stack and return pointer to actual dir or
* NULL on error
*/
static char_u *qf_push_dir(char_u *dirbuf, struct dir_stack_T **stackptr)
{
struct dir_stack_T *ds_ptr;
/* allocate new stack element and hook it in */
struct dir_stack_T *ds_new = xmalloc(sizeof(struct dir_stack_T));
ds_new->next = *stackptr;
*stackptr = ds_new;
/* store directory on the stack */
if (vim_isAbsName(dirbuf)
|| (*stackptr)->next == NULL
|| (*stackptr && dir_stack != *stackptr))
(*stackptr)->dirname = vim_strsave(dirbuf);
else {
/* Okay we don't have an absolute path.
* dirbuf must be a subdir of one of the directories on the stack.
* Let's search...
*/
ds_new = (*stackptr)->next;
(*stackptr)->dirname = NULL;
while (ds_new) {
xfree((*stackptr)->dirname);
(*stackptr)->dirname = (char_u *)concat_fnames((char *)ds_new->dirname,
(char *)dirbuf, TRUE);
if (os_isdir((*stackptr)->dirname))
break;
ds_new = ds_new->next;
}
/* clean up all dirs we already left */
while ((*stackptr)->next != ds_new) {
ds_ptr = (*stackptr)->next;
(*stackptr)->next = (*stackptr)->next->next;
xfree(ds_ptr->dirname);
xfree(ds_ptr);
}
/* Nothing found -> it must be on top level */
if (ds_new == NULL) {
xfree((*stackptr)->dirname);
(*stackptr)->dirname = vim_strsave(dirbuf);
}
}
if ((*stackptr)->dirname != NULL)
return (*stackptr)->dirname;
else {
ds_ptr = *stackptr;
*stackptr = (*stackptr)->next;
xfree(ds_ptr);
return NULL;
}
}
/*
* pop dirbuf from the directory stack and return previous directory or NULL if
* stack is empty
*/
static char_u *qf_pop_dir(struct dir_stack_T **stackptr)
{
struct dir_stack_T *ds_ptr;
/* TODO: Should we check if dirbuf is the directory on top of the stack?
* What to do if it isn't? */
/* pop top element and free it */
if (*stackptr != NULL) {
ds_ptr = *stackptr;
*stackptr = (*stackptr)->next;
xfree(ds_ptr->dirname);
xfree(ds_ptr);
}
/* return NEW top element as current dir or NULL if stack is empty*/
return *stackptr ? (*stackptr)->dirname : NULL;
}
/*
* clean up directory stack
*/
static void qf_clean_dir_stack(struct dir_stack_T **stackptr)
{
struct dir_stack_T *ds_ptr;
while ((ds_ptr = *stackptr) != NULL) {
*stackptr = (*stackptr)->next;
xfree(ds_ptr->dirname);
xfree(ds_ptr);
}
}
/*
* Check in which directory of the directory stack the given file can be
* found.
* Returns a pointer to the directory name or NULL if not found.
* Cleans up intermediate directory entries.
*
* TODO: How to solve the following problem?
* If we have the this directory tree:
* ./
* ./aa
* ./aa/bb
* ./bb
* ./bb/x.c
* and make says:
* making all in aa
* making all in bb
* x.c:9: Error
* Then qf_push_dir thinks we are in ./aa/bb, but we are in ./bb.
* qf_guess_filepath will return NULL.
*/
static char_u *qf_guess_filepath(char_u *filename)
{
struct dir_stack_T *ds_ptr;
struct dir_stack_T *ds_tmp;
char_u *fullname;
/* no dirs on the stack - there's nothing we can do */
if (dir_stack == NULL)
return NULL;
ds_ptr = dir_stack->next;
fullname = NULL;
while (ds_ptr) {
xfree(fullname);
fullname = (char_u *)concat_fnames((char *)ds_ptr->dirname, (char *)filename, TRUE);
if (os_path_exists(fullname)) {
break;
}
ds_ptr = ds_ptr->next;
}
xfree(fullname);
/* clean up all dirs we already left */
while (dir_stack->next != ds_ptr) {
ds_tmp = dir_stack->next;
dir_stack->next = dir_stack->next->next;
xfree(ds_tmp->dirname);
xfree(ds_tmp);
}
return ds_ptr==NULL ? NULL : ds_ptr->dirname;
}
/*
* jump to a quickfix line
* if dir == FORWARD go "errornr" valid entries forward
* if dir == BACKWARD go "errornr" valid entries backward
* if dir == FORWARD_FILE go "errornr" valid entries files backward
* if dir == BACKWARD_FILE go "errornr" valid entries files backward
* else if "errornr" is zero, redisplay the same line
* else go to entry "errornr"
*/
void qf_jump(qf_info_T *qi, int dir, int errornr, int forceit)
{
qf_info_T *ll_ref;
qfline_T *qf_ptr;
qfline_T *old_qf_ptr;
int qf_index;
int old_qf_fnum;
int old_qf_index;
int prev_index;
static char_u *e_no_more_items = (char_u *)N_("E553: No more items");
char_u *err = e_no_more_items;
linenr_T i;
buf_T *old_curbuf;
linenr_T old_lnum;
colnr_T screen_col;
colnr_T char_col;
char_u *line;
char_u *old_swb = p_swb;
unsigned old_swb_flags = swb_flags;
int opened_window = FALSE;
win_T *win;
win_T *altwin;
int flags;
win_T *oldwin = curwin;
int print_message = TRUE;
int len;
int old_KeyTyped = KeyTyped; /* getting file may reset it */
int ok = OK;
bool usable_win;
if (qi == NULL)
qi = &ql_info;
if (qi->qf_curlist >= qi->qf_listcount
|| qi->qf_lists[qi->qf_curlist].qf_count == 0) {
EMSG(_(e_quickfix));
return;
}
qf_ptr = qi->qf_lists[qi->qf_curlist].qf_ptr;
old_qf_ptr = qf_ptr;
qf_index = qi->qf_lists[qi->qf_curlist].qf_index;
old_qf_index = qf_index;
if (dir == FORWARD || dir == FORWARD_FILE) { /* next valid entry */
while (errornr--) {
old_qf_ptr = qf_ptr;
prev_index = qf_index;
old_qf_fnum = qf_ptr->qf_fnum;
do {
if (qf_index == qi->qf_lists[qi->qf_curlist].qf_count
|| qf_ptr->qf_next == NULL) {
qf_ptr = old_qf_ptr;
qf_index = prev_index;
if (err != NULL) {
EMSG(_(err));
goto theend;
}
errornr = 0;
break;
}
++qf_index;
qf_ptr = qf_ptr->qf_next;
} while ((!qi->qf_lists[qi->qf_curlist].qf_nonevalid
&& !qf_ptr->qf_valid)
|| (dir == FORWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum));
err = NULL;
}
} else if (dir == BACKWARD || dir == BACKWARD_FILE) { /* prev. valid entry */
while (errornr--) {
old_qf_ptr = qf_ptr;
prev_index = qf_index;
old_qf_fnum = qf_ptr->qf_fnum;
do {
if (qf_index == 1 || qf_ptr->qf_prev == NULL) {
qf_ptr = old_qf_ptr;
qf_index = prev_index;
if (err != NULL) {
EMSG(_(err));
goto theend;
}
errornr = 0;
break;
}
--qf_index;
qf_ptr = qf_ptr->qf_prev;
} while ((!qi->qf_lists[qi->qf_curlist].qf_nonevalid
&& !qf_ptr->qf_valid)
|| (dir == BACKWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum));
err = NULL;
}
} else if (errornr != 0) { /* go to specified number */
while (errornr < qf_index && qf_index > 1 && qf_ptr->qf_prev != NULL) {
--qf_index;
qf_ptr = qf_ptr->qf_prev;
}
while (errornr > qf_index && qf_index <
qi->qf_lists[qi->qf_curlist].qf_count
&& qf_ptr->qf_next != NULL) {
++qf_index;
qf_ptr = qf_ptr->qf_next;
}
}
qi->qf_lists[qi->qf_curlist].qf_index = qf_index;
if (qf_win_pos_update(qi, old_qf_index))
/* No need to print the error message if it's visible in the error
* window */
print_message = FALSE;
/*
* For ":helpgrep" find a help window or open one.
*/
if (qf_ptr->qf_type == 1 && (!curwin->w_buffer->b_help || cmdmod.tab != 0)) {
win_T *wp = NULL;
if (cmdmod.tab == 0) {
FOR_ALL_WINDOWS_IN_TAB(wp2, curtab) {
if (wp2->w_buffer != NULL && wp2->w_buffer->b_help) {
wp = wp2;
break;
}
}
}
if (wp != NULL && wp->w_buffer->b_nwindows > 0)
win_enter(wp, true);
else {
/*
* Split off help window; put it at far top if no position
* specified, the current window is vertically split and narrow.
*/
flags = WSP_HELP;
if (cmdmod.split == 0 && curwin->w_width != Columns
&& curwin->w_width < 80)
flags |= WSP_TOP;
if (qi != &ql_info)
flags |= WSP_NEWLOC; /* don't copy the location list */
if (win_split(0, flags) == FAIL)
goto theend;
opened_window = TRUE; /* close it when fail */
if (curwin->w_height < p_hh)
win_setheight((int)p_hh);
if (qi != &ql_info) { /* not a quickfix list */
/* The new window should use the supplied location list */
curwin->w_llist = qi;
qi->qf_refcount++;
}
}
if (!p_im)
restart_edit = 0; /* don't want insert mode in help file */
}
/*
* If currently in the quickfix window, find another window to show the
* file in.
*/
if (bt_quickfix(curbuf) && !opened_window) {
win_T *usable_win_ptr = NULL;
/*
* If there is no file specified, we don't know where to go.
* But do advance, otherwise ":cn" gets stuck.
*/
if (qf_ptr->qf_fnum == 0)
goto theend;
usable_win = false;
ll_ref = curwin->w_llist_ref;
if (ll_ref != NULL) {
/* Find a window using the same location list that is not a
* quickfix window. */
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_llist == ll_ref
&& wp->w_buffer->b_p_bt[0] != 'q') {
usable_win = true;
usable_win_ptr = wp;
break;
}
}
}
if (!usable_win) {
/* Locate a window showing a normal buffer */
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_buffer->b_p_bt[0] == NUL) {
usable_win = true;
break;
}
}
}
/*
* If no usable window is found and 'switchbuf' contains "usetab"
* then search in other tabs.
*/
if (!usable_win && (swb_flags & SWB_USETAB)) {
FOR_ALL_TAB_WINDOWS(tp, wp) {
if (wp->w_buffer->b_fnum == qf_ptr->qf_fnum) {
goto_tabpage_win(tp, wp);
usable_win = true;
goto win_found;
}
}
}
win_found:
/*
* If there is only one window and it is the quickfix window, create a
* new one above the quickfix window.
*/
if (((firstwin == lastwin) && bt_quickfix(curbuf)) || !usable_win) {
flags = WSP_ABOVE;
if (ll_ref != NULL)
flags |= WSP_NEWLOC;
if (win_split(0, flags) == FAIL)
goto failed; /* not enough room for window */
opened_window = TRUE; /* close it when fail */
p_swb = empty_option; /* don't split again */
swb_flags = 0;
RESET_BINDING(curwin);
if (ll_ref != NULL) {
/* The new window should use the location list from the
* location list window */
curwin->w_llist = ll_ref;
ll_ref->qf_refcount++;
}
} else {
if (curwin->w_llist_ref != NULL) {
/* In a location window */
win = usable_win_ptr;
if (win == NULL) {
/* Find the window showing the selected file */
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_buffer->b_fnum == qf_ptr->qf_fnum) {
win = wp;
break;
}
}
if (win == NULL) {
/* Find a previous usable window */
win = curwin;
do {
if (win->w_buffer->b_p_bt[0] == NUL)
break;
if (win->w_prev == NULL)
win = lastwin; /* wrap around the top */
else
win = win->w_prev; /* go to previous window */
} while (win != curwin);
}
}
win_goto(win);
/* If the location list for the window is not set, then set it
* to the location list from the location window */
if (win->w_llist == NULL) {
win->w_llist = ll_ref;
ll_ref->qf_refcount++;
}
} else {
/*
* Try to find a window that shows the right buffer.
* Default to the window just above the quickfix buffer.
*/
win = curwin;
altwin = NULL;
for (;; ) {
if (win->w_buffer->b_fnum == qf_ptr->qf_fnum)
break;
if (win->w_prev == NULL)
win = lastwin; /* wrap around the top */
else
win = win->w_prev; /* go to previous window */
if (IS_QF_WINDOW(win)) {
/* Didn't find it, go to the window before the quickfix
* window. */
if (altwin != NULL)
win = altwin;
else if (curwin->w_prev != NULL)
win = curwin->w_prev;
else
win = curwin->w_next;
break;
}
/* Remember a usable window. */
if (altwin == NULL && !win->w_p_pvw
&& win->w_buffer->b_p_bt[0] == NUL)
altwin = win;
}
win_goto(win);
}
}
}
/*
* If there is a file name,
* read the wanted file if needed, and check autowrite etc.
*/
old_curbuf = curbuf;
old_lnum = curwin->w_cursor.lnum;
if (qf_ptr->qf_fnum != 0) {
if (qf_ptr->qf_type == 1) {
/* Open help file (do_ecmd() will set b_help flag, readfile() will
* set b_p_ro flag). */
if (!can_abandon(curbuf, forceit)) {
EMSG(_(e_nowrtmsg));
ok = false;
} else {
ok = do_ecmd(qf_ptr->qf_fnum, NULL, NULL, NULL, (linenr_T)1,
ECMD_HIDE + ECMD_SET_HELP,
oldwin == curwin ? curwin : NULL);
}
} else {
ok = buflist_getfile(qf_ptr->qf_fnum, (linenr_T)1,
GETF_SETMARK | GETF_SWITCH, forceit);
if (qi != &ql_info && !win_valid(oldwin)) {
EMSG(_("E924: Current window was closed"));
ok = false;
qi = NULL;
qf_ptr = NULL;
opened_window = false;
}
}
}
if (ok == OK) {
/* When not switched to another buffer, still need to set pc mark */
if (curbuf == old_curbuf)
setpcmark();
if (qf_ptr->qf_pattern == NULL) {
/*
* Go to line with error, unless qf_lnum is 0.
*/
i = qf_ptr->qf_lnum;
if (i > 0) {
if (i > curbuf->b_ml.ml_line_count)
i = curbuf->b_ml.ml_line_count;
curwin->w_cursor.lnum = i;
}
if (qf_ptr->qf_col > 0) {
curwin->w_cursor.col = qf_ptr->qf_col - 1;
curwin->w_cursor.coladd = 0;
if (qf_ptr->qf_viscol == true) {
// Check each character from the beginning of the error
// line up to the error column. For each tab character
// found, reduce the error column value by the length of
// a tab character.
line = get_cursor_line_ptr();
screen_col = 0;
for (char_col = 0; char_col < curwin->w_cursor.col; ++char_col) {
if (*line == NUL)
break;
if (*line++ == '\t') {
curwin->w_cursor.col -= 7 - (screen_col % 8);
screen_col += 8 - (screen_col % 8);
} else
++screen_col;
}
}
check_cursor();
} else
beginline(BL_WHITE | BL_FIX);
} else {
pos_T save_cursor;
/* Move the cursor to the first line in the buffer */
save_cursor = curwin->w_cursor;
curwin->w_cursor.lnum = 0;
if (!do_search(NULL, '/', qf_ptr->qf_pattern, (long)1,
SEARCH_KEEP, NULL))
curwin->w_cursor = save_cursor;
}
if ((fdo_flags & FDO_QUICKFIX) && old_KeyTyped)
foldOpenCursor();
if (print_message) {
/* Update the screen before showing the message, unless the screen
* scrolled up. */
if (!msg_scrolled)
update_topline_redraw();
sprintf((char *)IObuff, _("(%d of %d)%s%s: "), qf_index,
qi->qf_lists[qi->qf_curlist].qf_count,
qf_ptr->qf_cleared ? _(" (line deleted)") : "",
(char *)qf_types(qf_ptr->qf_type, qf_ptr->qf_nr));
/* Add the message, skipping leading whitespace and newlines. */
len = (int)STRLEN(IObuff);
qf_fmt_text(skipwhite(qf_ptr->qf_text), IObuff + len, IOSIZE - len);
/* Output the message. Overwrite to avoid scrolling when the 'O'
* flag is present in 'shortmess'; But when not jumping, print the
* whole message. */
i = msg_scroll;
if (curbuf == old_curbuf && curwin->w_cursor.lnum == old_lnum) {
msg_scroll = true;
} else if (!msg_scrolled && shortmess(SHM_OVERALL)) {
msg_scroll = false;
}
msg_attr_keep(IObuff, 0, true);
msg_scroll = (int)i;
}
} else {
if (opened_window) {
win_close(curwin, true); // Close opened window
}
if (qf_ptr != NULL && qf_ptr->qf_fnum != 0) {
// Couldn't open file, so put index back where it was. This could
// happen if the file was readonly and we changed something.
failed:
qf_ptr = old_qf_ptr;
qf_index = old_qf_index;
}
}
theend:
if (qi != NULL) {
qi->qf_lists[qi->qf_curlist].qf_ptr = qf_ptr;
qi->qf_lists[qi->qf_curlist].qf_index = qf_index;
}
if (p_swb != old_swb && opened_window) {
/* Restore old 'switchbuf' value, but not when an autocommand or
* modeline has changed the value. */
if (p_swb == empty_option) {
p_swb = old_swb;
swb_flags = old_swb_flags;
} else
free_string_option(old_swb);
}
}
/*
* ":clist": list all errors
* ":llist": list all locations
*/
void qf_list(exarg_T *eap)
{
buf_T *buf;
char_u *fname;
qfline_T *qfp;
int i;
int idx1 = 1;
int idx2 = -1;
char_u *arg = eap->arg;
int all = eap->forceit; /* if not :cl!, only show
recognised errors */
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_llist) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
EMSG(_(e_loclist));
return;
}
}
if (qi->qf_curlist >= qi->qf_listcount
|| qi->qf_lists[qi->qf_curlist].qf_count == 0) {
EMSG(_(e_quickfix));
return;
}
if (!get_list_range(&arg, &idx1, &idx2) || *arg != NUL) {
EMSG(_(e_trailing));
return;
}
i = qi->qf_lists[qi->qf_curlist].qf_count;
if (idx1 < 0)
idx1 = (-idx1 > i) ? 0 : idx1 + i + 1;
if (idx2 < 0)
idx2 = (-idx2 > i) ? 0 : idx2 + i + 1;
if (qi->qf_lists[qi->qf_curlist].qf_nonevalid)
all = TRUE;
qfp = qi->qf_lists[qi->qf_curlist].qf_start;
for (i = 1; !got_int && i <= qi->qf_lists[qi->qf_curlist].qf_count; ) {
if ((qfp->qf_valid || all) && idx1 <= i && i <= idx2) {
msg_putchar('\n');
if (got_int)
break;
fname = NULL;
if (qfp->qf_fnum != 0
&& (buf = buflist_findnr(qfp->qf_fnum)) != NULL) {
fname = buf->b_fname;
if (qfp->qf_type == 1) /* :helpgrep */
fname = path_tail(fname);
}
if (fname == NULL)
sprintf((char *)IObuff, "%2d", i);
else
vim_snprintf((char *)IObuff, IOSIZE, "%2d %s",
i, (char *)fname);
msg_outtrans_attr(IObuff, i == qi->qf_lists[qi->qf_curlist].qf_index
? hl_attr(HLF_L) : hl_attr(HLF_D));
if (qfp->qf_lnum == 0)
IObuff[0] = NUL;
else if (qfp->qf_col == 0)
sprintf((char *)IObuff, ":%" PRId64, (int64_t)qfp->qf_lnum);
else
sprintf((char *)IObuff, ":%" PRId64 " col %d",
(int64_t)qfp->qf_lnum, qfp->qf_col);
sprintf((char *)IObuff + STRLEN(IObuff), "%s:",
(char *)qf_types(qfp->qf_type, qfp->qf_nr));
msg_puts_attr(IObuff, hl_attr(HLF_N));
if (qfp->qf_pattern != NULL) {
qf_fmt_text(qfp->qf_pattern, IObuff, IOSIZE);
STRCAT(IObuff, ":");
msg_puts(IObuff);
}
msg_puts((char_u *)" ");
/* Remove newlines and leading whitespace from the text. For an
* unrecognized line keep the indent, the compiler may mark a word
* with ^^^^. */
qf_fmt_text((fname != NULL || qfp->qf_lnum != 0)
? skipwhite(qfp->qf_text) : qfp->qf_text,
IObuff, IOSIZE);
msg_prt_line(IObuff, FALSE);
ui_flush(); /* show one line at a time */
}
qfp = qfp->qf_next;
++i;
os_breakcheck();
}
}
/*
* Remove newlines and leading whitespace from an error message.
* Put the result in "buf[bufsize]".
*/
static void qf_fmt_text(char_u *text, char_u *buf, int bufsize)
{
int i;
char_u *p = text;
for (i = 0; *p != NUL && i < bufsize - 1; ++i) {
if (*p == '\n') {
buf[i] = ' ';
while (*++p != NUL)
if (!ascii_iswhite(*p) && *p != '\n')
break;
} else
buf[i] = *p++;
}
buf[i] = NUL;
}
/*
* ":colder [count]": Up in the quickfix stack.
* ":cnewer [count]": Down in the quickfix stack.
* ":lolder [count]": Up in the location list stack.
* ":lnewer [count]": Down in the location list stack.
*/
void qf_age(exarg_T *eap)
{
qf_info_T *qi = &ql_info;
int count;
if (eap->cmdidx == CMD_lolder || eap->cmdidx == CMD_lnewer) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
EMSG(_(e_loclist));
return;
}
}
if (eap->addr_count != 0) {
assert(eap->line2 <= INT_MAX);
count = (int)eap->line2;
} else {
count = 1;
}
while (count--) {
if (eap->cmdidx == CMD_colder || eap->cmdidx == CMD_lolder) {
if (qi->qf_curlist == 0) {
EMSG(_("E380: At bottom of quickfix stack"));
break;
}
--qi->qf_curlist;
} else {
if (qi->qf_curlist >= qi->qf_listcount - 1) {
EMSG(_("E381: At top of quickfix stack"));
break;
}
++qi->qf_curlist;
}
}
qf_msg(qi);
}
static void qf_msg(qf_info_T *qi)
{
smsg(_("error list %d of %d; %d errors"),
qi->qf_curlist + 1, qi->qf_listcount,
qi->qf_lists[qi->qf_curlist].qf_count);
qf_update_buffer(qi);
}
/*
* Free error list "idx".
*/
static void qf_free(qf_info_T *qi, int idx)
{
qfline_T *qfp;
int stop = FALSE;
while (qi->qf_lists[idx].qf_count) {
qfp = qi->qf_lists[idx].qf_start->qf_next;
if (qi->qf_lists[idx].qf_title != NULL && !stop) {
xfree(qi->qf_lists[idx].qf_start->qf_text);
stop = (qi->qf_lists[idx].qf_start == qfp);
xfree(qi->qf_lists[idx].qf_start->qf_pattern);
xfree(qi->qf_lists[idx].qf_start);
if (stop)
/* Somehow qf_count may have an incorrect value, set it to 1
* to avoid crashing when it's wrong.
* TODO: Avoid qf_count being incorrect. */
qi->qf_lists[idx].qf_count = 1;
}
qi->qf_lists[idx].qf_start = qfp;
--qi->qf_lists[idx].qf_count;
}
xfree(qi->qf_lists[idx].qf_title);
qi->qf_lists[idx].qf_start = NULL;
qi->qf_lists[idx].qf_ptr = NULL;
qi->qf_lists[idx].qf_title = NULL;
qi->qf_lists[idx].qf_index = 0;
}
/*
* qf_mark_adjust: adjust marks
*/
void qf_mark_adjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long amount_after)
{
int i;
qfline_T *qfp;
int idx;
qf_info_T *qi = &ql_info;
if (wp != NULL) {
if (wp->w_llist == NULL)
return;
qi = wp->w_llist;
}
for (idx = 0; idx < qi->qf_listcount; ++idx)
if (qi->qf_lists[idx].qf_count)
for (i = 0, qfp = qi->qf_lists[idx].qf_start;
i < qi->qf_lists[idx].qf_count; ++i, qfp = qfp->qf_next)
if (qfp->qf_fnum == curbuf->b_fnum) {
if (qfp->qf_lnum >= line1 && qfp->qf_lnum <= line2) {
if (amount == MAXLNUM)
qfp->qf_cleared = TRUE;
else
qfp->qf_lnum += amount;
} else if (amount_after && qfp->qf_lnum > line2)
qfp->qf_lnum += amount_after;
}
}
/*
* Make a nice message out of the error character and the error number:
* char number message
* e or E 0 " error"
* w or W 0 " warning"
* i or I 0 " info"
* 0 0 ""
* other 0 " c"
* e or E n " error n"
* w or W n " warning n"
* i or I n " info n"
* 0 n " error n"
* other n " c n"
* 1 x "" :helpgrep
*/
static char_u *qf_types(int c, int nr)
{
static char_u buf[20];
static char_u cc[3];
char_u *p;
if (c == 'W' || c == 'w')
p = (char_u *)" warning";
else if (c == 'I' || c == 'i')
p = (char_u *)" info";
else if (c == 'E' || c == 'e' || (c == 0 && nr > 0))
p = (char_u *)" error";
else if (c == 0 || c == 1)
p = (char_u *)"";
else {
cc[0] = ' ';
cc[1] = (char_u)c;
cc[2] = NUL;
p = cc;
}
if (nr <= 0)
return p;
sprintf((char *)buf, "%s %3d", (char *)p, nr);
return buf;
}
/*
* ":cwindow": open the quickfix window if we have errors to display,
* close it if not.
* ":lwindow": open the location list window if we have locations to display,
* close it if not.
*/
void ex_cwindow(exarg_T *eap)
{
qf_info_T *qi = &ql_info;
win_T *win;
if (eap->cmdidx == CMD_lwindow) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL)
return;
}
/* Look for an existing quickfix window. */
win = qf_find_win(qi);
/*
* If a quickfix window is open but we have no errors to display,
* close the window. If a quickfix window is not open, then open
* it if we have errors; otherwise, leave it closed.
*/
if (qi->qf_lists[qi->qf_curlist].qf_nonevalid
|| qi->qf_lists[qi->qf_curlist].qf_count == 0
|| qi->qf_curlist >= qi->qf_listcount) {
if (win != NULL)
ex_cclose(eap);
} else if (win == NULL)
ex_copen(eap);
}
/*
* ":cclose": close the window showing the list of errors.
* ":lclose": close the window showing the location list
*/
void ex_cclose(exarg_T *eap)
{
win_T *win = NULL;
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_lclose || eap->cmdidx == CMD_lwindow) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL)
return;
}
/* Find existing quickfix window and close it. */
win = qf_find_win(qi);
if (win != NULL)
win_close(win, FALSE);
}
/*
* ":copen": open a window that shows the list of errors.
* ":lopen": open a window that shows the location list.
*/
void ex_copen(exarg_T *eap)
{
qf_info_T *qi = &ql_info;
int height;
win_T *win;
tabpage_T *prevtab = curtab;
buf_T *qf_buf;
win_T *oldwin = curwin;
if (eap->cmdidx == CMD_lopen || eap->cmdidx == CMD_lwindow) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
EMSG(_(e_loclist));
return;
}
}
if (eap->addr_count != 0) {
assert(eap->line2 <= INT_MAX);
height = (int)eap->line2;
} else {
height = QF_WINHEIGHT;
}
reset_VIsual_and_resel(); // stop Visual mode
/*
* Find existing quickfix window, or open a new one.
*/
win = qf_find_win(qi);
if (win != NULL && cmdmod.tab == 0) {
win_goto(win);
if (eap->addr_count != 0) {
if (cmdmod.split & WSP_VERT) {
if (height != win->w_width) {
win_setwidth(height);
}
} else {
if (height != win->w_height) {
win_setheight(height);
}
}
}
} else {
qf_buf = qf_find_buf(qi);
/* The current window becomes the previous window afterwards. */
win = curwin;
if ((eap->cmdidx == CMD_copen || eap->cmdidx == CMD_cwindow)
&& cmdmod.split == 0)
/* Create the new window at the very bottom, except when
* :belowright or :aboveleft is used. */
win_goto(lastwin);
if (win_split(height, WSP_BELOW | WSP_NEWLOC) == FAIL)
return; /* not enough room for window */
RESET_BINDING(curwin);
if (eap->cmdidx == CMD_lopen || eap->cmdidx == CMD_lwindow) {
/*
* For the location list window, create a reference to the
* location list from the window 'win'.
*/
curwin->w_llist_ref = win->w_llist;
win->w_llist->qf_refcount++;
}
if (oldwin != curwin)
oldwin = NULL; /* don't store info when in another window */
if (qf_buf != NULL)
/* Use the existing quickfix buffer */
(void)do_ecmd(qf_buf->b_fnum, NULL, NULL, NULL, ECMD_ONE,
ECMD_HIDE + ECMD_OLDBUF, oldwin);
else {
/* Create a new quickfix buffer */
(void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, oldwin);
/* switch off 'swapfile' */
set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL);
set_option_value((char_u *)"bt", 0L, (char_u *)"quickfix",
OPT_LOCAL);
set_option_value((char_u *)"bh", 0L, (char_u *)"wipe", OPT_LOCAL);
RESET_BINDING(curwin);
curwin->w_p_diff = FALSE;
set_option_value((char_u *)"fdm", 0L, (char_u *)"manual",
OPT_LOCAL);
}
/* Only set the height when still in the same tab page and there is no
* window to the side. */
if (curtab == prevtab
&& curwin->w_width == Columns
)
win_setheight(height);
curwin->w_p_wfh = TRUE; /* set 'winfixheight' */
if (win_valid(win))
prevwin = win;
}
qf_set_title_var(qi);
// Fill the buffer with the quickfix list.
qf_fill_buffer(qi);
curwin->w_cursor.lnum = qi->qf_lists[qi->qf_curlist].qf_index;
curwin->w_cursor.col = 0;
check_cursor();
update_topline(); /* scroll to show the line */
}
/*
* Return the number of the current entry (line number in the quickfix
* window).
*/
linenr_T qf_current_entry(win_T *wp)
{
qf_info_T *qi = &ql_info;
if (IS_LL_WINDOW(wp))
/* In the location list window, use the referenced location list */
qi = wp->w_llist_ref;
return qi->qf_lists[qi->qf_curlist].qf_index;
}
/*
* Update the cursor position in the quickfix window to the current error.
* Return TRUE if there is a quickfix window.
*/
static int
qf_win_pos_update (
qf_info_T *qi,
int old_qf_index /* previous qf_index or zero */
)
{
win_T *win;
int qf_index = qi->qf_lists[qi->qf_curlist].qf_index;
/*
* Put the cursor on the current error in the quickfix window, so that
* it's viewable.
*/
win = qf_find_win(qi);
if (win != NULL
&& qf_index <= win->w_buffer->b_ml.ml_line_count
&& old_qf_index != qf_index) {
win_T *old_curwin = curwin;
curwin = win;
curbuf = win->w_buffer;
if (qf_index > old_qf_index) {
curwin->w_redraw_top = old_qf_index;
curwin->w_redraw_bot = qf_index;
} else {
curwin->w_redraw_top = qf_index;
curwin->w_redraw_bot = old_qf_index;
}
curwin->w_cursor.lnum = qf_index;
curwin->w_cursor.col = 0;
update_topline(); /* scroll to show the line */
redraw_later(VALID);
curwin->w_redr_status = TRUE; /* update ruler */
curwin = old_curwin;
curbuf = curwin->w_buffer;
}
return win != NULL;
}
/*
* Check whether the given window is displaying the specified quickfix/location
* list buffer
*/
static int is_qf_win(win_T *win, qf_info_T *qi)
{
/*
* A window displaying the quickfix buffer will have the w_llist_ref field
* set to NULL.
* A window displaying a location list buffer will have the w_llist_ref
* pointing to the location list.
*/
if (bt_quickfix(win->w_buffer))
if ((qi == &ql_info && win->w_llist_ref == NULL)
|| (qi != &ql_info && win->w_llist_ref == qi))
return TRUE;
return FALSE;
}
/*
* Find a window displaying the quickfix/location list 'qi'
* Searches in only the windows opened in the current tab.
*/
static win_T *qf_find_win(qf_info_T *qi)
{
FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
if (is_qf_win(win, qi)) {
return win;
}
}
return NULL;
}
/*
* Find a quickfix buffer.
* Searches in windows opened in all the tabs.
*/
static buf_T *qf_find_buf(qf_info_T *qi)
{
FOR_ALL_TAB_WINDOWS(tp, win) {
if (is_qf_win(win, qi)) {
return win->w_buffer;
}
}
return NULL;
}
/*
* Find the quickfix buffer. If it exists, update the contents.
*/
static void qf_update_buffer(qf_info_T *qi)
{
buf_T *buf;
win_T *win;
win_T *curwin_save;
aco_save_T aco;
/* Check if a buffer for the quickfix list exists. Update it. */
buf = qf_find_buf(qi);
if (buf != NULL) {
/* set curwin/curbuf to buf and save a few things */
aucmd_prepbuf(&aco, buf);
if ((win = qf_find_win(qi)) != NULL) {
curwin_save = curwin;
curwin = win;
qf_set_title_var(qi);
curwin = curwin_save;
}
qf_fill_buffer(qi);
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
(void)qf_win_pos_update(qi, 0);
}
}
// Set "w:quickfix_title" if "qi" has a title.
static void qf_set_title_var(qf_info_T *qi)
{
if (qi->qf_lists[qi->qf_curlist].qf_title != NULL) {
set_internal_string_var((char_u *)"w:quickfix_title",
qi->qf_lists[qi->qf_curlist].qf_title);
}
}
/*
* Fill current buffer with quickfix errors, replacing any previous contents.
* curbuf must be the quickfix buffer!
*/
static void qf_fill_buffer(qf_info_T *qi)
{
linenr_T lnum;
qfline_T *qfp;
buf_T *errbuf;
int len;
int old_KeyTyped = KeyTyped;
/* delete all existing lines */
while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0)
(void)ml_delete((linenr_T)1, FALSE);
/* Check if there is anything to display */
if (qi->qf_curlist < qi->qf_listcount) {
/* Add one line for each error */
qfp = qi->qf_lists[qi->qf_curlist].qf_start;
for (lnum = 0; lnum < qi->qf_lists[qi->qf_curlist].qf_count; ++lnum) {
if (qfp->qf_fnum != 0
&& (errbuf = buflist_findnr(qfp->qf_fnum)) != NULL
&& errbuf->b_fname != NULL) {
if (qfp->qf_type == 1) { // :helpgrep
STRLCPY(IObuff, path_tail(errbuf->b_fname), sizeof(IObuff));
} else {
STRLCPY(IObuff, errbuf->b_fname, sizeof(IObuff));
}
len = (int)STRLEN(IObuff);
} else {
len = 0;
}
IObuff[len++] = '|';
if (qfp->qf_lnum > 0) {
sprintf((char *)IObuff + len, "%" PRId64, (int64_t)qfp->qf_lnum);
len += (int)STRLEN(IObuff + len);
if (qfp->qf_col > 0) {
sprintf((char *)IObuff + len, " col %d", qfp->qf_col);
len += (int)STRLEN(IObuff + len);
}
sprintf((char *)IObuff + len, "%s",
(char *)qf_types(qfp->qf_type, qfp->qf_nr));
len += (int)STRLEN(IObuff + len);
} else if (qfp->qf_pattern != NULL) {
qf_fmt_text(qfp->qf_pattern, IObuff + len, IOSIZE - len);
len += (int)STRLEN(IObuff + len);
}
IObuff[len++] = '|';
IObuff[len++] = ' ';
/* Remove newlines and leading whitespace from the text.
* For an unrecognized line keep the indent, the compiler may
* mark a word with ^^^^. */
qf_fmt_text(len > 3 ? skipwhite(qfp->qf_text) : qfp->qf_text,
IObuff + len, IOSIZE - len);
if (ml_append(lnum, IObuff, (colnr_T)STRLEN(IObuff) + 1, FALSE)
== FAIL)
break;
qfp = qfp->qf_next;
}
/* Delete the empty line which is now at the end */
(void)ml_delete(lnum + 1, FALSE);
}
/* correct cursor position */
check_lnums(TRUE);
/* Set the 'filetype' to "qf" each time after filling the buffer. This
* resembles reading a file into a buffer, it's more logical when using
* autocommands. */
set_option_value((char_u *)"ft", 0L, (char_u *)"qf", OPT_LOCAL);
curbuf->b_p_ma = FALSE;
keep_filetype = TRUE; /* don't detect 'filetype' */
apply_autocmds(EVENT_BUFREADPOST, (char_u *)"quickfix", NULL,
FALSE, curbuf);
apply_autocmds(EVENT_BUFWINENTER, (char_u *)"quickfix", NULL,
FALSE, curbuf);
keep_filetype = FALSE;
/* make sure it will be redrawn */
redraw_curbuf_later(NOT_VALID);
/* Restore KeyTyped, setting 'filetype' may reset it. */
KeyTyped = old_KeyTyped;
}
/*
* Return TRUE if "buf" is the quickfix buffer.
*/
int bt_quickfix(buf_T *buf)
{
return buf != NULL && buf->b_p_bt[0] == 'q';
}
// Return TRUE if "buf" is a "nofile", "acwrite" or "terminal" buffer.
// This means the buffer name is not a file name.
int bt_nofile(buf_T *buf)
{
return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f')
|| buf->b_p_bt[0] == 'a' || buf->terminal);
}
// Return TRUE if "buf" is a "nowrite", "nofile" or "terminal" buffer.
int bt_dontwrite(buf_T *buf)
{
return buf != NULL && (buf->b_p_bt[0] == 'n' || buf->terminal);
}
int bt_dontwrite_msg(buf_T *buf)
{
if (bt_dontwrite(buf)) {
EMSG(_("E382: Cannot write, 'buftype' option is set"));
return TRUE;
}
return FALSE;
}
/*
* Return TRUE if the buffer should be hidden, according to 'hidden', ":hide"
* and 'bufhidden'.
*/
int buf_hide(buf_T *buf)
{
/* 'bufhidden' overrules 'hidden' and ":hide", check it first */
switch (buf->b_p_bh[0]) {
case 'u': /* "unload" */
case 'w': /* "wipe" */
case 'd': return FALSE; /* "delete" */
case 'h': return TRUE; /* "hide" */
}
return p_hid || cmdmod.hide;
}
/*
* Return TRUE when using ":vimgrep" for ":grep".
*/
int grep_internal(cmdidx_T cmdidx)
{
return (cmdidx == CMD_grep
|| cmdidx == CMD_lgrep
|| cmdidx == CMD_grepadd
|| cmdidx == CMD_lgrepadd)
&& STRCMP("internal",
*curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp) == 0;
}
/*
* Used for ":make", ":lmake", ":grep", ":lgrep", ":grepadd", and ":lgrepadd"
*/
void ex_make(exarg_T *eap)
{
char_u *fname;
win_T *wp = NULL;
qf_info_T *qi = &ql_info;
int res;
char_u *au_name = NULL;
/* Redirect ":grep" to ":vimgrep" if 'grepprg' is "internal". */
if (grep_internal(eap->cmdidx)) {
ex_vimgrep(eap);
return;
}
switch (eap->cmdidx) {
case CMD_make: au_name = (char_u *)"make"; break;
case CMD_lmake: au_name = (char_u *)"lmake"; break;
case CMD_grep: au_name = (char_u *)"grep"; break;
case CMD_lgrep: au_name = (char_u *)"lgrep"; break;
case CMD_grepadd: au_name = (char_u *)"grepadd"; break;
case CMD_lgrepadd: au_name = (char_u *)"lgrepadd"; break;
default: break;
}
if (au_name != NULL) {
apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
curbuf->b_fname, TRUE, curbuf);
if (did_throw || force_abort)
return;
}
if (eap->cmdidx == CMD_lmake || eap->cmdidx == CMD_lgrep
|| eap->cmdidx == CMD_lgrepadd)
wp = curwin;
autowrite_all();
fname = get_mef_name();
if (fname == NULL)
return;
os_remove((char *)fname); // in case it's not unique
// If 'shellpipe' empty: don't redirect to 'errorfile'.
const size_t len = (STRLEN(p_shq) * 2 + STRLEN(eap->arg) + 1
+ (*p_sp == NUL
? 0
: STRLEN(p_sp) + STRLEN(fname) + 3));
char *const cmd = xmalloc(len);
snprintf(cmd, len, "%s%s%s", (char *)p_shq, (char *)eap->arg,
(char *)p_shq);
if (*p_sp != NUL) {
append_redir(cmd, len, (char *) p_sp, (char *) fname);
}
// Output a newline if there's something else than the :make command that
// was typed (in which case the cursor is in column 0).
if (msg_col == 0) {
msg_didout = false;
}
msg_start();
MSG_PUTS(":!");
msg_outtrans((char_u *) cmd); // show what we are doing
// let the shell know if we are redirecting output or not
do_shell((char_u *) cmd, *p_sp != NUL ? kShellOptDoOut : 0);
res = qf_init(wp, fname, (eap->cmdidx != CMD_make
&& eap->cmdidx != CMD_lmake) ? p_gefm : p_efm,
(eap->cmdidx != CMD_grepadd
&& eap->cmdidx != CMD_lgrepadd),
*eap->cmdlinep);
if (wp != NULL)
qi = GET_LOC_LIST(wp);
if (au_name != NULL) {
apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name,
curbuf->b_fname, TRUE, curbuf);
if (qi->qf_curlist < qi->qf_listcount)
res = qi->qf_lists[qi->qf_curlist].qf_count;
else
res = 0;
}
if (res > 0 && !eap->forceit)
qf_jump(qi, 0, 0, FALSE); /* display first error */
os_remove((char *)fname);
xfree(fname);
xfree(cmd);
}
/*
* Return the name for the errorfile, in allocated memory.
* Find a new unique name when 'makeef' contains "##".
* Returns NULL for error.
*/
static char_u *get_mef_name(void)
{
char_u *p;
char_u *name;
static int start = -1;
static int off = 0;
if (*p_mef == NUL) {
name = vim_tempname();
if (name == NULL)
EMSG(_(e_notmp));
return name;
}
for (p = p_mef; *p; ++p)
if (p[0] == '#' && p[1] == '#')
break;
if (*p == NUL)
return vim_strsave(p_mef);
/* Keep trying until the name doesn't exist yet. */
for (;; ) {
if (start == -1) {
start = (int)os_get_pid();
} else {
off += 19;
}
name = xmalloc(STRLEN(p_mef) + 30);
STRCPY(name, p_mef);
sprintf((char *)name + (p - p_mef), "%d%d", start, off);
STRCAT(name, p + 2);
// Don't accept a symbolic link, its a security risk.
FileInfo file_info;
bool file_or_link_found = os_fileinfo_link((char *)name, &file_info);
if (!file_or_link_found) {
break;
}
xfree(name);
}
return name;
}
/// Returns the number of valid entries in the current quickfix/location list.
size_t qf_get_size(exarg_T *eap)
FUNC_ATTR_NONNULL_ALL
{
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_ldo || eap->cmdidx == CMD_lfdo) {
// Location list.
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
return 0;
}
}
int prev_fnum = 0;
size_t sz = 0;
qfline_T *qfp;
size_t i;
assert(qi->qf_lists[qi->qf_curlist].qf_count >= 0);
for (i = 0, qfp = qi->qf_lists[qi->qf_curlist].qf_start;
i < (size_t)qi->qf_lists[qi->qf_curlist].qf_count && qfp != NULL;
i++, qfp = qfp->qf_next) {
if (!qfp->qf_valid) {
continue;
}
if (eap->cmdidx == CMD_cdo || eap->cmdidx == CMD_ldo) {
// Count all valid entries.
sz++;
} else if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
// Count the number of files.
sz++;
prev_fnum = qfp->qf_fnum;
}
}
return sz;
}
/// Returns the current index of the quickfix/location list.
/// Returns 0 if there is an error.
size_t qf_get_cur_idx(exarg_T *eap)
FUNC_ATTR_NONNULL_ALL
{
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_ldo || eap->cmdidx == CMD_lfdo) {
// Location list.
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
return 0;
}
}
assert(qi->qf_lists[qi->qf_curlist].qf_index >= 0);
return (size_t)qi->qf_lists[qi->qf_curlist].qf_index;
}
/// Returns the current index in the quickfix/location list,
/// counting only valid entries.
/// Returns 1 if there are no valid entries.
int qf_get_cur_valid_idx(exarg_T *eap)
FUNC_ATTR_NONNULL_ALL
{
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_ldo || eap->cmdidx == CMD_lfdo) {
// Location list.
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
return 1;
}
}
qf_list_T *qfl = &qi->qf_lists[qi->qf_curlist];
// Check if the list has valid errors.
if (qfl->qf_count <= 0 || qfl->qf_nonevalid) {
return 1;
}
int prev_fnum = 0;
int eidx = 0;
qfline_T *qfp;
size_t i;
assert(qfl->qf_index >= 0);
for (i = 1, qfp = qfl->qf_start;
i <= (size_t)qfl->qf_index && qfp != NULL;
i++, qfp = qfp->qf_next) {
if (!qfp->qf_valid) {
continue;
}
if (eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo) {
if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
// Count the number of files.
eidx++;
prev_fnum = qfp->qf_fnum;
}
} else {
eidx++;
}
}
return eidx != 0 ? eidx : 1;
}
/// Get the 'n'th valid error entry in the quickfix or location list.
///
/// Used by :cdo, :ldo, :cfdo and :lfdo commands.
/// For :cdo and :ldo, returns the 'n'th valid error entry.
/// For :cfdo and :lfdo, returns the 'n'th valid file entry.
static size_t qf_get_nth_valid_entry(qf_info_T *qi, size_t n, bool fdo)
FUNC_ATTR_NONNULL_ALL
{
qf_list_T *qfl = &qi->qf_lists[qi->qf_curlist];
// Check if the list has valid errors.
if (qfl->qf_count <= 0 || qfl->qf_nonevalid) {
return 1;
}
int prev_fnum = 0;
size_t eidx = 0;
size_t i;
qfline_T *qfp;
assert(qfl->qf_count >= 0);
for (i = 1, qfp = qfl->qf_start;
i <= (size_t)qfl->qf_count && qfp != NULL;
i++, qfp = qfp->qf_next) {
if (qfp->qf_valid) {
if (fdo) {
if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
// Count the number of files.
eidx++;
prev_fnum = qfp->qf_fnum;
}
} else {
eidx++;
}
}
if (eidx == n) {
break;
}
}
return i <= (size_t)qfl->qf_count ? i : 1;
}
/*
* ":cc", ":crewind", ":cfirst" and ":clast".
* ":ll", ":lrewind", ":lfirst" and ":llast".
* ":cdo", ":ldo", ":cfdo" and ":lfdo".
*/
void ex_cc(exarg_T *eap)
{
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_ll
|| eap->cmdidx == CMD_lrewind
|| eap->cmdidx == CMD_lfirst
|| eap->cmdidx == CMD_llast
|| eap->cmdidx == CMD_llast
|| eap->cmdidx == CMD_ldo
|| eap->cmdidx == CMD_lfdo) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
EMSG(_(e_loclist));
return;
}
}
int errornr;
if (eap->addr_count > 0) {
errornr = (int)eap->line2;
} else if (eap->cmdidx == CMD_cc || eap->cmdidx == CMD_ll) {
errornr = 0;
} else if (eap->cmdidx == CMD_crewind || eap->cmdidx == CMD_lrewind
|| eap->cmdidx == CMD_cfirst || eap->cmdidx == CMD_lfirst) {
errornr = 1;
} else {
errornr = 32767;
}
// For cdo and ldo commands, jump to the nth valid error.
// For cfdo and lfdo commands, jump to the nth valid file entry.
if (eap->cmdidx == CMD_cdo || eap->cmdidx == CMD_ldo
|| eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo) {
size_t n;
if (eap->addr_count > 0) {
assert(eap->line1 >= 0);
n = (size_t)eap->line1;
} else {
n = 1;
}
size_t valid_entry = qf_get_nth_valid_entry(qi, n,
eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo);
assert(valid_entry <= INT_MAX);
errornr = (int)valid_entry;
}
qf_jump(qi, 0, errornr, eap->forceit);
}
/*
* ":cnext", ":cnfile", ":cNext" and ":cprevious".
* ":lnext", ":lNext", ":lprevious", ":lnfile", ":lNfile" and ":lpfile".
* ":cdo", ":ldo", ":cfdo" and ":lfdo".
*/
void ex_cnext(exarg_T *eap)
{
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_lnext
|| eap->cmdidx == CMD_lNext
|| eap->cmdidx == CMD_lprevious
|| eap->cmdidx == CMD_lnfile
|| eap->cmdidx == CMD_lNfile
|| eap->cmdidx == CMD_lpfile
|| eap->cmdidx == CMD_lpfile
|| eap->cmdidx == CMD_ldo
|| eap->cmdidx == CMD_lfdo) {
qi = GET_LOC_LIST(curwin);
if (qi == NULL) {
EMSG(_(e_loclist));
return;
}
}
int errornr;
if (eap->addr_count > 0
&& (eap->cmdidx != CMD_cdo && eap->cmdidx != CMD_ldo
&& eap->cmdidx != CMD_cfdo && eap->cmdidx != CMD_lfdo)) {
errornr = (int)eap->line2;
} else {
errornr = 1;
}
qf_jump(qi, (eap->cmdidx == CMD_cnext || eap->cmdidx == CMD_lnext
|| eap->cmdidx == CMD_cdo || eap->cmdidx == CMD_ldo)
? FORWARD
: (eap->cmdidx == CMD_cnfile || eap->cmdidx == CMD_lnfile
|| eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo)
? FORWARD_FILE
: (eap->cmdidx == CMD_cpfile || eap->cmdidx == CMD_lpfile
|| eap->cmdidx == CMD_cNfile || eap->cmdidx == CMD_lNfile)
? BACKWARD_FILE
: BACKWARD,
errornr, eap->forceit);
}
/*
* ":cfile"/":cgetfile"/":caddfile" commands.
* ":lfile"/":lgetfile"/":laddfile" commands.
*/
void ex_cfile(exarg_T *eap)
{
win_T *wp = NULL;
qf_info_T *qi = &ql_info;
char_u *au_name = NULL;
if (eap->cmdidx == CMD_lfile || eap->cmdidx == CMD_lgetfile
|| eap->cmdidx == CMD_laddfile)
wp = curwin;
switch (eap->cmdidx) {
case CMD_cfile: au_name = (char_u *)"cfile"; break;
case CMD_cgetfile: au_name = (char_u *)"cgetfile"; break;
case CMD_caddfile: au_name = (char_u *)"caddfile"; break;
case CMD_lfile: au_name = (char_u *)"lfile"; break;
case CMD_lgetfile: au_name = (char_u *)"lgetfile"; break;
case CMD_laddfile: au_name = (char_u *)"laddfile"; break;
default: break;
}
if (au_name != NULL)
apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, NULL, FALSE, curbuf);
if (*eap->arg != NUL)
set_string_option_direct((char_u *)"ef", -1, eap->arg, OPT_FREE, 0);
/*
* This function is used by the :cfile, :cgetfile and :caddfile
* commands.
* :cfile always creates a new quickfix list and jumps to the
* first error.
* :cgetfile creates a new quickfix list but doesn't jump to the
* first error.
* :caddfile adds to an existing quickfix list. If there is no
* quickfix list then a new list is created.
*/
if (qf_init(wp, p_ef, p_efm, (eap->cmdidx != CMD_caddfile
&& eap->cmdidx != CMD_laddfile),
*eap->cmdlinep) > 0
&& (eap->cmdidx == CMD_cfile
|| eap->cmdidx == CMD_lfile)) {
if (au_name != NULL)
apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, NULL, FALSE, curbuf);
if (wp != NULL)
qi = GET_LOC_LIST(wp);
qf_jump(qi, 0, 0, eap->forceit); /* display first error */
} else {
if (au_name != NULL)
apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, NULL, FALSE, curbuf);
}
}
/*
* ":vimgrep {pattern} file(s)"
* ":vimgrepadd {pattern} file(s)"
* ":lvimgrep {pattern} file(s)"
* ":lvimgrepadd {pattern} file(s)"
*/
void ex_vimgrep(exarg_T *eap)
{
regmmatch_T regmatch;
int fcount;
char_u **fnames;
char_u *fname;
char_u *s;
char_u *p;
int fi;
qf_info_T *qi = &ql_info;
qfline_T *cur_qf_start;
qfline_T *prevp = NULL;
long lnum;
buf_T *buf;
int duplicate_name = FALSE;
int using_dummy;
int redraw_for_dummy = FALSE;
int found_match;
buf_T *first_match_buf = NULL;
time_t seconds = 0;
long save_mls;
char_u *save_ei = NULL;
aco_save_T aco;
int flags = 0;
colnr_T col;
long tomatch;
char_u *dirname_start = NULL;
char_u *dirname_now = NULL;
char_u *target_dir = NULL;
char_u *au_name = NULL;
switch (eap->cmdidx) {
case CMD_vimgrep: au_name = (char_u *)"vimgrep"; break;
case CMD_lvimgrep: au_name = (char_u *)"lvimgrep"; break;
case CMD_vimgrepadd: au_name = (char_u *)"vimgrepadd"; break;
case CMD_lvimgrepadd: au_name = (char_u *)"lvimgrepadd"; break;
case CMD_grep: au_name = (char_u *)"grep"; break;
case CMD_lgrep: au_name = (char_u *)"lgrep"; break;
case CMD_grepadd: au_name = (char_u *)"grepadd"; break;
case CMD_lgrepadd: au_name = (char_u *)"lgrepadd"; break;
default: break;
}
if (au_name != NULL) {
apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
curbuf->b_fname, TRUE, curbuf);
if (did_throw || force_abort)
return;
}
if (eap->cmdidx == CMD_lgrep
|| eap->cmdidx == CMD_lvimgrep
|| eap->cmdidx == CMD_lgrepadd
|| eap->cmdidx == CMD_lvimgrepadd) {
qi = ll_get_or_alloc_list(curwin);
}
if (eap->addr_count > 0)
tomatch = eap->line2;
else
tomatch = MAXLNUM;
/* Get the search pattern: either white-separated or enclosed in // */
regmatch.regprog = NULL;
p = skip_vimgrep_pat(eap->arg, &s, &flags);
if (p == NULL) {
EMSG(_(e_invalpat));
goto theend;
}
if (s != NULL && *s == NUL) {
/* Pattern is empty, use last search pattern. */
if (last_search_pat() == NULL) {
EMSG(_(e_noprevre));
goto theend;
}
regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
} else
regmatch.regprog = vim_regcomp(s, RE_MAGIC);
if (regmatch.regprog == NULL)
goto theend;
regmatch.rmm_ic = p_ic;
regmatch.rmm_maxcol = 0;
p = skipwhite(p);
if (*p == NUL) {
EMSG(_("E683: File name missing or invalid pattern"));
goto theend;
}
if ((eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd
&& eap->cmdidx != CMD_vimgrepadd && eap->cmdidx != CMD_lvimgrepadd)
|| qi->qf_curlist == qi->qf_listcount) {
// make place for a new list
qf_new_list(qi, *eap->cmdlinep);
} else if (qi->qf_lists[qi->qf_curlist].qf_count > 0) {
// Adding to existing list, find last entry.
for (prevp = qi->qf_lists[qi->qf_curlist].qf_start;
prevp->qf_next != prevp;
prevp = prevp->qf_next) {
}
}
/* parse the list of arguments */
if (get_arglist_exp(p, &fcount, &fnames, true) == FAIL)
goto theend;
if (fcount == 0) {
EMSG(_(e_nomatch));
goto theend;
}
dirname_start = xmalloc(MAXPATHL);
dirname_now = xmalloc(MAXPATHL);
/* Remember the current directory, because a BufRead autocommand that does
* ":lcd %:p:h" changes the meaning of short path names. */
os_dirname(dirname_start, MAXPATHL);
/* Remember the value of qf_start, so that we can check for autocommands
* changing the current quickfix list. */
cur_qf_start = qi->qf_lists[qi->qf_curlist].qf_start;
seconds = (time_t)0;
for (fi = 0; fi < fcount && !got_int && tomatch > 0; ++fi) {
fname = path_shorten_fname_if_possible(fnames[fi]);
if (time(NULL) > seconds) {
/* Display the file name every second or so, show the user we are
* working on it. */
seconds = time(NULL);
msg_start();
p = msg_strtrunc(fname, TRUE);
if (p == NULL)
msg_outtrans(fname);
else {
msg_outtrans(p);
xfree(p);
}
msg_clr_eos();
msg_didout = FALSE; /* overwrite this message */
msg_nowait = TRUE; /* don't wait for this message */
msg_col = 0;
ui_flush();
}
buf = buflist_findname_exp(fnames[fi]);
if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
/* Remember that a buffer with this name already exists. */
duplicate_name = (buf != NULL);
using_dummy = TRUE;
redraw_for_dummy = TRUE;
/* Don't do Filetype autocommands to avoid loading syntax and
* indent scripts, a great speed improvement. */
save_ei = au_event_disable(",Filetype");
/* Don't use modelines here, it's useless. */
save_mls = p_mls;
p_mls = 0;
/* Load file into a buffer, so that 'fileencoding' is detected,
* autocommands applied, etc. */
buf = load_dummy_buffer(fname, dirname_start, dirname_now);
p_mls = save_mls;
au_event_restore(save_ei);
} else
/* Use existing, loaded buffer. */
using_dummy = FALSE;
if (cur_qf_start != qi->qf_lists[qi->qf_curlist].qf_start) {
int idx;
/* Autocommands changed the quickfix list. Find the one we were
* using and restore it. */
for (idx = 0; idx < LISTCOUNT; ++idx)
if (cur_qf_start == qi->qf_lists[idx].qf_start) {
qi->qf_curlist = idx;
break;
}
if (idx == LISTCOUNT) {
/* List cannot be found, create a new one. */
qf_new_list(qi, *eap->cmdlinep);
cur_qf_start = qi->qf_lists[qi->qf_curlist].qf_start;
}
}
if (buf == NULL) {
if (!got_int)
smsg(_("Cannot open file \"%s\""), fname);
} else {
/* Try for a match in all lines of the buffer.
* For ":1vimgrep" look for first match only. */
found_match = FALSE;
for (lnum = 1; lnum <= buf->b_ml.ml_line_count && tomatch > 0;
++lnum) {
col = 0;
while (vim_regexec_multi(®match, curwin, buf, lnum,
col, NULL) > 0) {
;
if (qf_add_entry(qi, &prevp,
NULL, /* dir */
fname,
0,
ml_get_buf(buf,
regmatch.startpos[0].lnum + lnum, FALSE),
regmatch.startpos[0].lnum + lnum,
regmatch.startpos[0].col + 1,
FALSE, /* vis_col */
NULL, /* search pattern */
0, /* nr */
0, /* type */
TRUE /* valid */
) == FAIL) {
got_int = TRUE;
break;
}
found_match = TRUE;
if (--tomatch == 0)
break;
if ((flags & VGR_GLOBAL) == 0
|| regmatch.endpos[0].lnum > 0)
break;
col = regmatch.endpos[0].col
+ (col == regmatch.endpos[0].col);
if (col > (colnr_T)STRLEN(ml_get_buf(buf, lnum, FALSE)))
break;
}
line_breakcheck();
if (got_int)
break;
}
cur_qf_start = qi->qf_lists[qi->qf_curlist].qf_start;
if (using_dummy) {
if (found_match && first_match_buf == NULL)
first_match_buf = buf;
if (duplicate_name) {
/* Never keep a dummy buffer if there is another buffer
* with the same name. */
wipe_dummy_buffer(buf, dirname_start);
buf = NULL;
} else if (!cmdmod.hide
|| buf->b_p_bh[0] == 'u' /* "unload" */
|| buf->b_p_bh[0] == 'w' /* "wipe" */
|| buf->b_p_bh[0] == 'd') { /* "delete" */
/* When no match was found we don't need to remember the
* buffer, wipe it out. If there was a match and it
* wasn't the first one or we won't jump there: only
* unload the buffer.
* Ignore 'hidden' here, because it may lead to having too
* many swap files. */
if (!found_match) {
wipe_dummy_buffer(buf, dirname_start);
buf = NULL;
} else if (buf != first_match_buf || (flags & VGR_NOJUMP)) {
unload_dummy_buffer(buf, dirname_start);
buf = NULL;
}
}
if (buf != NULL) {
/* If the buffer is still loaded we need to use the
* directory we jumped to below. */
if (buf == first_match_buf
&& target_dir == NULL
&& STRCMP(dirname_start, dirname_now) != 0)
target_dir = vim_strsave(dirname_now);
/* The buffer is still loaded, the Filetype autocommands
* need to be done now, in that buffer. And the modelines
* need to be done (again). But not the window-local
* options! */
aucmd_prepbuf(&aco, buf);
apply_autocmds(EVENT_FILETYPE, buf->b_p_ft,
buf->b_fname, TRUE, buf);
do_modelines(OPT_NOWIN);
aucmd_restbuf(&aco);
}
}
}
}
FreeWild(fcount, fnames);
qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE;
qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start;
qi->qf_lists[qi->qf_curlist].qf_index = 1;
qf_update_buffer(qi);
if (au_name != NULL)
apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name,
curbuf->b_fname, TRUE, curbuf);
/* Jump to first match. */
if (qi->qf_lists[qi->qf_curlist].qf_count > 0) {
if ((flags & VGR_NOJUMP) == 0) {
buf = curbuf;
qf_jump(qi, 0, 0, eap->forceit);
if (buf != curbuf)
/* If we jumped to another buffer redrawing will already be
* taken care of. */
redraw_for_dummy = FALSE;
/* Jump to the directory used after loading the buffer. */
if (curbuf == first_match_buf && target_dir != NULL) {
exarg_T ea;
ea.arg = target_dir;
ea.cmdidx = CMD_lcd;
ex_cd(&ea);
}
}
} else
EMSG2(_(e_nomatch2), s);
/* If we loaded a dummy buffer into the current window, the autocommands
* may have messed up things, need to redraw and recompute folds. */
if (redraw_for_dummy) {
foldUpdateAll(curwin);
}
theend:
xfree(dirname_now);
xfree(dirname_start);
xfree(target_dir);
vim_regfree(regmatch.regprog);
}
/*
* Skip over the pattern argument of ":vimgrep /pat/[g][j]".
* Put the start of the pattern in "*s", unless "s" is NULL.
* If "flags" is not NULL put the flags in it: VGR_GLOBAL, VGR_NOJUMP.
* If "s" is not NULL terminate the pattern with a NUL.
* Return a pointer to the char just past the pattern plus flags.
*/
char_u *skip_vimgrep_pat(char_u *p, char_u **s, int *flags)
{
int c;
if (vim_isIDc(*p)) {
/* ":vimgrep pattern fname" */
if (s != NULL)
*s = p;
p = skiptowhite(p);
if (s != NULL && *p != NUL)
*p++ = NUL;
} else {
/* ":vimgrep /pattern/[g][j] fname" */
if (s != NULL)
*s = p + 1;
c = *p;
p = skip_regexp(p + 1, c, TRUE, NULL);
if (*p != c)
return NULL;
/* Truncate the pattern. */
if (s != NULL)
*p = NUL;
++p;
/* Find the flags */
while (*p == 'g' || *p == 'j') {
if (flags != NULL) {
if (*p == 'g')
*flags |= VGR_GLOBAL;
else
*flags |= VGR_NOJUMP;
}
++p;
}
}
return p;
}
/*
* Restore current working directory to "dirname_start" if they differ, taking
* into account whether it is set locally or globally.
*/
static void restore_start_dir(char_u *dirname_start)
{
char_u *dirname_now = xmalloc(MAXPATHL);
os_dirname(dirname_now, MAXPATHL);
if (STRCMP(dirname_start, dirname_now) != 0) {
/* If the directory has changed, change it back by building up an
* appropriate ex command and executing it. */
exarg_T ea;
ea.arg = dirname_start;
ea.cmdidx = (curwin->w_localdir == NULL) ? CMD_cd : CMD_lcd;
ex_cd(&ea);
}
xfree(dirname_now);
}
/*
* Load file "fname" into a dummy buffer and return the buffer pointer,
* placing the directory resulting from the buffer load into the
* "resulting_dir" pointer. "resulting_dir" must be allocated by the caller
* prior to calling this function. Restores directory to "dirname_start" prior
* to returning, if autocmds or the 'autochdir' option have changed it.
*
* If creating the dummy buffer does not fail, must call unload_dummy_buffer()
* or wipe_dummy_buffer() later!
*
* Returns NULL if it fails.
*/
static buf_T *
load_dummy_buffer (
char_u *fname,
char_u *dirname_start, /* in: old directory */
char_u *resulting_dir /* out: new directory */
)
{
buf_T *newbuf;
buf_T *newbuf_to_wipe = NULL;
int failed = TRUE;
aco_save_T aco;
/* Allocate a buffer without putting it in the buffer list. */
newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
if (newbuf == NULL)
return NULL;
/* Init the options. */
buf_copy_options(newbuf, BCO_ENTER | BCO_NOHELP);
/* need to open the memfile before putting the buffer in a window */
if (ml_open(newbuf) == OK) {
/* set curwin/curbuf to buf and save a few things */
aucmd_prepbuf(&aco, newbuf);
/* Need to set the filename for autocommands. */
(void)setfname(curbuf, fname, NULL, FALSE);
/* Create swap file now to avoid the ATTENTION message. */
check_need_swap(TRUE);
/* Remove the "dummy" flag, otherwise autocommands may not
* work. */
curbuf->b_flags &= ~BF_DUMMY;
if (readfile(fname, NULL,
(linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM,
NULL, READ_NEW | READ_DUMMY) == OK
&& !got_int
&& !(curbuf->b_flags & BF_NEW)) {
failed = FALSE;
if (curbuf != newbuf) {
/* Bloody autocommands changed the buffer! Can happen when
* using netrw and editing a remote file. Use the current
* buffer instead, delete the dummy one after restoring the
* window stuff. */
newbuf_to_wipe = newbuf;
newbuf = curbuf;
}
}
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
if (newbuf_to_wipe != NULL && buf_valid(newbuf_to_wipe))
wipe_buffer(newbuf_to_wipe, FALSE);
}
/*
* When autocommands/'autochdir' option changed directory: go back.
* Let the caller know what the resulting dir was first, in case it is
* important.
*/
os_dirname(resulting_dir, MAXPATHL);
restore_start_dir(dirname_start);
if (!buf_valid(newbuf))
return NULL;
if (failed) {
wipe_dummy_buffer(newbuf, dirname_start);
return NULL;
}
return newbuf;
}
/*
* Wipe out the dummy buffer that load_dummy_buffer() created. Restores
* directory to "dirname_start" prior to returning, if autocmds or the
* 'autochdir' option have changed it.
*/
static void wipe_dummy_buffer(buf_T *buf, char_u *dirname_start)
{
if (curbuf != buf) { /* safety check */
cleanup_T cs;
/* Reset the error/interrupt/exception state here so that aborting()
* returns FALSE when wiping out the buffer. Otherwise it doesn't
* work when got_int is set. */
enter_cleanup(&cs);
wipe_buffer(buf, FALSE);
/* Restore the error/interrupt/exception state if not discarded by a
* new aborting error, interrupt, or uncaught exception. */
leave_cleanup(&cs);
/* When autocommands/'autochdir' option changed directory: go back. */
restore_start_dir(dirname_start);
}
}
/*
* Unload the dummy buffer that load_dummy_buffer() created. Restores
* directory to "dirname_start" prior to returning, if autocmds or the
* 'autochdir' option have changed it.
*/
static void unload_dummy_buffer(buf_T *buf, char_u *dirname_start)
{
if (curbuf != buf) { /* safety check */
close_buffer(NULL, buf, DOBUF_UNLOAD, FALSE);
/* When autocommands/'autochdir' option changed directory: go back. */
restore_start_dir(dirname_start);
}
}
/*
* Add each quickfix error to list "list" as a dictionary.
*/
int get_errorlist(win_T *wp, list_T *list)
{
qf_info_T *qi = &ql_info;
dict_T *dict;
char_u buf[2];
qfline_T *qfp;
int i;
int bufnum;
if (wp != NULL) {
qi = GET_LOC_LIST(wp);
if (qi == NULL)
return FAIL;
}
if (qi->qf_curlist >= qi->qf_listcount
|| qi->qf_lists[qi->qf_curlist].qf_count == 0)
return FAIL;
qfp = qi->qf_lists[qi->qf_curlist].qf_start;
for (i = 1; !got_int && i <= qi->qf_lists[qi->qf_curlist].qf_count; ++i) {
/* Handle entries with a non-existing buffer number. */
bufnum = qfp->qf_fnum;
if (bufnum != 0 && (buflist_findnr(bufnum) == NULL))
bufnum = 0;
dict = dict_alloc();
list_append_dict(list, dict);
buf[0] = qfp->qf_type;
buf[1] = NUL;
if ( dict_add_nr_str(dict, "bufnr", (long)bufnum, NULL) == FAIL
|| dict_add_nr_str(dict, "lnum", (long)qfp->qf_lnum, NULL) == FAIL
|| dict_add_nr_str(dict, "col", (long)qfp->qf_col, NULL) == FAIL
|| dict_add_nr_str(dict, "vcol", (long)qfp->qf_viscol, NULL) == FAIL
|| dict_add_nr_str(dict, "nr", (long)qfp->qf_nr, NULL) == FAIL
|| dict_add_nr_str(dict, "pattern", 0L,
qfp->qf_pattern == NULL ? (char_u *)"" : qfp->qf_pattern) == FAIL
|| dict_add_nr_str(dict, "text", 0L,
qfp->qf_text == NULL ? (char_u *)"" : qfp->qf_text) == FAIL
|| dict_add_nr_str(dict, "type", 0L, buf) == FAIL
|| dict_add_nr_str(dict, "valid", (long)qfp->qf_valid, NULL) == FAIL)
return FAIL;
qfp = qfp->qf_next;
}
return OK;
}
/*
* Populate the quickfix list with the items supplied in the list
* of dictionaries. "title" will be copied to w:quickfix_title
*/
int set_errorlist(win_T *wp, list_T *list, int action, char_u *title)
{
listitem_T *li;
dict_T *d;
qfline_T *prevp = NULL;
int retval = OK;
qf_info_T *qi = &ql_info;
bool did_bufnr_emsg = false;
if (wp != NULL) {
qi = ll_get_or_alloc_list(wp);
}
if (action == ' ' || qi->qf_curlist == qi->qf_listcount)
/* make place for a new list */
qf_new_list(qi, title);
else if (action == 'a' && qi->qf_lists[qi->qf_curlist].qf_count > 0)
/* Adding to existing list, find last entry. */
for (prevp = qi->qf_lists[qi->qf_curlist].qf_start;
prevp->qf_next != prevp; prevp = prevp->qf_next)
;
else if (action == 'r') {
qf_free(qi, qi->qf_curlist);
qf_store_title(qi, title);
}
for (li = list->lv_first; li != NULL; li = li->li_next) {
if (li->li_tv.v_type != VAR_DICT)
continue; /* Skip non-dict items */
d = li->li_tv.vval.v_dict;
if (d == NULL)
continue;
char_u *filename = get_dict_string(d, (char_u *)"filename", true);
int bufnum = (int)get_dict_number(d, (char_u *)"bufnr");
long lnum = get_dict_number(d, (char_u *)"lnum");
int col = (int)get_dict_number(d, (char_u *)"col");
char_u vcol = (char_u)get_dict_number(d, (char_u *)"vcol");
int nr = (int)get_dict_number(d, (char_u *)"nr");
char_u *type = get_dict_string(d, (char_u *)"type", true);
char_u *pattern = get_dict_string(d, (char_u *)"pattern", true);
char_u *text = get_dict_string(d, (char_u *)"text", true);
if (text == NULL) {
text = vim_strsave((char_u *)"");
}
bool valid = true;
if ((filename == NULL && bufnum == 0) || (lnum == 0 && pattern == NULL)) {
valid = false;
}
/* Mark entries with non-existing buffer number as not valid. Give the
* error message only once. */
if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) {
if (!did_bufnr_emsg) {
did_bufnr_emsg = TRUE;
EMSGN(_("E92: Buffer %" PRId64 " not found"), bufnum);
}
valid = false;
bufnum = 0;
}
int status = qf_add_entry(qi,
&prevp,
NULL, // dir
filename,
bufnum,
text,
lnum,
col,
vcol, // vis_col
pattern, // search pattern
nr,
(char_u)(type == NULL ? NUL : *type),
valid);
xfree(filename);
xfree(pattern);
xfree(text);
xfree(type);
if (status == FAIL) {
retval = FAIL;
break;
}
}
if (qi->qf_lists[qi->qf_curlist].qf_index == 0)
/* no valid entry */
qi->qf_lists[qi->qf_curlist].qf_nonevalid = TRUE;
else
qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE;
qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start;
qi->qf_lists[qi->qf_curlist].qf_index = 1;
qf_update_buffer(qi);
return retval;
}
/*
* ":[range]cbuffer [bufnr]" command.
* ":[range]caddbuffer [bufnr]" command.
* ":[range]cgetbuffer [bufnr]" command.
* ":[range]lbuffer [bufnr]" command.
* ":[range]laddbuffer [bufnr]" command.
* ":[range]lgetbuffer [bufnr]" command.
*/
void ex_cbuffer(exarg_T *eap)
{
buf_T *buf = NULL;
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_lbuffer || eap->cmdidx == CMD_lgetbuffer
|| eap->cmdidx == CMD_laddbuffer) {
qi = ll_get_or_alloc_list(curwin);
}
if (*eap->arg == NUL)
buf = curbuf;
else if (*skipwhite(skipdigits(eap->arg)) == NUL)
buf = buflist_findnr(atoi((char *)eap->arg));
if (buf == NULL)
EMSG(_(e_invarg));
else if (buf->b_ml.ml_mfp == NULL)
EMSG(_("E681: Buffer is not loaded"));
else {
if (eap->addr_count == 0) {
eap->line1 = 1;
eap->line2 = buf->b_ml.ml_line_count;
}
if (eap->line1 < 1 || eap->line1 > buf->b_ml.ml_line_count
|| eap->line2 < 1 || eap->line2 > buf->b_ml.ml_line_count)
EMSG(_(e_invrange));
else {
char_u *qf_title = *eap->cmdlinep;
if (buf->b_sfname) {
vim_snprintf((char *)IObuff, IOSIZE, "%s (%s)",
(char *)qf_title, (char *)buf->b_sfname);
qf_title = IObuff;
}
if (qf_init_ext(qi, NULL, buf, NULL, p_efm,
(eap->cmdidx != CMD_caddbuffer
&& eap->cmdidx != CMD_laddbuffer),
eap->line1, eap->line2,
qf_title) > 0
&& (eap->cmdidx == CMD_cbuffer
|| eap->cmdidx == CMD_lbuffer))
qf_jump(qi, 0, 0, eap->forceit); /* display first error */
}
}
}
/*
* ":cexpr {expr}", ":cgetexpr {expr}", ":caddexpr {expr}" command.
* ":lexpr {expr}", ":lgetexpr {expr}", ":laddexpr {expr}" command.
*/
void ex_cexpr(exarg_T *eap)
{
typval_T *tv;
qf_info_T *qi = &ql_info;
if (eap->cmdidx == CMD_lexpr || eap->cmdidx == CMD_lgetexpr
|| eap->cmdidx == CMD_laddexpr) {
qi = ll_get_or_alloc_list(curwin);
}
/* Evaluate the expression. When the result is a string or a list we can
* use it to fill the errorlist. */
tv = eval_expr(eap->arg, NULL);
if (tv != NULL) {
if ((tv->v_type == VAR_STRING && tv->vval.v_string != NULL)
|| (tv->v_type == VAR_LIST && tv->vval.v_list != NULL)) {
if (qf_init_ext(qi, NULL, NULL, tv, p_efm,
(eap->cmdidx != CMD_caddexpr
&& eap->cmdidx != CMD_laddexpr),
(linenr_T)0, (linenr_T)0, *eap->cmdlinep) > 0
&& (eap->cmdidx == CMD_cexpr
|| eap->cmdidx == CMD_lexpr))
qf_jump(qi, 0, 0, eap->forceit); /* display first error */
} else
EMSG(_("E777: String or List expected"));
free_tv(tv);
}
}
/*
* ":helpgrep {pattern}"
*/
void ex_helpgrep(exarg_T *eap)
{
regmatch_T regmatch;
char_u *save_cpo;
char_u *p;
int fcount;
char_u **fnames;
FILE *fd;
int fi;
qfline_T *prevp = NULL;
long lnum;
char_u *lang;
qf_info_T *qi = &ql_info;
int new_qi = FALSE;
char_u *au_name = NULL;
/* Check for a specified language */
lang = check_help_lang(eap->arg);
switch (eap->cmdidx) {
case CMD_helpgrep: au_name = (char_u *)"helpgrep"; break;
case CMD_lhelpgrep: au_name = (char_u *)"lhelpgrep"; break;
default: break;
}
if (au_name != NULL) {
apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
curbuf->b_fname, TRUE, curbuf);
if (did_throw || force_abort)
return;
}
/* Make 'cpoptions' empty, the 'l' flag should not be used here. */
save_cpo = p_cpo;
p_cpo = empty_option;
if (eap->cmdidx == CMD_lhelpgrep) {
qi = NULL;
/* Find an existing help window */
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_buffer != NULL && wp->w_buffer->b_help) {
qi = wp->w_llist;
}
}
/* Help window not found */
if (qi == NULL) {
/* Allocate a new location list for help text matches */
qi = ll_new_list();
new_qi = TRUE;
}
}
regmatch.regprog = vim_regcomp(eap->arg, RE_MAGIC + RE_STRING);
regmatch.rm_ic = FALSE;
if (regmatch.regprog != NULL) {
vimconv_T vc;
/* Help files are in utf-8 or latin1, convert lines when 'encoding'
* differs. */
vc.vc_type = CONV_NONE;
if (!enc_utf8)
convert_setup(&vc, (char_u *)"utf-8", p_enc);
/* create a new quickfix list */
qf_new_list(qi, *eap->cmdlinep);
/* Go through all directories in 'runtimepath' */
p = p_rtp;
while (*p != NUL && !got_int) {
copy_option_part(&p, NameBuff, MAXPATHL, ",");
/* Find all "*.txt" and "*.??x" files in the "doc" directory. */
add_pathsep((char *)NameBuff);
STRCAT(NameBuff, "doc/*.\\(txt\\|??x\\)");
// Note: We cannot just do `&NameBuff` because it is a statically sized array
// so `NameBuff == &NameBuff` according to C semantics.
char_u *buff_list[1] = {NameBuff};
if (gen_expand_wildcards(1, buff_list, &fcount,
&fnames, EW_FILE|EW_SILENT) == OK
&& fcount > 0) {
for (fi = 0; fi < fcount && !got_int; ++fi) {
/* Skip files for a different language. */
if (lang != NULL
&& STRNICMP(lang, fnames[fi]
+ STRLEN(fnames[fi]) - 3, 2) != 0
&& !(STRNICMP(lang, "en", 2) == 0
&& STRNICMP("txt", fnames[fi]
+ STRLEN(fnames[fi]) - 3, 3) == 0))
continue;
fd = mch_fopen((char *)fnames[fi], "r");
if (fd != NULL) {
lnum = 1;
while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int) {
char_u *line = IObuff;
/* Convert a line if 'encoding' is not utf-8 and
* the line contains a non-ASCII character. */
if (vc.vc_type != CONV_NONE
&& has_non_ascii(IObuff)) {
line = string_convert(&vc, IObuff, NULL);
if (line == NULL)
line = IObuff;
}
if (vim_regexec(®match, line, (colnr_T)0)) {
int l = (int)STRLEN(line);
/* remove trailing CR, LF, spaces, etc. */
while (l > 0 && line[l - 1] <= ' ')
line[--l] = NUL;
if (qf_add_entry(qi, &prevp,
NULL, /* dir */
fnames[fi],
0,
line,
lnum,
(int)(regmatch.startp[0] - line)
+ 1, /* col */
FALSE, /* vis_col */
NULL, /* search pattern */
0, /* nr */
1, /* type */
TRUE /* valid */
) == FAIL) {
got_int = TRUE;
if (line != IObuff)
xfree(line);
break;
}
}
if (line != IObuff)
xfree(line);
++lnum;
line_breakcheck();
}
fclose(fd);
}
}
FreeWild(fcount, fnames);
}
}
vim_regfree(regmatch.regprog);
if (vc.vc_type != CONV_NONE)
convert_setup(&vc, NULL, NULL);
qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE;
qi->qf_lists[qi->qf_curlist].qf_ptr =
qi->qf_lists[qi->qf_curlist].qf_start;
qi->qf_lists[qi->qf_curlist].qf_index = 1;
}
if (p_cpo == empty_option)
p_cpo = save_cpo;
else
/* Darn, some plugin changed the value. */
free_string_option(save_cpo);
qf_update_buffer(qi);
if (au_name != NULL) {
apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name,
curbuf->b_fname, TRUE, curbuf);
if (!new_qi && qi != &ql_info && qf_find_buf(qi) == NULL)
/* autocommands made "qi" invalid */
return;
}
/* Jump to first match. */
if (qi->qf_lists[qi->qf_curlist].qf_count > 0)
qf_jump(qi, 0, 0, FALSE);
else
EMSG2(_(e_nomatch2), eap->arg);
if (eap->cmdidx == CMD_lhelpgrep) {
/* If the help window is not opened or if it already points to the
* correct location list, then free the new location list. */
if (!curwin->w_buffer->b_help || curwin->w_llist == qi) {
if (new_qi)
ll_free_all(&qi);
} else if (curwin->w_llist == NULL)
curwin->w_llist = qi;
}
}
|
117802.c | /*
* net/sched/cls_basic.c Basic Packet Classifier.
*
* 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.
*
* Authors: Thomas Graf <[email protected]>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <net/netlink.h>
#include <net/act_api.h>
#include <net/pkt_cls.h>
struct basic_head {
u32 hgenerator;
struct list_head flist;
struct rcu_head rcu;
};
struct basic_filter {
u32 handle;
struct tcf_exts exts;
struct tcf_ematch_tree ematches;
struct tcf_result res;
struct tcf_proto *tp;
struct list_head link;
struct rcu_head rcu;
};
static int basic_classify(struct sk_buff *skb, const struct tcf_proto *tp,
struct tcf_result *res)
{
int r;
struct basic_head *head = rcu_dereference_bh(tp->root);
struct basic_filter *f;
list_for_each_entry_rcu(f, &head->flist, link) {
if (!tcf_em_tree_match(skb, &f->ematches, NULL))
continue;
*res = f->res;
r = tcf_exts_exec(skb, &f->exts, res);
if (r < 0)
continue;
return r;
}
return -1;
}
static unsigned long basic_get(struct tcf_proto *tp, u32 handle)
{
unsigned long l = 0UL;
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f;
if (head == NULL)
return 0UL;
list_for_each_entry(f, &head->flist, link) {
if (f->handle == handle) {
l = (unsigned long) f;
break;
}
}
return l;
}
static int basic_init(struct tcf_proto *tp)
{
struct basic_head *head;
head = kzalloc(sizeof(*head), GFP_KERNEL);
if (head == NULL)
return -ENOBUFS;
INIT_LIST_HEAD(&head->flist);
rcu_assign_pointer(tp->root, head);
return 0;
}
static void basic_delete_filter(struct rcu_head *head)
{
struct basic_filter *f = container_of(head, struct basic_filter, rcu);
tcf_exts_destroy(&f->exts);
tcf_em_tree_destroy(&f->ematches);
kfree(f);
}
static void basic_destroy(struct tcf_proto *tp)
{
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f, *n;
list_for_each_entry_safe(f, n, &head->flist, link) {
list_del_rcu(&f->link);
tcf_unbind_filter(tp, &f->res);
call_rcu(&f->rcu, basic_delete_filter);
}
RCU_INIT_POINTER(tp->root, NULL);
kfree_rcu(head, rcu);
}
static int basic_delete(struct tcf_proto *tp, unsigned long arg)
{
struct basic_filter *f = (struct basic_filter *) arg;
list_del_rcu(&f->link);
tcf_unbind_filter(tp, &f->res);
call_rcu(&f->rcu, basic_delete_filter);
return 0;
}
static const struct nla_policy basic_policy[TCA_BASIC_MAX + 1] = {
[TCA_BASIC_CLASSID] = { .type = NLA_U32 },
[TCA_BASIC_EMATCHES] = { .type = NLA_NESTED },
};
static int basic_set_parms(struct net *net, struct tcf_proto *tp,
struct basic_filter *f, unsigned long base,
struct nlattr **tb,
struct nlattr *est, bool ovr)
{
int err;
struct tcf_exts e;
struct tcf_ematch_tree t;
tcf_exts_init(&e, TCA_BASIC_ACT, TCA_BASIC_POLICE);
err = tcf_exts_validate(net, tp, tb, est, &e, ovr);
if (err < 0)
return err;
err = tcf_em_tree_validate(tp, tb[TCA_BASIC_EMATCHES], &t);
if (err < 0)
goto errout;
if (tb[TCA_BASIC_CLASSID]) {
f->res.classid = nla_get_u32(tb[TCA_BASIC_CLASSID]);
tcf_bind_filter(tp, &f->res, base);
}
tcf_exts_change(tp, &f->exts, &e);
tcf_em_tree_change(tp, &f->ematches, &t);
f->tp = tp;
return 0;
errout:
tcf_exts_destroy(&e);
return err;
}
static int basic_change(struct net *net, struct sk_buff *in_skb,
struct tcf_proto *tp, unsigned long base, u32 handle,
struct nlattr **tca, unsigned long *arg, bool ovr)
{
int err;
struct basic_head *head = rtnl_dereference(tp->root);
struct nlattr *tb[TCA_BASIC_MAX + 1];
struct basic_filter *fold = (struct basic_filter *) *arg;
struct basic_filter *fnew;
if (tca[TCA_OPTIONS] == NULL)
return -EINVAL;
err = nla_parse_nested(tb, TCA_BASIC_MAX, tca[TCA_OPTIONS],
basic_policy);
if (err < 0)
return err;
if (fold != NULL) {
if (handle && fold->handle != handle)
return -EINVAL;
}
fnew = kzalloc(sizeof(*fnew), GFP_KERNEL);
if (!fnew)
return -ENOBUFS;
tcf_exts_init(&fnew->exts, TCA_BASIC_ACT, TCA_BASIC_POLICE);
err = -EINVAL;
if (handle) {
fnew->handle = handle;
} else if (fold) {
fnew->handle = fold->handle;
} else {
unsigned int i = 0x80000000;
do {
if (++head->hgenerator == 0x7FFFFFFF)
head->hgenerator = 1;
} while (--i > 0 && basic_get(tp, head->hgenerator));
if (i <= 0) {
pr_err("Insufficient number of handles\n");
goto errout;
}
fnew->handle = head->hgenerator;
}
err = basic_set_parms(net, tp, fnew, base, tb, tca[TCA_RATE], ovr);
if (err < 0)
goto errout;
*arg = (unsigned long)fnew;
if (fold) {
list_replace_rcu(&fold->link, &fnew->link);
tcf_unbind_filter(tp, &fold->res);
call_rcu(&fold->rcu, basic_delete_filter);
} else {
list_add_rcu(&fnew->link, &head->flist);
}
return 0;
errout:
kfree(fnew);
return err;
}
static void basic_walk(struct tcf_proto *tp, struct tcf_walker *arg)
{
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f;
list_for_each_entry(f, &head->flist, link) {
if (arg->count < arg->skip)
goto skip;
if (arg->fn(tp, (unsigned long) f, arg) < 0) {
arg->stop = 1;
break;
}
skip:
arg->count++;
}
}
static int basic_dump(struct net *net, struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct basic_filter *f = (struct basic_filter *) fh;
struct nlattr *nest;
if (f == NULL)
return skb->len;
t->tcm_handle = f->handle;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (f->res.classid &&
nla_put_u32(skb, TCA_BASIC_CLASSID, f->res.classid))
goto nla_put_failure;
if (tcf_exts_dump(skb, &f->exts) < 0 ||
tcf_em_tree_dump(skb, &f->ematches, TCA_BASIC_EMATCHES) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest);
if (tcf_exts_dump_stats(skb, &f->exts) < 0)
goto nla_put_failure;
return skb->len;
nla_put_failure:
nla_nest_cancel(skb, nest);
return -1;
}
static struct tcf_proto_ops cls_basic_ops __read_mostly = {
.kind = "basic",
.classify = basic_classify,
.init = basic_init,
.destroy = basic_destroy,
.get = basic_get,
.change = basic_change,
.delete = basic_delete,
.walk = basic_walk,
.dump = basic_dump,
.owner = THIS_MODULE,
};
static int __init init_basic(void)
{
return register_tcf_proto_ops(&cls_basic_ops);
}
static void __exit exit_basic(void)
{
unregister_tcf_proto_ops(&cls_basic_ops);
}
module_init(init_basic)
module_exit(exit_basic)
MODULE_LICENSE("GPL");
|
656185.c | #include "libc.h"
#include "threads_impl.h"
#include "setjmp_impl.h"
#include "zircon_impl.h"
#include <elf.h>
#include <stdatomic.h>
#include <string.h>
#include <lib/processargs/processargs.h>
#include <zircon/sanitizer.h>
#include <zircon/syscalls.h>
#include <runtime/thread.h>
struct start_params {
int (*main)(int, char**, char**);
thrd_t td;
uint8_t* buffer;
zx_proc_args_t* procargs;
zx_handle_t* handles;
uint32_t* handle_info;
uint32_t nbytes, nhandles;
};
// This gets called via inline assembly below, after switching onto
// the newly-allocated (safe) stack.
static _Noreturn void start_main(const struct start_params*)
__asm__("start_main") __attribute__((used));
static void start_main(const struct start_params* p) {
uint32_t argc = p->procargs->args_num;
uint32_t envc = p->procargs->environ_num;
uint32_t namec = p->procargs->names_num;
// Use a single contiguous buffer for argv and envp, with two
// extra words of terminator on the end. In traditional Unix
// process startup, the stack contains argv followed immediately
// by envp and that's followed immediately by the auxiliary vector
// (auxv), which is in two-word pairs and terminated by zero
// words. Some crufty programs might assume some of that layout,
// and it costs us nothing to stay consistent with it here.
char* args_and_environ[argc + 1 + envc + 1 + 2];
char** argv = &args_and_environ[0];
__environ = &args_and_environ[argc + 1];
char** dummy_auxv = &args_and_environ[argc + 1 + envc + 1];
dummy_auxv[0] = dummy_auxv[1] = 0;
char* names[namec + 1];
zx_status_t status = processargs_strings(p->buffer, p->nbytes,
argv, __environ, names);
if (status != ZX_OK) {
argc = namec = 0;
argv = __environ = NULL;
}
for (uint32_t n = 0; n < p->nhandles; n++) {
unsigned arg = PA_HND_ARG(p->handle_info[n]);
zx_handle_t h = p->handles[n];
switch (PA_HND_TYPE(p->handle_info[n])) {
case PA_NS_DIR:
if (strcmp(names[arg], "/svc") == 0) {
// TODO(phosek): We should ideally duplicate the handle since
// higher layers might consume it and we want to have a guarantee
// that it stays alive, but that's typically possible since
// channel handles don't have ZX_RIGHT_DUPLICATE right.
//
// TODO(phosek): What if the program uses bind to replace its
// /svc, should the subsequent invocations to __sanitizer_*
// use the startup value or reflect the live changes?
__zircon_namespace_svc = h;
}
continue;
}
}
__sanitizer_startup_hook(argc, argv, __environ,
p->td->safe_stack.iov_base,
p->td->safe_stack.iov_len);
// Allow companion libraries a chance to claim handles, zeroing out
// handles[i] and handle_info[i] for handles they claim.
if (&__libc_extensions_init != NULL) {
__libc_extensions_init(p->nhandles, p->handles, p->handle_info,
namec, names);
}
// Give any unclaimed handles to zx_take_startup_handle(). This function
// takes ownership of the data, but not the memory: it assumes that the
// arrays are valid as long as the process is alive.
__libc_startup_handles_init(p->nhandles, p->handles, p->handle_info);
// Run static constructors et al.
__libc_start_init();
// Pass control to the application.
exit((*p->main)(argc, argv, __environ));
}
__NO_SAFESTACK _Noreturn void __libc_start_main(
zx_handle_t bootstrap, int (*main)(int, char**, char**)) {
// Initialize stack-protector canary value first thing. Do the setjmp
// manglers in the same call to avoid the overhead of two system calls.
// That means we need a temporary buffer on the stack, which we then
// want to clear out so the values don't leak there.
struct randoms {
uintptr_t stack_guard;
struct setjmp_manglers setjmp_manglers;
} randoms;
static_assert(sizeof(randoms) <= ZX_CPRNG_DRAW_MAX_LEN, "");
_zx_cprng_draw(&randoms, sizeof(randoms));
__stack_chk_guard = randoms.stack_guard;
__setjmp_manglers = randoms.setjmp_manglers;
// Zero the stack temporaries.
randoms = (struct randoms) {};
// Tell the compiler that the value is used, so it doesn't optimize
// out the zeroing as dead stores.
__asm__("# keepalive %0" :: "m"(randoms));
// extract process startup information from channel in arg
struct start_params p = { .main = main };
zx_status_t status = processargs_message_size(bootstrap, &p.nbytes, &p.nhandles);
if (status != ZX_OK) {
p.nbytes = p.nhandles = 0;
}
PROCESSARGS_BUFFER(buffer, p.nbytes);
zx_handle_t handles[p.nhandles];
p.buffer = buffer;
p.handles = handles;
if (status == ZX_OK) {
status = processargs_read(bootstrap, buffer, p.nbytes,
handles, p.nhandles,
&p.procargs, &p.handle_info);
}
// Find the handles we're interested in among what we were given.
zx_handle_t main_thread_handle = ZX_HANDLE_INVALID;
for (uint32_t i = 0; i < p.nhandles; ++i) {
switch (PA_HND_TYPE(p.handle_info[i])) {
case PA_PROC_SELF:
// The handle will have been installed already by dynamic
// linker startup, but now we have another one. They
// should of course be handles to the same process, but
// just for cleanliness switch to the "main" one.
if (__zircon_process_self != ZX_HANDLE_INVALID)
_zx_handle_close(__zircon_process_self);
__zircon_process_self = handles[i];
handles[i] = ZX_HANDLE_INVALID;
p.handle_info[i] = 0;
break;
case PA_JOB_DEFAULT:
// The default job provided to the process to use for
// creation of additional processes. It may or may not
// be the job this process is a child of. It may not
// be provided at all.
if (__zircon_job_default != ZX_HANDLE_INVALID)
_zx_handle_close(__zircon_job_default);
__zircon_job_default = handles[i];
handles[i] = ZX_HANDLE_INVALID;
p.handle_info[i] = 0;
break;
case PA_VMAR_ROOT:
// As above for PROC_SELF
if (__zircon_vmar_root_self != ZX_HANDLE_INVALID)
_zx_handle_close(__zircon_vmar_root_self);
__zircon_vmar_root_self = handles[i];
handles[i] = ZX_HANDLE_INVALID;
p.handle_info[i] = 0;
break;
case PA_THREAD_SELF:
main_thread_handle = handles[i];
handles[i] = ZX_HANDLE_INVALID;
p.handle_info[i] = 0;
break;
}
}
atomic_store(&libc.thread_count, 1);
// This consumes the thread handle and sets up the thread pointer.
p.td = __init_main_thread(main_thread_handle);
// Switch to the allocated stack and call start_main(&p) there. The
// original stack stays around just to hold the message buffer and handles
// array. The new stack is whole pages, so it's sufficiently aligned.
#ifdef __x86_64__
// The x86-64 ABI requires %rsp % 16 = 8 on entry. The zero word
// at (%rsp) serves as the return address for the outermost frame.
__asm__("lea -8(%[base], %[len], 1), %%rsp\n"
"jmp start_main\n"
"# Target receives %[arg]" : :
[base]"r"(p.td->safe_stack.iov_base),
[len]"r"(p.td->safe_stack.iov_len),
"m"(p), // Tell the compiler p's fields are all still alive.
[arg]"D"(&p));
#elif defined(__aarch64__)
__asm__("add sp, %[base], %[len]\n"
"mov x0, %[arg]\n"
"b start_main" : :
[base]"r"(p.td->safe_stack.iov_base),
[len]"r"(p.td->safe_stack.iov_len),
"m"(p), // Tell the compiler p's fields are all still alive.
[arg]"r"(&p));
#else
#error what architecture?
#endif
__builtin_unreachable();
}
|
962161.c | /*
Copyright (C) 2014, The University of Texas at Austin
This file is part of libflame and is available under the 3-Clause
BSD license, which can be found in the LICENSE file at the top-level
directory, or at http://opensource.org/licenses/BSD-3-Clause
*/
#include "FLAME.h"
FLA_Error FLA_Trsm_lln_blk_var3( FLA_Diag diagA, FLA_Obj alpha, FLA_Obj A, FLA_Obj B, fla_trsm_t* cntl )
{
FLA_Obj BL, BR, B0, B1, B2;
dim_t b;
FLA_Part_1x2( B, &BL, &BR, 0, FLA_LEFT );
while ( FLA_Obj_width( BL ) < FLA_Obj_width( B ) ){
b = FLA_Determine_blocksize( BR, FLA_RIGHT, FLA_Cntl_blocksize( cntl ) );
FLA_Repart_1x2_to_1x3( BL, /**/ BR, &B0, /**/ &B1, &B2,
b, FLA_RIGHT );
/*------------------------------------------------------------*/
/* B1 = tril( A ) \ B1 */
FLA_Trsm_internal( FLA_LEFT, FLA_LOWER_TRIANGULAR, FLA_NO_TRANSPOSE, diagA,
alpha, A, B1,
FLA_Cntl_sub_trsm( cntl ) );
/*------------------------------------------------------------*/
FLA_Cont_with_1x3_to_1x2( &BL, /**/ &BR, B0, B1, /**/ B2,
FLA_LEFT );
}
return FLA_SUCCESS;
}
|
945627.c | /*
* Populate sysfs with topology information
*
* Written by: Matthew Dobson, IBM Corporation
* Original Code: Paul Dorwin, IBM Corporation, Patrick Mochel, OSDL
*
* Copyright (C) 2002, IBM Corp.
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <[email protected]>
*/
#include <linux/nodemask.h>
#include <linux/mmzone.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <asm/cpu.h>
static DEFINE_PER_CPU(struct x86_cpu, cpu_devices);
#ifdef CONFIG_HOTPLUG_CPU
int __ref arch_register_cpu(int num)
{
/*
* CPU0 cannot be offlined due to several
* restrictions and assumptions in kernel. This basically
* doesnt add a control file, one cannot attempt to offline
* BSP.
*
* Also certain PCI quirks require not to enable hotplug control
* for all CPU's.
*/
if (num)
per_cpu(cpu_devices, num).cpu.hotpluggable = 1;
return register_cpu(&per_cpu(cpu_devices, num).cpu, num);
}
EXPORT_SYMBOL(arch_register_cpu);
void arch_unregister_cpu(int num)
{
unregister_cpu(&per_cpu(cpu_devices, num).cpu);
}
EXPORT_SYMBOL(arch_unregister_cpu);
#else /* CONFIG_HOTPLUG_CPU */
static int __init arch_register_cpu(int num)
{
return register_cpu(&per_cpu(cpu_devices, num).cpu, num);
}
#endif /* CONFIG_HOTPLUG_CPU */
static int __init topology_init(void)
{
int i;
#ifdef CONFIG_NUMA
for_each_online_node(i)
register_one_node(i);
#endif
for_each_present_cpu(i)
arch_register_cpu(i);
return 0;
}
subsys_initcall(topology_init);
|
799078.c | /*
******************************************************************************
* @file multi_read_fifo.c
* @author Sensors Software Solution Team
* @brief LIS3DE driver file
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "lis3de_reg.h"
#include <string.h>
#include <stdio.h>
//#define MKI109V2
#define NUCLEO_STM32F411RE
#ifdef MKI109V2
#include "stm32f1xx_hal.h"
#include "usbd_cdc_if.h"
#include "spi.h"
#include "i2c.h"
#endif
#ifdef NUCLEO_STM32F411RE
#include "stm32f4xx_hal.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"
#endif
typedef union{
int16_t i16bit[3];
uint8_t u8bit[6];
} axis3bit16_t;
/* Private macro -------------------------------------------------------------*/
#ifdef MKI109V2
#define CS_SPI2_GPIO_Port CS_DEV_GPIO_Port
#define CS_SPI2_Pin CS_DEV_Pin
#define CS_SPI1_GPIO_Port CS_RF_GPIO_Port
#define CS_SPI1_Pin CS_RF_Pin
#endif
#if defined(NUCLEO_STM32F411RE)
/* N/A on NUCLEO_STM32F411RE + IKS01A1 */
/* N/A on NUCLEO_STM32F411RE + IKS01A2 */
#define CS_SPI2_GPIO_Port 0
#define CS_SPI2_Pin 0
#define CS_SPI1_GPIO_Port 0
#define CS_SPI1_Pin 0
#endif /* NUCLEO_XXX */
#define TX_BUF_DIM 1000
/* Define number of byte for each sensor sample */
#define OUT_XYZ_SIZE 6
/* Define FIFO watermark to 10 samples */
#define FIFO_WATERMARK 10
/* Private variables ---------------------------------------------------------*/
static uint8_t tx_buffer[TX_BUF_DIM];
static float acceleration_mg[3];
static axis3bit16_t data_raw_acceleration;
static stmdev_ctx_t dev_ctx;
/* Extern variables ----------------------------------------------------------*/
/* Platform Functions --------------------------------------------------------*/
/*
* Replace the functions "platform_write" and "platform_read" with your
* platform specific read and write function.
* This example use an STM32 evaluation board and CubeMX tool.
* In this case the "*handle" variable is useful in order to select the
* correct interface but the usage of "*handle" is not mandatory.
*/
static int32_t platform_write(void *handle, uint8_t Reg, uint8_t *Bufp,
uint16_t len)
{
if (handle == &hi2c1)
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0x80;
HAL_I2C_Mem_Write(handle, LIS3DE_I2C_ADD_H, Reg,
I2C_MEMADD_SIZE_8BIT, Bufp, len, 1000);
}
#ifdef MKI109V2
else if (handle == &hspi2)
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0x40;
HAL_GPIO_WritePin(CS_SPI2_GPIO_Port, CS_SPI2_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, &Reg, 1, 1000);
HAL_SPI_Transmit(handle, Bufp, len, 1000);
HAL_GPIO_WritePin(CS_SPI2_GPIO_Port, CS_SPI2_Pin, GPIO_PIN_SET);
}
else if (handle == &hspi1)
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0x40;
HAL_GPIO_WritePin(CS_SPI1_GPIO_Port, CS_SPI1_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, &Reg, 1, 1000);
HAL_SPI_Transmit(handle, Bufp, len, 1000);
HAL_GPIO_WritePin(CS_SPI1_GPIO_Port, CS_SPI1_Pin, GPIO_PIN_SET);
}
#endif
return 0;
}
static int32_t platform_read(void *handle, uint8_t Reg, uint8_t *Bufp,
uint16_t len)
{
if (handle == &hi2c1)
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0x80;
HAL_I2C_Mem_Read(handle, LIS3DE_I2C_ADD_H, Reg,
I2C_MEMADD_SIZE_8BIT, Bufp, len, 1000);
}
#ifdef MKI109V2
else if (handle == &hspi2)
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0xC0;
HAL_GPIO_WritePin(CS_DEV_GPIO_Port, CS_DEV_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, &Reg, 1, 1000);
HAL_SPI_Receive(handle, Bufp, len, 1000);
HAL_GPIO_WritePin(CS_DEV_GPIO_Port, CS_DEV_Pin, GPIO_PIN_SET);
}
else
{
/* enable auto incremented in multiple read/write commands */
Reg |= 0xC0;
HAL_GPIO_WritePin(CS_RF_GPIO_Port, CS_RF_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(handle, &Reg, 1, 1000);
HAL_SPI_Receive(handle, Bufp, len, 1000);
HAL_GPIO_WritePin(CS_RF_GPIO_Port, CS_RF_Pin, GPIO_PIN_SET);
}
#endif
return 0;
}
/*
* Function to print messages
*/
static void tx_com( uint8_t *tx_buffer, uint16_t len )
{
#ifdef NUCLEO_STM32F411RE
HAL_UART_Transmit( &huart2, tx_buffer, len, 1000 );
#endif /* NUCLEO_STM32F411RE */
#ifdef MKI109V2
CDC_Transmit_FS( tx_buffer, len );
#endif /* MKI109V2 */
}
/*
* example_main - Main Example FIFO support
*
* FIFO read acc sample
*/
void example_lis3de_fifo(void)
{
uint8_t whoamI;
dev_ctx.write_reg = platform_write;
dev_ctx.read_reg = platform_read;
dev_ctx.handle = &hi2c1;
whoamI = 0;
lis3de_device_id_get(&dev_ctx, &whoamI);
if ( whoamI != LIS3DE_ID )
while(1); /*manage here device not found */
/* Enable Block Data Update. */
lis3de_block_data_update_set(&dev_ctx, PROPERTY_ENABLE);
/* Set Output Data Rate to 100 hz. */
lis3de_data_rate_set(&dev_ctx, LIS3DE_ODR_100Hz);
/* Set full scale to 2 g. */
lis3de_full_scale_set(&dev_ctx, LIS3DE_2g);
/*
* Set operating mode to high resolution.
*/
lis3de_operating_mode_set(&dev_ctx, LIS3DE_LP);
/* Set FIFO watermark to FIFO_WATERMARK samples. */
lis3de_fifo_watermark_set(&dev_ctx, FIFO_WATERMARK);
/*
* Set FIFO mode to Stream mode: Accumulate samples and
* override old data.
*/
lis3de_fifo_mode_set(&dev_ctx, LIS3DE_DYNAMIC_STREAM_MODE);
/* Enable FIFO. */
lis3de_fifo_set(&dev_ctx, PROPERTY_ENABLE);
while(1)
{
uint8_t flags;
uint8_t num = 0;
/* Check if FIFO level over threshold. */
lis3de_fifo_fth_flag_get(&dev_ctx, &flags);
if (flags)
{
/* Read number of sample in FIFO. */
lis3de_fifo_data_level_get(&dev_ctx, &num);
while (num-- > 0)
{
/* Read XL samples. */
lis3de_acceleration_raw_get(&dev_ctx, data_raw_acceleration.i16bit);
acceleration_mg[0] = lis3de_from_fs2_to_mg(data_raw_acceleration.i16bit[0]);
acceleration_mg[1] = lis3de_from_fs2_to_mg(data_raw_acceleration.i16bit[1]);
acceleration_mg[2] = lis3de_from_fs2_to_mg(data_raw_acceleration.i16bit[2]);
sprintf((char*)tx_buffer, "Acceleration [mg]:%4.2f\t%4.2f\t%4.2f\r\n",
acceleration_mg[0], acceleration_mg[1], acceleration_mg[2]);
tx_com( tx_buffer, strlen( (char const*)tx_buffer ) );
}
}
else
{
/* Force compiler to generate code, avoiding I2C polling stress. */
for (volatile uint32_t i = 0; i < 10000; i++);
}
}
}
|
158506.c | /*
* FreeRTOS Kernel <DEVELOPMENT BRANCH>
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/* GCC/HCS12 port by Jefferson L Smith, 2005 */
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Port includes */
#include <sys/ports_def.h>
/*-----------------------------------------------------------
* Implementation of functions defined in portable.h for the HCS12 port.
*----------------------------------------------------------*/
/*
* Configure a timer to generate the RTOS tick at the frequency specified
* within FreeRTOSConfig.h.
*/
static void prvSetupTimerInterrupt( void );
/* NOTE: Interrupt service routines must be in non-banked memory - as does the
scheduler startup function. */
#define ATTR_NEAR __attribute__((near))
/* Manual context switch function. This is the SWI ISR. */
// __attribute__((interrupt))
void ATTR_NEAR vPortYield( void );
/* Tick context switch function. This is the timer ISR. */
// __attribute__((interrupt))
void ATTR_NEAR vPortTickInterrupt( void );
/* Function in non-banked memory which actually switches to first task. */
BaseType_t ATTR_NEAR xStartSchedulerNear( void );
/* Calls to portENTER_CRITICAL() can be nested. When they are nested the
critical section should not be left (i.e. interrupts should not be re-enabled)
until the nesting depth reaches 0. This variable simply tracks the nesting
depth. Each task maintains it's own critical nesting depth variable so
uxCriticalNesting is saved and restored from the task stack during a context
switch. */
volatile UBaseType_t uxCriticalNesting = 0x80; // un-initialized
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
{
/* Setup the initial stack of the task. The stack is set exactly as
expected by the portRESTORE_CONTEXT() macro. In this case the stack as
expected by the HCS12 RTI instruction. */
/* The address of the task function is placed in the stack byte at a time. */
*pxTopOfStack = ( StackType_t ) *( ((StackType_t *) (&pxCode) ) + 1 );
*--pxTopOfStack = ( StackType_t ) *( ((StackType_t *) (&pxCode) ) + 0 );
/* Next are all the registers that form part of the task context. */
/* Y register */
*--pxTopOfStack = ( StackType_t ) 0xff;
*--pxTopOfStack = ( StackType_t ) 0xee;
/* X register */
*--pxTopOfStack = ( StackType_t ) 0xdd;
*--pxTopOfStack = ( StackType_t ) 0xcc;
/* A register contains parameter high byte. */
*--pxTopOfStack = ( StackType_t ) *( ((StackType_t *) (&pvParameters) ) + 0 );
/* B register contains parameter low byte. */
*--pxTopOfStack = ( StackType_t ) *( ((StackType_t *) (&pvParameters) ) + 1 );
/* CCR: Note that when the task starts interrupts will be enabled since
"I" bit of CCR is cleared */
*--pxTopOfStack = ( StackType_t ) 0x80; // keeps Stop disabled (MCU default)
/* tmp softregs used by GCC. Values right now don't matter. */
__asm("\n\
movw _.frame, 2,-%0 \n\
movw _.tmp, 2,-%0 \n\
movw _.z, 2,-%0 \n\
movw _.xy, 2,-%0 \n\
;movw _.d2, 2,-%0 \n\
;movw _.d1, 2,-%0 \n\
": "=A"(pxTopOfStack) : "0"(pxTopOfStack) );
#ifdef BANKED_MODEL
/* The page of the task. */
*--pxTopOfStack = 0x30; // can only directly start in PPAGE 0x30
#endif
/* The critical nesting depth is initialised with 0 (meaning not in
a critical section). */
*--pxTopOfStack = ( StackType_t ) 0x00;
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler( void )
{
/* It is unlikely that the HCS12 port will get stopped. */
}
/*-----------------------------------------------------------*/
static void prvSetupTimerInterrupt( void )
{
/* Enable hardware RTI timer */
/* Ignores configTICK_RATE_HZ */
RTICTL = 0x50; // 16 MHz xtal: 976.56 Hz, 1024mS
CRGINT |= 0x80; // RTIE
}
/*-----------------------------------------------------------*/
BaseType_t xPortStartScheduler( void )
{
/* xPortStartScheduler() does not start the scheduler directly because
the header file containing the xPortStartScheduler() prototype is part
of the common kernel code, and therefore cannot use the CODE_SEG pragma.
Instead it simply calls the locally defined xNearStartScheduler() -
which does use the CODE_SEG pragma. */
int16_t register d;
__asm ("jmp xStartSchedulerNear ; will never return": "=d"(d));
return d;
}
/*-----------------------------------------------------------*/
BaseType_t xStartSchedulerNear( void )
{
/* Configure the timer that will generate the RTOS tick. Interrupts are
disabled when this function is called. */
prvSetupTimerInterrupt();
/* Restore the context of the first task. */
portRESTORE_CONTEXT();
portISR_TAIL();
/* Should not get here! */
return pdFALSE;
}
/*-----------------------------------------------------------*/
/*
* Context switch functions. These are interrupt service routines.
*/
/*
* Manual context switch forced by calling portYIELD(). This is the SWI
* handler.
*/
void vPortYield( void )
{
portISR_HEAD();
/* NOTE: This is the trap routine (swi) although not defined as a trap.
It will fill the stack the same way as an ISR in order to mix preemtion
and cooperative yield. */
portSAVE_CONTEXT();
vTaskSwitchContext();
portRESTORE_CONTEXT();
portISR_TAIL();
}
/*-----------------------------------------------------------*/
/*
* RTOS tick interrupt service routine. If the cooperative scheduler is
* being used then this simply increments the tick count. If the
* preemptive scheduler is being used a context switch can occur.
*/
void vPortTickInterrupt( void )
{
portISR_HEAD();
/* Clear tick timer flag */
CRGFLG = 0x80;
#if configUSE_PREEMPTION == 1
{
/* A context switch might happen so save the context. */
portSAVE_CONTEXT();
/* Increment the tick ... */
if( xTaskIncrementTick() != pdFALSE )
{
/* A context switch is necessary. */
vTaskSwitchContext();
}
/* Restore the context of a task - which may be a different task
to that interrupted. */
portRESTORE_CONTEXT();
}
#else
{
xTaskIncrementTick();
}
#endif
portISR_TAIL();
}
|
318754.c | // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "sdkconfig.h"
#include "soc/soc.h"
#include "soc/cpu.h"
#include "soc/rtc_cntl_reg.h"
#include "rom/ets_sys.h"
#include "esp_system.h"
#include "driver/rtc_cntl.h"
#include "freertos/FreeRTOS.h"
#ifdef CONFIG_BROWNOUT_DET_LVL
#define BROWNOUT_DET_LVL CONFIG_BROWNOUT_DET_LVL
#else
#define BROWNOUT_DET_LVL 0
#endif //CONFIG_BROWNOUT_DET_LVL
static void rtc_brownout_isr_handler()
{
/* Normally RTC ISR clears the interrupt flag after the application-supplied
* handler returns. Since restart is called here, the flag needs to be
* cleared manually.
*/
REG_WRITE(RTC_CNTL_INT_CLR_REG, RTC_CNTL_BROWN_OUT_INT_CLR);
/* Stall the other CPU to make sure the code running there doesn't use UART
* at the same time as the following ets_printf.
*/
esp_cpu_stall(!xPortGetCoreID());
ets_printf("\r\nBrownout detector was triggered\r\n\r\n");
esp_restart_noos();
}
void esp_brownout_init()
{
REG_WRITE(RTC_CNTL_BROWN_OUT_REG,
RTC_CNTL_BROWN_OUT_ENA /* Enable BOD */
| RTC_CNTL_BROWN_OUT_PD_RF_ENA /* Automatically power down RF */
/* Reset timeout must be set to >1 even if BOR feature is not used */
| (2 << RTC_CNTL_BROWN_OUT_RST_WAIT_S)
| (BROWNOUT_DET_LVL << RTC_CNTL_DBROWN_OUT_THRES_S));
ESP_ERROR_CHECK( rtc_isr_register(rtc_brownout_isr_handler, NULL, RTC_CNTL_BROWN_OUT_INT_ENA_M) );
REG_SET_BIT(RTC_CNTL_INT_ENA_REG, RTC_CNTL_BROWN_OUT_INT_ENA_M);
}
|
982427.c | /*
TASK :
AUTHOR: Hydrolyzed~
GITHUB: MasterIceZ
LANG : C
SCHOOL: RYW
*/
#include<stdio.h>
int main(){
int n;
scanf("%d", &n);
printf("%s",n%2==1?"Odd":"Even");
printf("\n");
return 0;
}
|
390850.c | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
/*
* common eBPF ELF operations.
*
* Copyright (C) 2013-2015 Alexei Starovoitov <[email protected]>
* Copyright (C) 2015 Wang Nan <[email protected]>
* Copyright (C) 2015 Huawei Inc.
*
* 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;
* version 2.1 of the License (not later!)
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses>
*/
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <unistd.h>
#include <asm/unistd.h>
#include <errno.h>
#include <linux/bpf.h>
#include "bpf.h"
#include "libbpf.h"
#include "libbpf_internal.h"
/*
* When building perf, unistd.h is overridden. __NR_bpf is
* required to be defined explicitly.
*/
#ifndef __NR_bpf
# if defined(__i386__)
# define __NR_bpf 357
# elif defined(__x86_64__)
# define __NR_bpf 321
# elif defined(__aarch64__)
# define __NR_bpf 280
# elif defined(__sparc__)
# define __NR_bpf 349
# elif defined(__s390__)
# define __NR_bpf 351
# elif defined(__arc__)
# define __NR_bpf 280
# else
# error __NR_bpf not defined. libbpf does not support your arch.
# endif
#endif
static inline __u64 ptr_to_u64(const void *ptr)
{
return (__u64) (unsigned long) ptr;
}
static inline int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
unsigned int size)
{
return syscall(__NR_bpf, cmd, attr, size);
}
static inline int sys_bpf_prog_load(union bpf_attr *attr, unsigned int size)
{
int retries = 5;
int fd;
do {
fd = sys_bpf(BPF_PROG_LOAD, attr, size);
} while (fd < 0 && errno == EAGAIN && retries-- > 0);
return fd;
}
int bpf_create_map_xattr(const struct bpf_create_map_attr *create_attr)
{
union bpf_attr attr;
memset(&attr, '\0', sizeof(attr));
attr.map_type = create_attr->map_type;
attr.key_size = create_attr->key_size;
attr.value_size = create_attr->value_size;
attr.max_entries = create_attr->max_entries;
attr.map_flags = create_attr->map_flags;
if (create_attr->name)
memcpy(attr.map_name, create_attr->name,
min(strlen(create_attr->name), BPF_OBJ_NAME_LEN - 1));
attr.numa_node = create_attr->numa_node;
attr.btf_fd = create_attr->btf_fd;
attr.btf_key_type_id = create_attr->btf_key_type_id;
attr.btf_value_type_id = create_attr->btf_value_type_id;
attr.map_ifindex = create_attr->map_ifindex;
if (attr.map_type == BPF_MAP_TYPE_STRUCT_OPS)
attr.btf_vmlinux_value_type_id =
create_attr->btf_vmlinux_value_type_id;
else
attr.inner_map_fd = create_attr->inner_map_fd;
return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
}
int bpf_create_map_node(enum bpf_map_type map_type, const char *name,
int key_size, int value_size, int max_entries,
__u32 map_flags, int node)
{
struct bpf_create_map_attr map_attr = {};
map_attr.name = name;
map_attr.map_type = map_type;
map_attr.map_flags = map_flags;
map_attr.key_size = key_size;
map_attr.value_size = value_size;
map_attr.max_entries = max_entries;
if (node >= 0) {
map_attr.numa_node = node;
map_attr.map_flags |= BPF_F_NUMA_NODE;
}
return bpf_create_map_xattr(&map_attr);
}
int bpf_create_map(enum bpf_map_type map_type, int key_size,
int value_size, int max_entries, __u32 map_flags)
{
struct bpf_create_map_attr map_attr = {};
map_attr.map_type = map_type;
map_attr.map_flags = map_flags;
map_attr.key_size = key_size;
map_attr.value_size = value_size;
map_attr.max_entries = max_entries;
return bpf_create_map_xattr(&map_attr);
}
int bpf_create_map_name(enum bpf_map_type map_type, const char *name,
int key_size, int value_size, int max_entries,
__u32 map_flags)
{
struct bpf_create_map_attr map_attr = {};
map_attr.name = name;
map_attr.map_type = map_type;
map_attr.map_flags = map_flags;
map_attr.key_size = key_size;
map_attr.value_size = value_size;
map_attr.max_entries = max_entries;
return bpf_create_map_xattr(&map_attr);
}
int bpf_create_map_in_map_node(enum bpf_map_type map_type, const char *name,
int key_size, int inner_map_fd, int max_entries,
__u32 map_flags, int node)
{
union bpf_attr attr;
memset(&attr, '\0', sizeof(attr));
attr.map_type = map_type;
attr.key_size = key_size;
attr.value_size = 4;
attr.inner_map_fd = inner_map_fd;
attr.max_entries = max_entries;
attr.map_flags = map_flags;
if (name)
memcpy(attr.map_name, name,
min(strlen(name), BPF_OBJ_NAME_LEN - 1));
if (node >= 0) {
attr.map_flags |= BPF_F_NUMA_NODE;
attr.numa_node = node;
}
return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
}
int bpf_create_map_in_map(enum bpf_map_type map_type, const char *name,
int key_size, int inner_map_fd, int max_entries,
__u32 map_flags)
{
return bpf_create_map_in_map_node(map_type, name, key_size,
inner_map_fd, max_entries, map_flags,
-1);
}
static void *
alloc_zero_tailing_info(const void *orecord, __u32 cnt,
__u32 actual_rec_size, __u32 expected_rec_size)
{
__u64 info_len = (__u64)actual_rec_size * cnt;
void *info, *nrecord;
int i;
info = malloc(info_len);
if (!info)
return NULL;
/* zero out bytes kernel does not understand */
nrecord = info;
for (i = 0; i < cnt; i++) {
memcpy(nrecord, orecord, expected_rec_size);
memset(nrecord + expected_rec_size, 0,
actual_rec_size - expected_rec_size);
orecord += actual_rec_size;
nrecord += actual_rec_size;
}
return info;
}
int libbpf__bpf_prog_load(const struct bpf_prog_load_params *load_attr)
{
void *finfo = NULL, *linfo = NULL;
union bpf_attr attr;
int fd;
if (!load_attr->log_buf != !load_attr->log_buf_sz)
return -EINVAL;
if (load_attr->log_level > (4 | 2 | 1) || (load_attr->log_level && !load_attr->log_buf))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.prog_type = load_attr->prog_type;
attr.expected_attach_type = load_attr->expected_attach_type;
if (load_attr->attach_prog_fd)
attr.attach_prog_fd = load_attr->attach_prog_fd;
else
attr.attach_btf_obj_fd = load_attr->attach_btf_obj_fd;
attr.attach_btf_id = load_attr->attach_btf_id;
attr.prog_ifindex = load_attr->prog_ifindex;
attr.kern_version = load_attr->kern_version;
attr.insn_cnt = (__u32)load_attr->insn_cnt;
attr.insns = ptr_to_u64(load_attr->insns);
attr.license = ptr_to_u64(load_attr->license);
attr.log_level = load_attr->log_level;
if (attr.log_level) {
attr.log_buf = ptr_to_u64(load_attr->log_buf);
attr.log_size = load_attr->log_buf_sz;
}
attr.prog_btf_fd = load_attr->prog_btf_fd;
attr.prog_flags = load_attr->prog_flags;
attr.func_info_rec_size = load_attr->func_info_rec_size;
attr.func_info_cnt = load_attr->func_info_cnt;
attr.func_info = ptr_to_u64(load_attr->func_info);
attr.line_info_rec_size = load_attr->line_info_rec_size;
attr.line_info_cnt = load_attr->line_info_cnt;
attr.line_info = ptr_to_u64(load_attr->line_info);
if (load_attr->name)
memcpy(attr.prog_name, load_attr->name,
min(strlen(load_attr->name), (size_t)BPF_OBJ_NAME_LEN - 1));
fd = sys_bpf_prog_load(&attr, sizeof(attr));
if (fd >= 0)
return fd;
/* After bpf_prog_load, the kernel may modify certain attributes
* to give user space a hint how to deal with loading failure.
* Check to see whether we can make some changes and load again.
*/
while (errno == E2BIG && (!finfo || !linfo)) {
if (!finfo && attr.func_info_cnt &&
attr.func_info_rec_size < load_attr->func_info_rec_size) {
/* try with corrected func info records */
finfo = alloc_zero_tailing_info(load_attr->func_info,
load_attr->func_info_cnt,
load_attr->func_info_rec_size,
attr.func_info_rec_size);
if (!finfo)
goto done;
attr.func_info = ptr_to_u64(finfo);
attr.func_info_rec_size = load_attr->func_info_rec_size;
} else if (!linfo && attr.line_info_cnt &&
attr.line_info_rec_size <
load_attr->line_info_rec_size) {
linfo = alloc_zero_tailing_info(load_attr->line_info,
load_attr->line_info_cnt,
load_attr->line_info_rec_size,
attr.line_info_rec_size);
if (!linfo)
goto done;
attr.line_info = ptr_to_u64(linfo);
attr.line_info_rec_size = load_attr->line_info_rec_size;
} else {
break;
}
fd = sys_bpf_prog_load(&attr, sizeof(attr));
if (fd >= 0)
goto done;
}
if (load_attr->log_level || !load_attr->log_buf)
goto done;
/* Try again with log */
attr.log_buf = ptr_to_u64(load_attr->log_buf);
attr.log_size = load_attr->log_buf_sz;
attr.log_level = 1;
load_attr->log_buf[0] = 0;
fd = sys_bpf_prog_load(&attr, sizeof(attr));
done:
free(finfo);
free(linfo);
return fd;
}
int bpf_load_program_xattr(const struct bpf_load_program_attr *load_attr,
char *log_buf, size_t log_buf_sz)
{
struct bpf_prog_load_params p = {};
if (!load_attr || !log_buf != !log_buf_sz)
return -EINVAL;
p.prog_type = load_attr->prog_type;
p.expected_attach_type = load_attr->expected_attach_type;
switch (p.prog_type) {
case BPF_PROG_TYPE_STRUCT_OPS:
case BPF_PROG_TYPE_LSM:
p.attach_btf_id = load_attr->attach_btf_id;
break;
case BPF_PROG_TYPE_TRACING:
case BPF_PROG_TYPE_EXT:
p.attach_btf_id = load_attr->attach_btf_id;
p.attach_prog_fd = load_attr->attach_prog_fd;
break;
default:
p.prog_ifindex = load_attr->prog_ifindex;
p.kern_version = load_attr->kern_version;
}
p.insn_cnt = load_attr->insns_cnt;
p.insns = load_attr->insns;
p.license = load_attr->license;
p.log_level = load_attr->log_level;
p.log_buf = log_buf;
p.log_buf_sz = log_buf_sz;
p.prog_btf_fd = load_attr->prog_btf_fd;
p.func_info_rec_size = load_attr->func_info_rec_size;
p.func_info_cnt = load_attr->func_info_cnt;
p.func_info = load_attr->func_info;
p.line_info_rec_size = load_attr->line_info_rec_size;
p.line_info_cnt = load_attr->line_info_cnt;
p.line_info = load_attr->line_info;
p.name = load_attr->name;
p.prog_flags = load_attr->prog_flags;
return libbpf__bpf_prog_load(&p);
}
int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,
size_t insns_cnt, const char *license,
__u32 kern_version, char *log_buf,
size_t log_buf_sz)
{
struct bpf_load_program_attr load_attr;
memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
load_attr.prog_type = type;
load_attr.expected_attach_type = 0;
load_attr.name = NULL;
load_attr.insns = insns;
load_attr.insns_cnt = insns_cnt;
load_attr.license = license;
load_attr.kern_version = kern_version;
return bpf_load_program_xattr(&load_attr, log_buf, log_buf_sz);
}
int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns,
size_t insns_cnt, __u32 prog_flags, const char *license,
__u32 kern_version, char *log_buf, size_t log_buf_sz,
int log_level)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.prog_type = type;
attr.insn_cnt = (__u32)insns_cnt;
attr.insns = ptr_to_u64(insns);
attr.license = ptr_to_u64(license);
attr.log_buf = ptr_to_u64(log_buf);
attr.log_size = log_buf_sz;
attr.log_level = log_level;
log_buf[0] = 0;
attr.kern_version = kern_version;
attr.prog_flags = prog_flags;
return sys_bpf_prog_load(&attr, sizeof(attr));
}
int bpf_map_update_elem(int fd, const void *key, const void *value,
__u64 flags)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
attr.value = ptr_to_u64(value);
attr.flags = flags;
return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
}
int bpf_map_lookup_elem(int fd, const void *key, void *value)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
attr.value = ptr_to_u64(value);
return sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}
int bpf_map_lookup_elem_flags(int fd, const void *key, void *value, __u64 flags)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
attr.value = ptr_to_u64(value);
attr.flags = flags;
return sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}
int bpf_map_lookup_and_delete_elem(int fd, const void *key, void *value)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
attr.value = ptr_to_u64(value);
return sys_bpf(BPF_MAP_LOOKUP_AND_DELETE_ELEM, &attr, sizeof(attr));
}
int bpf_map_delete_elem(int fd, const void *key)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
return sys_bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
}
int bpf_map_get_next_key(int fd, const void *key, void *next_key)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
attr.key = ptr_to_u64(key);
attr.next_key = ptr_to_u64(next_key);
return sys_bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
}
int bpf_map_freeze(int fd)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
return sys_bpf(BPF_MAP_FREEZE, &attr, sizeof(attr));
}
static int bpf_map_batch_common(int cmd, int fd, void *in_batch,
void *out_batch, void *keys, void *values,
__u32 *count,
const struct bpf_map_batch_opts *opts)
{
union bpf_attr attr;
int ret;
if (!OPTS_VALID(opts, bpf_map_batch_opts))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.batch.map_fd = fd;
attr.batch.in_batch = ptr_to_u64(in_batch);
attr.batch.out_batch = ptr_to_u64(out_batch);
attr.batch.keys = ptr_to_u64(keys);
attr.batch.values = ptr_to_u64(values);
attr.batch.count = *count;
attr.batch.elem_flags = OPTS_GET(opts, elem_flags, 0);
attr.batch.flags = OPTS_GET(opts, flags, 0);
ret = sys_bpf(cmd, &attr, sizeof(attr));
*count = attr.batch.count;
return ret;
}
int bpf_map_delete_batch(int fd, void *keys, __u32 *count,
const struct bpf_map_batch_opts *opts)
{
return bpf_map_batch_common(BPF_MAP_DELETE_BATCH, fd, NULL,
NULL, keys, NULL, count, opts);
}
int bpf_map_lookup_batch(int fd, void *in_batch, void *out_batch, void *keys,
void *values, __u32 *count,
const struct bpf_map_batch_opts *opts)
{
return bpf_map_batch_common(BPF_MAP_LOOKUP_BATCH, fd, in_batch,
out_batch, keys, values, count, opts);
}
int bpf_map_lookup_and_delete_batch(int fd, void *in_batch, void *out_batch,
void *keys, void *values, __u32 *count,
const struct bpf_map_batch_opts *opts)
{
return bpf_map_batch_common(BPF_MAP_LOOKUP_AND_DELETE_BATCH,
fd, in_batch, out_batch, keys, values,
count, opts);
}
int bpf_map_update_batch(int fd, void *keys, void *values, __u32 *count,
const struct bpf_map_batch_opts *opts)
{
return bpf_map_batch_common(BPF_MAP_UPDATE_BATCH, fd, NULL, NULL,
keys, values, count, opts);
}
int bpf_obj_pin(int fd, const char *pathname)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.pathname = ptr_to_u64((void *)pathname);
attr.bpf_fd = fd;
return sys_bpf(BPF_OBJ_PIN, &attr, sizeof(attr));
}
int bpf_obj_get(const char *pathname)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.pathname = ptr_to_u64((void *)pathname);
return sys_bpf(BPF_OBJ_GET, &attr, sizeof(attr));
}
int bpf_prog_attach(int prog_fd, int target_fd, enum bpf_attach_type type,
unsigned int flags)
{
DECLARE_LIBBPF_OPTS(bpf_prog_attach_opts, opts,
.flags = flags,
);
return bpf_prog_attach_xattr(prog_fd, target_fd, type, &opts);
}
int bpf_prog_attach_xattr(int prog_fd, int target_fd,
enum bpf_attach_type type,
const struct bpf_prog_attach_opts *opts)
{
union bpf_attr attr;
if (!OPTS_VALID(opts, bpf_prog_attach_opts))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.target_fd = target_fd;
attr.attach_bpf_fd = prog_fd;
attr.attach_type = type;
attr.attach_flags = OPTS_GET(opts, flags, 0);
attr.replace_bpf_fd = OPTS_GET(opts, replace_prog_fd, 0);
return sys_bpf(BPF_PROG_ATTACH, &attr, sizeof(attr));
}
int bpf_prog_detach(int target_fd, enum bpf_attach_type type)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.target_fd = target_fd;
attr.attach_type = type;
return sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
}
int bpf_prog_detach2(int prog_fd, int target_fd, enum bpf_attach_type type)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.target_fd = target_fd;
attr.attach_bpf_fd = prog_fd;
attr.attach_type = type;
return sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
}
int bpf_link_create(int prog_fd, int target_fd,
enum bpf_attach_type attach_type,
const struct bpf_link_create_opts *opts)
{
__u32 target_btf_id, iter_info_len;
union bpf_attr attr;
if (!OPTS_VALID(opts, bpf_link_create_opts))
return -EINVAL;
iter_info_len = OPTS_GET(opts, iter_info_len, 0);
target_btf_id = OPTS_GET(opts, target_btf_id, 0);
if (iter_info_len && target_btf_id)
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.link_create.prog_fd = prog_fd;
attr.link_create.target_fd = target_fd;
attr.link_create.attach_type = attach_type;
attr.link_create.flags = OPTS_GET(opts, flags, 0);
if (iter_info_len) {
attr.link_create.iter_info =
ptr_to_u64(OPTS_GET(opts, iter_info, (void *)0));
attr.link_create.iter_info_len = iter_info_len;
} else if (target_btf_id) {
attr.link_create.target_btf_id = target_btf_id;
}
return sys_bpf(BPF_LINK_CREATE, &attr, sizeof(attr));
}
int bpf_link_detach(int link_fd)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.link_detach.link_fd = link_fd;
return sys_bpf(BPF_LINK_DETACH, &attr, sizeof(attr));
}
int bpf_link_update(int link_fd, int new_prog_fd,
const struct bpf_link_update_opts *opts)
{
union bpf_attr attr;
if (!OPTS_VALID(opts, bpf_link_update_opts))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.link_update.link_fd = link_fd;
attr.link_update.new_prog_fd = new_prog_fd;
attr.link_update.flags = OPTS_GET(opts, flags, 0);
attr.link_update.old_prog_fd = OPTS_GET(opts, old_prog_fd, 0);
return sys_bpf(BPF_LINK_UPDATE, &attr, sizeof(attr));
}
int bpf_iter_create(int link_fd)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.iter_create.link_fd = link_fd;
return sys_bpf(BPF_ITER_CREATE, &attr, sizeof(attr));
}
int bpf_prog_query(int target_fd, enum bpf_attach_type type, __u32 query_flags,
__u32 *attach_flags, __u32 *prog_ids, __u32 *prog_cnt)
{
union bpf_attr attr;
int ret;
memset(&attr, 0, sizeof(attr));
attr.query.target_fd = target_fd;
attr.query.attach_type = type;
attr.query.query_flags = query_flags;
attr.query.prog_cnt = *prog_cnt;
attr.query.prog_ids = ptr_to_u64(prog_ids);
ret = sys_bpf(BPF_PROG_QUERY, &attr, sizeof(attr));
if (attach_flags)
*attach_flags = attr.query.attach_flags;
*prog_cnt = attr.query.prog_cnt;
return ret;
}
int bpf_prog_test_run(int prog_fd, int repeat, void *data, __u32 size,
void *data_out, __u32 *size_out, __u32 *retval,
__u32 *duration)
{
union bpf_attr attr;
int ret;
memset(&attr, 0, sizeof(attr));
attr.test.prog_fd = prog_fd;
attr.test.data_in = ptr_to_u64(data);
attr.test.data_out = ptr_to_u64(data_out);
attr.test.data_size_in = size;
attr.test.repeat = repeat;
ret = sys_bpf(BPF_PROG_TEST_RUN, &attr, sizeof(attr));
if (size_out)
*size_out = attr.test.data_size_out;
if (retval)
*retval = attr.test.retval;
if (duration)
*duration = attr.test.duration;
return ret;
}
int bpf_prog_test_run_xattr(struct bpf_prog_test_run_attr *test_attr)
{
union bpf_attr attr;
int ret;
if (!test_attr->data_out && test_attr->data_size_out > 0)
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.test.prog_fd = test_attr->prog_fd;
attr.test.data_in = ptr_to_u64(test_attr->data_in);
attr.test.data_out = ptr_to_u64(test_attr->data_out);
attr.test.data_size_in = test_attr->data_size_in;
attr.test.data_size_out = test_attr->data_size_out;
attr.test.ctx_in = ptr_to_u64(test_attr->ctx_in);
attr.test.ctx_out = ptr_to_u64(test_attr->ctx_out);
attr.test.ctx_size_in = test_attr->ctx_size_in;
attr.test.ctx_size_out = test_attr->ctx_size_out;
attr.test.repeat = test_attr->repeat;
ret = sys_bpf(BPF_PROG_TEST_RUN, &attr, sizeof(attr));
test_attr->data_size_out = attr.test.data_size_out;
test_attr->ctx_size_out = attr.test.ctx_size_out;
test_attr->retval = attr.test.retval;
test_attr->duration = attr.test.duration;
return ret;
}
int bpf_prog_test_run_opts(int prog_fd, struct bpf_test_run_opts *opts)
{
union bpf_attr attr;
int ret;
if (!OPTS_VALID(opts, bpf_test_run_opts))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.test.prog_fd = prog_fd;
attr.test.cpu = OPTS_GET(opts, cpu, 0);
attr.test.flags = OPTS_GET(opts, flags, 0);
attr.test.repeat = OPTS_GET(opts, repeat, 0);
attr.test.duration = OPTS_GET(opts, duration, 0);
attr.test.ctx_size_in = OPTS_GET(opts, ctx_size_in, 0);
attr.test.ctx_size_out = OPTS_GET(opts, ctx_size_out, 0);
attr.test.data_size_in = OPTS_GET(opts, data_size_in, 0);
attr.test.data_size_out = OPTS_GET(opts, data_size_out, 0);
attr.test.ctx_in = ptr_to_u64(OPTS_GET(opts, ctx_in, NULL));
attr.test.ctx_out = ptr_to_u64(OPTS_GET(opts, ctx_out, NULL));
attr.test.data_in = ptr_to_u64(OPTS_GET(opts, data_in, NULL));
attr.test.data_out = ptr_to_u64(OPTS_GET(opts, data_out, NULL));
ret = sys_bpf(BPF_PROG_TEST_RUN, &attr, sizeof(attr));
OPTS_SET(opts, data_size_out, attr.test.data_size_out);
OPTS_SET(opts, ctx_size_out, attr.test.ctx_size_out);
OPTS_SET(opts, duration, attr.test.duration);
OPTS_SET(opts, retval, attr.test.retval);
return ret;
}
static int bpf_obj_get_next_id(__u32 start_id, __u32 *next_id, int cmd)
{
union bpf_attr attr;
int err;
memset(&attr, 0, sizeof(attr));
attr.start_id = start_id;
err = sys_bpf(cmd, &attr, sizeof(attr));
if (!err)
*next_id = attr.next_id;
return err;
}
int bpf_prog_get_next_id(__u32 start_id, __u32 *next_id)
{
return bpf_obj_get_next_id(start_id, next_id, BPF_PROG_GET_NEXT_ID);
}
int bpf_map_get_next_id(__u32 start_id, __u32 *next_id)
{
return bpf_obj_get_next_id(start_id, next_id, BPF_MAP_GET_NEXT_ID);
}
int bpf_btf_get_next_id(__u32 start_id, __u32 *next_id)
{
return bpf_obj_get_next_id(start_id, next_id, BPF_BTF_GET_NEXT_ID);
}
int bpf_link_get_next_id(__u32 start_id, __u32 *next_id)
{
return bpf_obj_get_next_id(start_id, next_id, BPF_LINK_GET_NEXT_ID);
}
int bpf_prog_get_fd_by_id(__u32 id)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.prog_id = id;
return sys_bpf(BPF_PROG_GET_FD_BY_ID, &attr, sizeof(attr));
}
int bpf_map_get_fd_by_id(__u32 id)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.map_id = id;
return sys_bpf(BPF_MAP_GET_FD_BY_ID, &attr, sizeof(attr));
}
int bpf_btf_get_fd_by_id(__u32 id)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.btf_id = id;
return sys_bpf(BPF_BTF_GET_FD_BY_ID, &attr, sizeof(attr));
}
int bpf_link_get_fd_by_id(__u32 id)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.link_id = id;
return sys_bpf(BPF_LINK_GET_FD_BY_ID, &attr, sizeof(attr));
}
int bpf_obj_get_info_by_fd(int bpf_fd, void *info, __u32 *info_len)
{
union bpf_attr attr;
int err;
memset(&attr, 0, sizeof(attr));
attr.info.bpf_fd = bpf_fd;
attr.info.info_len = *info_len;
attr.info.info = ptr_to_u64(info);
err = sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));
if (!err)
*info_len = attr.info.info_len;
return err;
}
int bpf_raw_tracepoint_open(const char *name, int prog_fd)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.raw_tracepoint.name = ptr_to_u64(name);
attr.raw_tracepoint.prog_fd = prog_fd;
return sys_bpf(BPF_RAW_TRACEPOINT_OPEN, &attr, sizeof(attr));
}
int bpf_load_btf(const void *btf, __u32 btf_size, char *log_buf, __u32 log_buf_size,
bool do_log)
{
union bpf_attr attr = {};
int fd;
attr.btf = ptr_to_u64(btf);
attr.btf_size = btf_size;
retry:
if (do_log && log_buf && log_buf_size) {
attr.btf_log_level = 1;
attr.btf_log_size = log_buf_size;
attr.btf_log_buf = ptr_to_u64(log_buf);
}
fd = sys_bpf(BPF_BTF_LOAD, &attr, sizeof(attr));
if (fd == -1 && !do_log && log_buf && log_buf_size) {
do_log = true;
goto retry;
}
return fd;
}
int bpf_task_fd_query(int pid, int fd, __u32 flags, char *buf, __u32 *buf_len,
__u32 *prog_id, __u32 *fd_type, __u64 *probe_offset,
__u64 *probe_addr)
{
union bpf_attr attr = {};
int err;
attr.task_fd_query.pid = pid;
attr.task_fd_query.fd = fd;
attr.task_fd_query.flags = flags;
attr.task_fd_query.buf = ptr_to_u64(buf);
attr.task_fd_query.buf_len = *buf_len;
err = sys_bpf(BPF_TASK_FD_QUERY, &attr, sizeof(attr));
*buf_len = attr.task_fd_query.buf_len;
*prog_id = attr.task_fd_query.prog_id;
*fd_type = attr.task_fd_query.fd_type;
*probe_offset = attr.task_fd_query.probe_offset;
*probe_addr = attr.task_fd_query.probe_addr;
return err;
}
int bpf_enable_stats(enum bpf_stats_type type)
{
union bpf_attr attr;
memset(&attr, 0, sizeof(attr));
attr.enable_stats.type = type;
return sys_bpf(BPF_ENABLE_STATS, &attr, sizeof(attr));
}
int bpf_prog_bind_map(int prog_fd, int map_fd,
const struct bpf_prog_bind_opts *opts)
{
union bpf_attr attr;
if (!OPTS_VALID(opts, bpf_prog_bind_opts))
return -EINVAL;
memset(&attr, 0, sizeof(attr));
attr.prog_bind_map.prog_fd = prog_fd;
attr.prog_bind_map.map_fd = map_fd;
attr.prog_bind_map.flags = OPTS_GET(opts, flags, 0);
return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
}
|
430719.c | #include <core/test.h>
#include <core/time.h>
#include <log.h>
static void *setup(unit_test *this)
{
return NULL;
}
static void clean(unit_test *this, void *data)
{
}
static void run(unit_test *this, void *data)
{
}
class_impl(unit_test){
.result = TRUE,
.setup = setup,
.clean = clean,
.run = run,
};
static void print_time(ktime_t t)
{
s64_t div = 1;
const char *unit = "ns";
if (ktime_to_ns(t) > 1000L)
{
div = 1000L;
unit = "us";
}
if (ktime_to_ns(t) > 1000000L)
{
div = 1000000L;
unit = "ms";
}
if (ktime_to_ns(t) > 1000000000L)
{
div = 1000000000L;
unit = "s";
}
printv(" " $((int)(ktime_to_ns(t) / div)) $(unit));
}
static void do_unit_test(type_index index, int order, int *pass, int *fail)
{
struct list_head *child = get_class_child(index);
struct class_table_info *info;
list_for_each_entry(info, child, list)
{
printv("Test [" $(order) "]");
void *obj = new_class_object(info->type);
if (obj == NULL)
{
printv("Failed to new " $(__class_name(info->type)) "\n");
continue;
}
unit_test *ut = dynamic_cast(unit_test)(obj);
printv("[" $(ut->ut_name) "]");
ktime_t t1 = ktime_get();
{
void *data = (ut->setup != NULL) ? ut->setup(ut) : NULL;
ut->run(ut, data);
if (ut->clean != NULL)
{
ut->clean(ut, data);
}
}
ktime_t t2 = ktime_get();
print_time(ktime_sub(t2, t1));
if (ut->result)
{
printv(" \e[32m[PASS]\e[0m\n");
(*pass)++;
}
else
{
printv(" \e[31m[FAIL]\e[0m\n");
(*fail)++;
}
order++;
if (ut != 0)
delete_class_object(ut);
}
list_for_each_entry(info, child, list)
{
do_unit_test(info->type, order, pass, fail);
}
}
void do_all_test()
{
printv("\n\n##################### Unit Test #####################\n");
int pass = 0, fail = 0;
do_unit_test(class_type(unit_test), 1, &pass, &fail);
printv("\nPASS ["$(pass)"] FAIL ["$(fail)"]\n");
printv("##################### END #####################\n");
} |
691385.c | /* hCommon.c - routines used by many files in hgap project. */
/* Copyright (C) 2014 The Regents of the University of California
* See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */
#include "common.h"
#include "hCommon.h"
#include "chromInfo.h"
#include "portable.h"
#include "hgConfig.h"
#include "errAbort.h"
static char *_hgcName = "../cgi-bin/hgc"; /* Path to click processing program. */
static char *_hgTracksName = "../cgi-bin/hgTracks"; /* Path back to genome browser. */
static char *_hgTrackUiName = "../cgi-bin/hgTrackUi"; /* Path to extended ui program. */
static char *_hgFileUiName = "../cgi-bin/hgFileUi"; /* Path to downloladable files CGI. */
static char *_hgTextName = "../cgi-bin/hgText"; /* Path back to the text browser. */
static char *_hgTablesName = "../cgi-bin/hgTables"; /* Path back to the table browser. */
static char *_hgVaiName = "../cgi-bin/hgVai"; /* Path back to the variant annotation integrator. */
static char *_hgCustomName = "../cgi-bin/hgCustom"; /* Path back to the custom tracks manager. */
static char *_hgCollectionName = "../cgi-bin/hgCollection"; /* Path back to the composite builder */
static char *_hgHubConnectName = "../cgi-bin/hgHubConnect"; /* Path back to the track hub manager. */
static char *_hgSessionName = "../cgi-bin/hgSession"; /* Path to session manager. */
static char *_hgPalName = "../cgi-bin/hgPal"; /* Path back to the protein aligner */
static char *_hgVarAnnogratorName = "../cgi-bin/hgVarAnnogrator"; /* Path to variant annot intgr */
static char *_hgIntegratorName = "../cgi-bin/hgIntegrator"; /* Path to annotation intgrator */
static char *_hgGeneName = "../cgi-bin/hgGene"; /* Path to gene details */
char *hgPalName()
/* Relative URL to click processing program. */
{
return _hgPalName;
}
char *hgcName()
/* Relative URL to click processing program. */
{
return _hgcName;
}
char *hgTracksName()
/* Relative URL to browser. */
{
return _hgTracksName;
}
char *hgTrackUiName()
/* Relative URL to extended track UI. */
{
return _hgTrackUiName;
}
char *hgFileUiName()
/* Relative URL to downloladable files UI. */
{
return _hgFileUiName;
}
char *hgTextName()
/* Relative URL to old table browser. */
{
return _hgTextName;
}
char *hgTablesName()
/* Relative URL to table browser. */
{
return _hgTablesName;
}
char *hgVaiName()
/* Relative URL to variant annotation integrator. */
{
return _hgVaiName;
}
char *hgCustomName()
/* Relative URL to custom tracks manager. */
{
return _hgCustomName;
}
char *hgCollectionName()
/* Relative URL to composite builder. */
{
return _hgCollectionName;
}
char *hgHubConnectName()
/* Relative URL to track hub manager. */
{
return _hgHubConnectName;
}
char *hgSessionName()
/* Relative URL to session manager. */
{
return _hgSessionName;
}
char *hgVarAnnogratorName()
/* Relative URL to variant annotation integrator program. */
{
return _hgVarAnnogratorName;
}
char *hgIntegratorName()
/* Relative URL to annotation integrator program. */
{
return _hgIntegratorName;
}
char *hgGeneName()
/* Relative URL to gene details program (hgGene). */
{
return _hgGeneName;
}
static void finishCloneName(char *fragName, char *e, char cloneName[128])
/* Finish conversion from frag to clone or clone.ver name. */
{
int size;
if (e == NULL)
e = fragName + strlen(fragName);
size = e - fragName;
if (size >= 128)
errAbort("name too long %s\n", fragName);
memcpy(cloneName, fragName, size);
cloneName[size] = 0;
}
void fragToCloneName(char *fragName, char cloneName[128])
/* Convert fragment name to clone name. */
{
char *e = strchr(fragName, '.');
finishCloneName(fragName, e, cloneName);
}
void fragToCloneVerName(char *fragName, char cloneVerName[128])
/* Convert fragment name to clone.version name. */
{
char *e = strchr(fragName, '.');
if (e == NULL)
errAbort("No . in fragName %s", fragName);
e = strchr(e, '_');
finishCloneName(fragName, e, cloneVerName);
}
void recNameToFileName(char *dir, char *recName, char *fileName, char *suffix)
/* Convert UCSC style fragment name to name of file for a clone. */
{
char *e;
char *d = fileName;
int size;
/* Start file name with directory if any. */
if (dir != NULL)
{
size = strlen(dir);
memcpy(d, dir, size);
d += size;
if (dir[size-1] != '/')
*d++ = '/';
}
if (*recName == '>')
++recName;
recName = skipLeadingSpaces(recName);
e = strchr(recName, '.');
if (e == NULL)
e = skipToSpaces(recName);
if (e == NULL)
e = recName + strlen(recName);
size = e - recName;
memcpy(d, recName, size);
d += size;
strcpy(d, suffix);
}
void faRecNameToQacFileName(char *dir, char *recName, char *fileName)
/* Convert fa record name to file name. */
{
recNameToFileName(dir, recName, fileName, ".qac");
}
void faRecNameToFaFileName(char *dir, char *recName, char *fileName)
/* Convert fa record name to file name. */
{
recNameToFileName(dir, recName, fileName, ".fa");
}
void gsToUcsc(char *gsName, char *ucscName)
/* Convert from
* AC020585.5~1.2 Fragment 2 of 29 (AC020585.5:1..1195)
* to
* AC020585.5_1_2
*/
{
char *s, *e, *d;
int size;
/* Copy in accession and version. */
d = ucscName;
s = gsName;
e = strchr(s, '~');
if (e == NULL)
errAbort("Expecting . in %s", gsName);
size = e - s;
memcpy(d, s, size);
d += size;
/* Skip over tilde and replace it with _ */
s = e+1;
*d++ = '_';
e = skipToSpaces(s);
if (e == NULL)
e = s + strlen(s);
size = e - s;
memcpy(d, s, size);
d[size] = 0;
subChar(d, '.', '_');
return;
}
char *skipChr(char *s)
/* Skip leading 'chr' in string (to get the actual chromosome part). */
{
if (startsWith("chr", s))
s += 3;
else if (startsWith("scaffold_", s))
s += 9;
else if (startsWith("Scaffold_", s))
s += 9;
return s;
}
int chromToInt(char *s)
/* converts a chrom name chrXX into an integer from 1 to 54.
X = 23 Y = 24 Un = 25 M = 26 random = chr + 26;*/
{
char *u;
int ret = 0;
char str[64];
if (!startsWith("chr", s))
{
return 0;
}
s += 3;
safef(str, sizeof(str), "%s", s);
u = strchr(str,'_');
if (u != NULL)
{
ret = 26;
*u = '\0';
}
switch (str[0])
{
case 'X':
ret += 23;
break;
case 'Y':
ret += 24;
break;
case 'U':
ret += 25;
break;
case 'M':
ret += 26;
break;
default:
ret += atoi(s);
}
return ret;
}
void hTableStart()
/* Output a table with solid borders. */
/* For some reason BORDER=1 does not work in our web.c nested table scheme.
* So use web.c's trick of using an enclosing table to provide a border. */
{
puts("<!--hTableStart-->" "\n"
"<TABLE BGCOLOR=\"#"HG_COL_BORDER"\" BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"1\"><TR><TD>");
puts("<TABLE BORDER=\"1\" BGCOLOR=\"#"HG_COL_INSIDE"\" CELLSPACING=\"0\">");
}
void hTableEnd()
/* Close out table started with hTableStart() */
{
puts("</TABLE>");
puts("</TD></TR></TABLE>");
puts("<!--hTableEnd-->");
}
static boolean stackDumpDisabled = FALSE; // prevent accidental recursion or undesired dumps
static boolean hDumpAbortCalled = FALSE;
static void hDumpStackAbortHandler()
/* abort handle that prints stack dump then invokes the previous abort
* handler on the stack. */
{
if (stackDumpDisabled)
{
stackDumpDisabled = FALSE;
}
else
{
dumpStack("\nStack dump:");
}
hDumpAbortCalled = TRUE;
popAbortHandler(); // remove us from the stack
// continue with next abort handler
noWarnAbort();
}
boolean hDumpStackEnabled(void)
/* is browser.pstack enabled? */
{
return cfgOptionBooleanDefault("browser.dumpStack", FALSE);
}
void hDumpStackDisallow(void)
/* prevent any dumping of the stack */
{
stackDumpDisabled = TRUE;
}
void hDumpStackPushAbortHandler(void)
/* push the stack dump abort handler on the stack if it's enabled. This should be pushed
* after the warn handle that will do the actual reporting */
{
if (hDumpStackEnabled())
{
errAbortDebugnPushPopErr();
pushAbortHandler(hDumpStackAbortHandler);
}
}
void hDumpStackPopAbortHandler()
/* pop the stack dump abort handler from the stack if it's enabled */
{
if (hDumpStackEnabled() && !hDumpAbortCalled)
popAbortHandler();
hDumpAbortCalled = FALSE;
}
void hVaUserAbort(char *format, va_list args)
/* errAbort when a `user' error is detected. This is an error that comes
* from user input. This disables the logging stack dumps. */
{
hDumpStackDisallow();
vaErrAbort(format, args);
}
void hUserAbort(char *format, ...)
/* errAbort when a `user' error is detected. This is an error that comes
* from user input. This disables the logging stack dumps. */
{
va_list args;
va_start(args, format);
hVaUserAbort(format, args);
va_end(args);
}
boolean hAllowAllTables(void)
/* Return TRUE if hg.conf's hgta.disableAllTables doesn't forbid an 'all tables' menu. */
{
return !cfgOptionBooleanDefault("hgta.disableAllTables", FALSE);
}
|
211721.c | /*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <types.h>
#include <atomic.h>
#include <bits.h>
#include <page.h>
#include <e820.h>
#include <mmu.h>
#include <vtd.h>
#include <lapic.h>
#include <per_cpu.h>
#include <cpufeatures.h>
#include <cpu_caps.h>
#include <acpi.h>
#include <ioapic.h>
#include <trampoline.h>
#include <cpuid.h>
#include <version.h>
#include <vmx.h>
#include <vm.h>
#include <ld_sym.h>
#include <logmsg.h>
#include <cat.h>
#include <vboot.h>
#define CPU_UP_TIMEOUT 100U /* millisecond */
#define CPU_DOWN_TIMEOUT 100U /* millisecond */
struct per_cpu_region per_cpu_data[CONFIG_MAX_PCPU_NUM] __aligned(PAGE_SIZE);
static uint16_t phys_cpu_num = 0U;
static uint64_t pcpu_sync = 0UL;
static uint16_t up_count = 0U;
static uint64_t startup_paddr = 0UL;
/* physical cpu active bitmap, support up to 64 cpus */
static uint64_t pcpu_active_bitmap = 0UL;
static void pcpu_xsave_init(void);
static void set_current_pcpu_id(uint16_t pcpu_id);
static void print_hv_banner(void);
static uint16_t get_pcpu_id_from_lapic_id(uint32_t lapic_id);
static uint64_t start_tsc __attribute__((__section__(".bss_noinit")));
static bool init_percpu_lapic_id(void)
{
uint16_t i;
uint16_t pcpu_num;
uint32_t lapic_id_array[CONFIG_MAX_PCPU_NUM];
bool success = false;
/* Save all lapic_id detected via parse_mdt in lapic_id_array */
pcpu_num = parse_madt(lapic_id_array);
if (pcpu_num != 0U) {
phys_cpu_num = pcpu_num;
for (i = 0U; (i < pcpu_num) && (i < CONFIG_MAX_PCPU_NUM); i++) {
per_cpu(lapic_id, i) = lapic_id_array[i];
}
success = true;
}
return success;
}
static void pcpu_set_current_state(uint16_t pcpu_id, enum pcpu_boot_state state)
{
/* Check if state is initializing */
if (state == PCPU_STATE_INITIALIZING) {
/* Increment CPU up count */
atomic_inc16(&up_count);
/* Save this CPU's logical ID to the TSC AUX MSR */
set_current_pcpu_id(pcpu_id);
}
/* If cpu is dead, decrement CPU up count */
if (state == PCPU_STATE_DEAD) {
atomic_dec16(&up_count);
}
/* Set state for the specified CPU */
per_cpu(boot_state, pcpu_id) = state;
}
uint16_t get_pcpu_nums(void)
{
return phys_cpu_num;
}
bool is_pcpu_active(uint16_t pcpu_id)
{
return bitmap_test(pcpu_id, &pcpu_active_bitmap);
}
uint64_t get_active_pcpu_bitmap(void)
{
return pcpu_active_bitmap;
}
void init_pcpu_pre(uint16_t pcpu_id_args)
{
uint16_t pcpu_id = pcpu_id_args;
int32_t ret;
if (pcpu_id == BOOT_CPU_ID) {
start_tsc = rdtsc();
/* Clear BSS */
(void)memset(&ld_bss_start, 0U, (size_t)(&ld_bss_end - &ld_bss_start));
/* Get CPU capabilities thru CPUID, including the physical address bit
* limit which is required for initializing paging.
*/
init_pcpu_capabilities();
init_vboot_operations();
init_pcpu_model_name();
load_pcpu_state_data();
/* Initialize the hypervisor paging */
init_e820();
init_paging();
if (!pcpu_has_cap(X86_FEATURE_X2APIC)) {
panic("x2APIC is not present!");
}
early_init_lapic();
if (!init_percpu_lapic_id()) {
panic("failed to init_percpu_lapic_id!");
}
ret = init_ioapic_id_info();
if (ret != 0) {
panic("System IOAPIC info is incorrect!");
}
ret = init_cat_cap_info();
if (ret != 0) {
panic("Platform CAT info is incorrect!");
}
} else {
/* Switch this CPU to use the same page tables set-up by the
* primary/boot CPU
*/
enable_paging();
early_init_lapic();
pcpu_id = get_pcpu_id_from_lapic_id(get_cur_lapic_id());
if (pcpu_id >= CONFIG_MAX_PCPU_NUM) {
panic("Invalid pCPU ID!");
}
}
bitmap_set_nolock(pcpu_id, &pcpu_active_bitmap);
/* Set state for this CPU to initializing */
pcpu_set_current_state(pcpu_id, PCPU_STATE_INITIALIZING);
}
void init_pcpu_post(uint16_t pcpu_id)
{
#ifdef STACK_PROTECTOR
set_fs_base();
#endif
load_gdtr_and_tr();
enable_smep();
enable_smap();
pcpu_xsave_init();
if (pcpu_id == BOOT_CPU_ID) {
/* Print Hypervisor Banner */
print_hv_banner();
/* Calibrate TSC Frequency */
calibrate_tsc();
pr_acrnlog("HV version %s-%s-%s %s (daily tag:%s) build by %s, start time %lluus",
HV_FULL_VERSION,
HV_BUILD_TIME, HV_BUILD_VERSION, HV_BUILD_TYPE,
HV_DAILY_TAG,
HV_BUILD_USER, ticks_to_us(start_tsc));
pr_acrnlog("API version %u.%u",
HV_API_MAJOR_VERSION, HV_API_MINOR_VERSION);
pr_acrnlog("Detect processor: %s", (get_pcpu_info())->model_name);
pr_dbg("Core %hu is up", BOOT_CPU_ID);
if (detect_hardware_support() != 0) {
panic("hardware not support!");
}
if (!sanitize_vm_config()) {
panic("VM Configuration Error!");
}
/* Warn for security feature not ready */
if (!check_cpu_security_cap()) {
pr_fatal("SECURITY WARNING!!!!!!");
pr_fatal("Please apply the latest CPU uCode patch!");
}
init_scheduler();
/* Initialize interrupts */
init_interrupt(BOOT_CPU_ID);
timer_init();
setup_notification();
setup_posted_intr_notification();
init_pci_pdev_list();
if (init_iommu() != 0) {
panic("failed to initialize iommu!");
}
ptdev_init();
/* Start all secondary cores */
startup_paddr = prepare_trampoline();
if (!start_pcpus(AP_MASK)) {
panic("Failed to start all secondary cores!");
}
ASSERT(get_pcpu_id() == BOOT_CPU_ID, "");
} else {
pr_dbg("Core %hu is up", pcpu_id);
/* Initialize secondary processor interrupts. */
init_interrupt(pcpu_id);
timer_init();
/* Wait for boot processor to signal all secondary cores to continue */
wait_sync_change(&pcpu_sync, 0UL);
}
setup_clos(pcpu_id);
}
static uint16_t get_pcpu_id_from_lapic_id(uint32_t lapic_id)
{
uint16_t i;
uint16_t pcpu_id = INVALID_CPU_ID;
for (i = 0U; (i < phys_cpu_num) && (i < CONFIG_MAX_PCPU_NUM); i++) {
if (per_cpu(lapic_id, i) == lapic_id) {
pcpu_id = i;
break;
}
}
return pcpu_id;
}
static void start_pcpu(uint16_t pcpu_id)
{
uint32_t timeout;
/* Update the stack for pcpu */
stac();
write_trampoline_stack_sym(pcpu_id);
clac();
send_startup_ipi(INTR_CPU_STARTUP_USE_DEST, pcpu_id, startup_paddr);
/* Wait until the pcpu with pcpu_id is running and set the active bitmap or
* configured time-out has expired
*/
timeout = CPU_UP_TIMEOUT * 1000U;
while (!is_pcpu_active(pcpu_id) && (timeout != 0U)) {
/* Delay 10us */
udelay(10U);
/* Decrement timeout value */
timeout -= 10U;
}
/* Check to see if expected CPU is actually up */
if (!is_pcpu_active(pcpu_id)) {
pr_fatal("Secondary CPU%hu failed to come up", pcpu_id);
pcpu_set_current_state(pcpu_id, PCPU_STATE_DEAD);
}
}
/**
* @brief Start all cpus if the bit is set in mask except itself
*
* @param[in] mask bits mask of cpus which should be started
*
* @return true if all cpus set in mask are started
* @return false if there are any cpus set in mask aren't started
*/
bool start_pcpus(uint64_t mask)
{
uint16_t i;
uint16_t pcpu_id = get_pcpu_id();
uint64_t expected_start_mask = mask;
/* secondary cpu start up will wait for pcpu_sync -> 0UL */
atomic_store64(&pcpu_sync, 1UL);
i = ffs64(expected_start_mask);
while (i != INVALID_BIT_INDEX) {
bitmap_clear_nolock(i, &expected_start_mask);
if (pcpu_id == i) {
continue; /* Avoid start itself */
}
start_pcpu(i);
i = ffs64(expected_start_mask);
}
/* Trigger event to allow secondary CPUs to continue */
atomic_store64(&pcpu_sync, 0UL);
return ((pcpu_active_bitmap & mask) == mask);
}
void wait_pcpus_offline(uint64_t mask)
{
uint32_t timeout;
timeout = CPU_DOWN_TIMEOUT * 1000U;
while (((pcpu_active_bitmap & mask) != 0UL) && (timeout != 0U)) {
udelay(10U);
timeout -= 10U;
}
}
void stop_pcpus(void)
{
uint16_t pcpu_id;
uint64_t mask = 0UL;
for (pcpu_id = 0U; pcpu_id < phys_cpu_num; pcpu_id++) {
if (get_pcpu_id() == pcpu_id) { /* avoid offline itself */
continue;
}
bitmap_set_nolock(pcpu_id, &mask);
make_pcpu_offline(pcpu_id);
}
/**
* Timeout never occurs here:
* If target cpu received a NMI and panic, it has called cpu_dead and make_pcpu_offline success.
* If target cpu is running, an IPI will be delivered to it and then call cpu_dead.
*/
wait_pcpus_offline(mask);
}
void cpu_do_idle(void)
{
asm_pause();
}
/**
* only run on current pcpu
*/
void cpu_dead(void)
{
/* For debug purposes, using a stack variable in the while loop enables
* us to modify the value using a JTAG probe and resume if needed.
*/
int32_t halt = 1;
uint16_t pcpu_id = get_pcpu_id();
if (bitmap_test(pcpu_id, &pcpu_active_bitmap)) {
/* clean up native stuff */
vmx_off();
cache_flush_invalidate_all();
/* Set state to show CPU is dead */
pcpu_set_current_state(pcpu_id, PCPU_STATE_DEAD);
bitmap_clear_nolock(pcpu_id, &pcpu_active_bitmap);
/* Halt the CPU */
do {
asm_hlt();
} while (halt != 0);
} else {
pr_err("pcpu%hu already dead", pcpu_id);
}
}
static void set_current_pcpu_id(uint16_t pcpu_id)
{
/* Write TSC AUX register */
msr_write(MSR_IA32_TSC_AUX, (uint64_t) pcpu_id);
}
static void print_hv_banner(void)
{
const char *boot_msg = "ACRN Hypervisor\n\r";
/* Print the boot message */
printf(boot_msg);
}
/* wait until *sync == wake_sync */
void wait_sync_change(uint64_t *sync, uint64_t wake_sync)
{
if (has_monitor_cap()) {
/* Wait for the event to be set using monitor/mwait */
asm volatile ("1: cmpq %%rbx,(%%rax)\n"
" je 2f\n"
" monitor\n"
" mwait\n"
" jmp 1b\n"
"2:\n"
:
: "a" (sync), "d"(0), "c"(0),
"b"(wake_sync)
: "cc");
} else {
/* Wait for the event to be set using pause */
asm volatile ("1: cmpq %%rbx,(%%rax)\n"
" je 2f\n"
" pause\n"
" jmp 1b\n"
"2:\n"
:
: "a" (sync), "d"(0), "c"(0),
"b"(wake_sync)
: "cc");
}
}
static void pcpu_xsave_init(void)
{
uint64_t val64;
struct cpuinfo_x86 *cpu_info;
if (pcpu_has_cap(X86_FEATURE_XSAVE)) {
CPU_CR_READ(cr4, &val64);
val64 |= CR4_OSXSAVE;
CPU_CR_WRITE(cr4, val64);
if (get_pcpu_id() == BOOT_CPU_ID) {
uint32_t ecx, unused;
cpuid(CPUID_FEATURES, &unused, &unused, &ecx, &unused);
/* if set, update it */
if ((ecx & CPUID_ECX_OSXSAVE) != 0U) {
cpu_info = get_pcpu_info();
cpu_info->cpuid_leaves[FEAT_1_ECX] |= CPUID_ECX_OSXSAVE;
}
}
}
}
static void smpcall_write_msr_func(void *data)
{
struct msr_data_struct *msr = (struct msr_data_struct *)data;
msr_write(msr->msr_index, msr->write_val);
}
void msr_write_pcpu(uint32_t msr_index, uint64_t value64, uint16_t pcpu_id)
{
struct msr_data_struct msr = {0};
uint64_t mask = 0UL;
if (pcpu_id == get_pcpu_id()) {
msr_write(msr_index, value64);
} else {
msr.msr_index = msr_index;
msr.write_val = value64;
bitmap_set_nolock(pcpu_id, &mask);
smp_call_function(mask, smpcall_write_msr_func, &msr);
}
}
static void smpcall_read_msr_func(void *data)
{
struct msr_data_struct *msr = (struct msr_data_struct *)data;
msr->read_val = msr_read(msr->msr_index);
}
uint64_t msr_read_pcpu(uint32_t msr_index, uint16_t pcpu_id)
{
struct msr_data_struct msr = {0};
uint64_t mask = 0UL;
uint64_t ret = 0;
if (pcpu_id == get_pcpu_id()) {
ret = msr_read(msr_index);
} else {
msr.msr_index = msr_index;
bitmap_set_nolock(pcpu_id, &mask);
smp_call_function(mask, smpcall_read_msr_func, &msr);
ret = msr.read_val;
}
return ret;
}
|
299825.c | #include <limits.h>
#include "history_buffer.h"
history_buffer *history_buffer_create(unsigned int min_traceback_length,
unsigned int traceback_group_length,
unsigned int renormalize_interval, unsigned int num_states,
shift_register_t highbit) {
history_buffer *buf = calloc(1, sizeof(history_buffer));
*(unsigned int *)&buf->min_traceback_length = min_traceback_length;
*(unsigned int *)&buf->traceback_group_length = traceback_group_length;
*(unsigned int *)&buf->cap = min_traceback_length + traceback_group_length;
*(unsigned int *)&buf->num_states = num_states;
*(shift_register_t *)&buf->highbit = highbit;
buf->history = malloc(buf->cap * sizeof(uint8_t *));
for (unsigned int i = 0; i < buf->cap; i++) {
buf->history[i] = calloc(num_states, sizeof(uint8_t));
}
buf->fetched = malloc(buf->cap * sizeof(uint8_t));
buf->index = 0;
buf->len = 0;
buf->renormalize_counter = 0;
buf->renormalize_interval = renormalize_interval;
return buf;
}
void history_buffer_destroy(history_buffer *buf) {
for (unsigned int i = 0; i < buf->cap; i++) {
free(buf->history[i]);
}
free(buf->history);
free(buf->fetched);
free(buf);
}
void history_buffer_reset(history_buffer *buf) {
buf->len = 0;
buf->index = 0;
}
uint8_t *history_buffer_get_slice(history_buffer *buf) { return buf->history[buf->index]; }
shift_register_t history_buffer_search(history_buffer *buf, const distance_t *distances,
unsigned int search_every) {
shift_register_t bestpath;
distance_t leasterror = USHRT_MAX;
// search for a state with the least error
for (shift_register_t state = 0; state < buf->num_states; state += search_every) {
if (distances[state] < leasterror) {
leasterror = distances[state];
bestpath = state;
}
}
return bestpath;
}
void history_buffer_renormalize(history_buffer *buf, distance_t *distances,
shift_register_t min_register) {
distance_t min_distance = distances[min_register];
for (shift_register_t i = 0; i < buf->num_states; i++) {
distances[i] -= min_distance;
}
}
void history_buffer_traceback(history_buffer *buf, shift_register_t bestpath,
unsigned int min_traceback_length, bit_writer_t *output) {
unsigned int fetched_index = 0;
shift_register_t highbit = buf->highbit;
unsigned int index = buf->index;
unsigned int cap = buf->cap;
for (unsigned int j = 0; j < min_traceback_length; j++) {
if (index == 0) {
index = cap - 1;
} else {
index--;
}
// we're walking backwards from what the work we did before
// so, we'll shift high order bits in
// the path will cross multiple different shift register states, and we determine
// which state by going backwards one time slice at a time
uint8_t history = buf->history[index][bestpath];
shift_register_t pathbit = history ? highbit : 0;
bestpath |= pathbit;
bestpath >>= 1;
}
unsigned int prefetch_index = index;
if (prefetch_index == 0) {
prefetch_index = cap - 1;
} else {
prefetch_index--;
}
unsigned int len = buf->len;
for (unsigned int j = min_traceback_length; j < len; j++) {
index = prefetch_index;
if (prefetch_index == 0) {
prefetch_index = cap - 1;
} else {
prefetch_index--;
}
__builtin_prefetch(buf->history[prefetch_index]);
// we're walking backwards from what the work we did before
// so, we'll shift high order bits in
// the path will cross multiple different shift register states, and we determine
// which state by going backwards one time slice at a time
uint8_t history = buf->history[index][bestpath];
shift_register_t pathbit = history ? highbit : 0;
bestpath |= pathbit;
bestpath >>= 1;
buf->fetched[fetched_index] = (pathbit ? 1 : 0);
fetched_index++;
}
bit_writer_write_bitlist_reversed(output, buf->fetched, fetched_index);
buf->len -= fetched_index;
}
void history_buffer_process_skip(history_buffer *buf, distance_t *distances, bit_writer_t *output,
unsigned int skip) {
buf->index++;
if (buf->index == buf->cap) {
buf->index = 0;
}
buf->renormalize_counter++;
buf->len++;
// there are four ways these branches can resolve
// a) we are neither renormalizing nor doing a traceback
// b) we are renormalizing but not doing a traceback
// c) we are renormalizing and doing a traceback
// d) we are not renormalizing but we are doing a traceback
// in case c, we want to save the effort of finding the bestpath
// since that's expensive
// so we have to check for that case after we renormalize
if (buf->renormalize_counter == buf->renormalize_interval) {
buf->renormalize_counter = 0;
shift_register_t bestpath = history_buffer_search(buf, distances, skip);
history_buffer_renormalize(buf, distances, bestpath);
if (buf->len == buf->cap) {
// reuse the bestpath found for renormalizing
history_buffer_traceback(buf, bestpath, buf->min_traceback_length, output);
}
} else if (buf->len == buf->cap) {
// not renormalizing, find the bestpath here
shift_register_t bestpath = history_buffer_search(buf, distances, skip);
history_buffer_traceback(buf, bestpath, buf->min_traceback_length, output);
}
}
void history_buffer_process(history_buffer *buf, distance_t *distances, bit_writer_t *output) {
history_buffer_process_skip(buf, distances, output, 1);
}
void history_buffer_flush(history_buffer *buf, bit_writer_t *output) {
history_buffer_traceback(buf, 0, 0, output);
}
|
236067.c | /*
* Fitipower FC0013 tuner driver
*
* Copyright (C) 2012 Hans-Frieder Vogt <[email protected]>
* partially based on driver code from Fitipower
* Copyright (C) 2010 Fitipower Integrated Technology Inc
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "fc0013.h"
#include "fc0013-priv.h"
static int fc0013_writereg(struct fc0013_priv *priv, u8 reg, u8 val)
{
u8 buf[2] = {reg, val};
struct i2c_msg msg = {
.addr = priv->addr, .flags = 0, .buf = buf, .len = 2
};
if (i2c_transfer(priv->i2c, &msg, 1) != 1) {
err("I2C write reg failed, reg: %02x, val: %02x", reg, val);
return -EREMOTEIO;
}
return 0;
}
static int fc0013_readreg(struct fc0013_priv *priv, u8 reg, u8 *val)
{
struct i2c_msg msg[2] = {
{ .addr = priv->addr, .flags = 0, .buf = ®, .len = 1 },
{ .addr = priv->addr, .flags = I2C_M_RD, .buf = val, .len = 1 },
};
if (i2c_transfer(priv->i2c, msg, 2) != 2) {
err("I2C read reg failed, reg: %02x", reg);
return -EREMOTEIO;
}
return 0;
}
static void fc0013_release(struct dvb_frontend *fe)
{
kfree(fe->tuner_priv);
fe->tuner_priv = NULL;
}
static int fc0013_init(struct dvb_frontend *fe)
{
struct fc0013_priv *priv = fe->tuner_priv;
int i, ret = 0;
unsigned char reg[] = {
0x00, /* reg. 0x00: dummy */
0x09, /* reg. 0x01 */
0x16, /* reg. 0x02 */
0x00, /* reg. 0x03 */
0x00, /* reg. 0x04 */
0x17, /* reg. 0x05 */
0x02, /* reg. 0x06 */
0x0a, /* reg. 0x07: CHECK */
0xff, /* reg. 0x08: AGC Clock divide by 256, AGC gain 1/256,
Loop Bw 1/8 */
0x6f, /* reg. 0x09: enable LoopThrough */
0xb8, /* reg. 0x0a: Disable LO Test Buffer */
0x82, /* reg. 0x0b: CHECK */
0xfc, /* reg. 0x0c: depending on AGC Up-Down mode, may need 0xf8 */
0x01, /* reg. 0x0d: AGC Not Forcing & LNA Forcing, may need 0x02 */
0x00, /* reg. 0x0e */
0x00, /* reg. 0x0f */
0x00, /* reg. 0x10 */
0x00, /* reg. 0x11 */
0x00, /* reg. 0x12 */
0x00, /* reg. 0x13 */
0x50, /* reg. 0x14: DVB-t High Gain, UHF.
Middle Gain: 0x48, Low Gain: 0x40 */
0x01, /* reg. 0x15 */
};
switch (priv->xtal_freq) {
case FC_XTAL_27_MHZ:
case FC_XTAL_28_8_MHZ:
reg[0x07] |= 0x20;
break;
case FC_XTAL_36_MHZ:
default:
break;
}
if (priv->dual_master)
reg[0x0c] |= 0x02;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1); /* open I2C-gate */
for (i = 1; i < sizeof(reg); i++) {
ret = fc0013_writereg(priv, i, reg[i]);
if (ret)
break;
}
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
if (ret)
err("fc0013_writereg failed: %d", ret);
return ret;
}
static int fc0013_sleep(struct dvb_frontend *fe)
{
/* nothing to do here */
return 0;
}
int fc0013_rc_cal_add(struct dvb_frontend *fe, int rc_val)
{
struct fc0013_priv *priv = fe->tuner_priv;
int ret;
u8 rc_cal;
int val;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1); /* open I2C-gate */
/* push rc_cal value, get rc_cal value */
ret = fc0013_writereg(priv, 0x10, 0x00);
if (ret)
goto error_out;
/* get rc_cal value */
ret = fc0013_readreg(priv, 0x10, &rc_cal);
if (ret)
goto error_out;
rc_cal &= 0x0f;
val = (int)rc_cal + rc_val;
/* forcing rc_cal */
ret = fc0013_writereg(priv, 0x0d, 0x11);
if (ret)
goto error_out;
/* modify rc_cal value */
if (val > 15)
ret = fc0013_writereg(priv, 0x10, 0x0f);
else if (val < 0)
ret = fc0013_writereg(priv, 0x10, 0x00);
else
ret = fc0013_writereg(priv, 0x10, (u8)val);
error_out:
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
return ret;
}
EXPORT_SYMBOL(fc0013_rc_cal_add);
int fc0013_rc_cal_reset(struct dvb_frontend *fe)
{
struct fc0013_priv *priv = fe->tuner_priv;
int ret;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1); /* open I2C-gate */
ret = fc0013_writereg(priv, 0x0d, 0x01);
if (!ret)
ret = fc0013_writereg(priv, 0x10, 0x00);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
return ret;
}
EXPORT_SYMBOL(fc0013_rc_cal_reset);
static int fc0013_set_vhf_track(struct fc0013_priv *priv, u32 freq)
{
int ret;
u8 tmp;
ret = fc0013_readreg(priv, 0x1d, &tmp);
if (ret)
goto error_out;
tmp &= 0xe3;
if (freq <= 177500) { /* VHF Track: 7 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x1c);
} else if (freq <= 184500) { /* VHF Track: 6 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x18);
} else if (freq <= 191500) { /* VHF Track: 5 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x14);
} else if (freq <= 198500) { /* VHF Track: 4 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x10);
} else if (freq <= 205500) { /* VHF Track: 3 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x0c);
} else if (freq <= 219500) { /* VHF Track: 2 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x08);
} else if (freq < 300000) { /* VHF Track: 1 */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x04);
} else { /* UHF and GPS */
ret = fc0013_writereg(priv, 0x1d, tmp | 0x1c);
}
error_out:
return ret;
}
static int fc0013_set_params(struct dvb_frontend *fe)
{
struct fc0013_priv *priv = fe->tuner_priv;
int i, ret = 0;
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
u32 freq = p->frequency / 1000;
u32 delsys = p->delivery_system;
unsigned char reg[7], am, pm, multi, tmp;
unsigned long f_vco;
unsigned short xtal_freq_khz_2, xin, xdiv;
bool vco_select = false;
if (fe->callback) {
ret = fe->callback(priv->i2c, DVB_FRONTEND_COMPONENT_TUNER,
FC_FE_CALLBACK_VHF_ENABLE, (freq > 300000 ? 0 : 1));
if (ret)
goto exit;
}
switch (priv->xtal_freq) {
case FC_XTAL_27_MHZ:
xtal_freq_khz_2 = 27000 / 2;
break;
case FC_XTAL_36_MHZ:
xtal_freq_khz_2 = 36000 / 2;
break;
case FC_XTAL_28_8_MHZ:
default:
xtal_freq_khz_2 = 28800 / 2;
break;
}
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1); /* open I2C-gate */
/* set VHF track */
ret = fc0013_set_vhf_track(priv, freq);
if (ret)
goto exit;
if (freq < 300000) {
/* enable VHF filter */
ret = fc0013_readreg(priv, 0x07, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x07, tmp | 0x10);
if (ret)
goto exit;
/* disable UHF & disable GPS */
ret = fc0013_readreg(priv, 0x14, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x14, tmp & 0x1f);
if (ret)
goto exit;
} else if (freq <= 862000) {
/* disable VHF filter */
ret = fc0013_readreg(priv, 0x07, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x07, tmp & 0xef);
if (ret)
goto exit;
/* enable UHF & disable GPS */
ret = fc0013_readreg(priv, 0x14, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x14, (tmp & 0x1f) | 0x40);
if (ret)
goto exit;
} else {
/* disable VHF filter */
ret = fc0013_readreg(priv, 0x07, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x07, tmp & 0xef);
if (ret)
goto exit;
/* disable UHF & enable GPS */
ret = fc0013_readreg(priv, 0x14, &tmp);
if (ret)
goto exit;
ret = fc0013_writereg(priv, 0x14, (tmp & 0x1f) | 0x20);
if (ret)
goto exit;
}
/* select frequency divider and the frequency of VCO */
if (freq < 37084) { /* freq * 96 < 3560000 */
multi = 96;
reg[5] = 0x82;
reg[6] = 0x00;
} else if (freq < 55625) { /* freq * 64 < 3560000 */
multi = 64;
reg[5] = 0x02;
reg[6] = 0x02;
} else if (freq < 74167) { /* freq * 48 < 3560000 */
multi = 48;
reg[5] = 0x42;
reg[6] = 0x00;
} else if (freq < 111250) { /* freq * 32 < 3560000 */
multi = 32;
reg[5] = 0x82;
reg[6] = 0x02;
} else if (freq < 148334) { /* freq * 24 < 3560000 */
multi = 24;
reg[5] = 0x22;
reg[6] = 0x00;
} else if (freq < 222500) { /* freq * 16 < 3560000 */
multi = 16;
reg[5] = 0x42;
reg[6] = 0x02;
} else if (freq < 296667) { /* freq * 12 < 3560000 */
multi = 12;
reg[5] = 0x12;
reg[6] = 0x00;
} else if (freq < 445000) { /* freq * 8 < 3560000 */
multi = 8;
reg[5] = 0x22;
reg[6] = 0x02;
} else if (freq < 593334) { /* freq * 6 < 3560000 */
multi = 6;
reg[5] = 0x0a;
reg[6] = 0x00;
} else if (freq < 950000) { /* freq * 4 < 3800000 */
multi = 4;
reg[5] = 0x12;
reg[6] = 0x02;
} else {
multi = 2;
reg[5] = 0x0a;
reg[6] = 0x02;
}
f_vco = freq * multi;
if (f_vco >= 3060000) {
reg[6] |= 0x08;
vco_select = true;
}
if (freq >= 45000) {
/* From divided value (XDIV) determined the FA and FP value */
xdiv = (unsigned short)(f_vco / xtal_freq_khz_2);
if ((f_vco - xdiv * xtal_freq_khz_2) >= (xtal_freq_khz_2 / 2))
xdiv++;
pm = (unsigned char)(xdiv / 8);
am = (unsigned char)(xdiv - (8 * pm));
if (am < 2) {
reg[1] = am + 8;
reg[2] = pm - 1;
} else {
reg[1] = am;
reg[2] = pm;
}
} else {
/* fix for frequency less than 45 MHz */
reg[1] = 0x06;
reg[2] = 0x11;
}
/* fix clock out */
reg[6] |= 0x20;
/* From VCO frequency determines the XIN ( fractional part of Delta
Sigma PLL) and divided value (XDIV) */
xin = (unsigned short)(f_vco - (f_vco / xtal_freq_khz_2) * xtal_freq_khz_2);
xin = (xin << 15) / xtal_freq_khz_2;
if (xin >= 16384)
xin += 32768;
reg[3] = xin >> 8;
reg[4] = xin & 0xff;
if (delsys == SYS_DVBT) {
reg[6] &= 0x3f; /* bits 6 and 7 describe the bandwidth */
switch (p->bandwidth_hz) {
case 6000000:
reg[6] |= 0x80;
break;
case 7000000:
reg[6] |= 0x40;
break;
case 8000000:
default:
break;
}
} else {
err("%s: modulation type not supported!", __func__);
return -EINVAL;
}
/* modified for Realtek demod */
reg[5] |= 0x07;
for (i = 1; i <= 6; i++) {
ret = fc0013_writereg(priv, i, reg[i]);
if (ret)
goto exit;
}
ret = fc0013_readreg(priv, 0x11, &tmp);
if (ret)
goto exit;
if (multi == 64)
ret = fc0013_writereg(priv, 0x11, tmp | 0x04);
else
ret = fc0013_writereg(priv, 0x11, tmp & 0xfb);
if (ret)
goto exit;
/* VCO Calibration */
ret = fc0013_writereg(priv, 0x0e, 0x80);
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x00);
/* VCO Re-Calibration if needed */
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x00);
if (!ret) {
msleep(10);
ret = fc0013_readreg(priv, 0x0e, &tmp);
}
if (ret)
goto exit;
/* vco selection */
tmp &= 0x3f;
if (vco_select) {
if (tmp > 0x3c) {
reg[6] &= ~0x08;
ret = fc0013_writereg(priv, 0x06, reg[6]);
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x80);
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x00);
}
} else {
if (tmp < 0x02) {
reg[6] |= 0x08;
ret = fc0013_writereg(priv, 0x06, reg[6]);
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x80);
if (!ret)
ret = fc0013_writereg(priv, 0x0e, 0x00);
}
}
priv->frequency = p->frequency;
priv->bandwidth = p->bandwidth_hz;
exit:
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
if (ret)
warn("%s: failed: %d", __func__, ret);
return ret;
}
static int fc0013_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct fc0013_priv *priv = fe->tuner_priv;
*frequency = priv->frequency;
return 0;
}
static int fc0013_get_if_frequency(struct dvb_frontend *fe, u32 *frequency)
{
/* always ? */
*frequency = 0;
return 0;
}
static int fc0013_get_bandwidth(struct dvb_frontend *fe, u32 *bandwidth)
{
struct fc0013_priv *priv = fe->tuner_priv;
*bandwidth = priv->bandwidth;
return 0;
}
#define INPUT_ADC_LEVEL -8
static int fc0013_get_rf_strength(struct dvb_frontend *fe, u16 *strength)
{
struct fc0013_priv *priv = fe->tuner_priv;
int ret;
unsigned char tmp;
int int_temp, lna_gain, int_lna, tot_agc_gain, power;
const int fc0013_lna_gain_table[] = {
/* low gain */
-63, -58, -99, -73,
-63, -65, -54, -60,
/* middle gain */
71, 70, 68, 67,
65, 63, 61, 58,
/* high gain */
197, 191, 188, 186,
184, 182, 181, 179,
};
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1); /* open I2C-gate */
ret = fc0013_writereg(priv, 0x13, 0x00);
if (ret)
goto err;
ret = fc0013_readreg(priv, 0x13, &tmp);
if (ret)
goto err;
int_temp = tmp;
ret = fc0013_readreg(priv, 0x14, &tmp);
if (ret)
goto err;
lna_gain = tmp & 0x1f;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
if (lna_gain < ARRAY_SIZE(fc0013_lna_gain_table)) {
int_lna = fc0013_lna_gain_table[lna_gain];
tot_agc_gain = (abs((int_temp >> 5) - 7) - 2 +
(int_temp & 0x1f)) * 2;
power = INPUT_ADC_LEVEL - tot_agc_gain - int_lna / 10;
if (power >= 45)
*strength = 255; /* 100% */
else if (power < -95)
*strength = 0;
else
*strength = (power + 95) * 255 / 140;
*strength |= *strength << 8;
} else {
ret = -1;
}
goto exit;
err:
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0); /* close I2C-gate */
exit:
if (ret)
warn("%s: failed: %d", __func__, ret);
return ret;
}
static const struct dvb_tuner_ops fc0013_tuner_ops = {
.info = {
.name = "Fitipower FC0013",
.frequency_min = 37000000, /* estimate */
.frequency_max = 1680000000, /* CHECK */
.frequency_step = 0,
},
.release = fc0013_release,
.init = fc0013_init,
.sleep = fc0013_sleep,
.set_params = fc0013_set_params,
.get_frequency = fc0013_get_frequency,
.get_if_frequency = fc0013_get_if_frequency,
.get_bandwidth = fc0013_get_bandwidth,
.get_rf_strength = fc0013_get_rf_strength,
};
struct dvb_frontend *fc0013_attach(struct dvb_frontend *fe,
struct i2c_adapter *i2c, u8 i2c_address, int dual_master,
enum fc001x_xtal_freq xtal_freq)
{
struct fc0013_priv *priv = NULL;
priv = kzalloc(sizeof(struct fc0013_priv), GFP_KERNEL);
if (priv == NULL)
return NULL;
priv->i2c = i2c;
priv->dual_master = dual_master;
priv->addr = i2c_address;
priv->xtal_freq = xtal_freq;
info("Fitipower FC0013 successfully attached.");
fe->tuner_priv = priv;
memcpy(&fe->ops.tuner_ops, &fc0013_tuner_ops,
sizeof(struct dvb_tuner_ops));
return fe;
}
EXPORT_SYMBOL(fc0013_attach);
MODULE_DESCRIPTION("Fitipower FC0013 silicon tuner driver");
MODULE_AUTHOR("Hans-Frieder Vogt <[email protected]>");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.2");
|
88694.c | /*
* Copyright (c) 2014-2017, Pelion and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include "mbed-client-libservice/ns_trace.h"
#include "nanostack-event-loop/eventOS_callback_timer.h"
#include "common/hal_interrupt.h"
#include "mac/ieee802154/sw_mac_internal.h"
#include "mac/ieee802154/mac_pd_sap.h"
#include "mac/ieee802154/mac_timer.h"
#include "nanostack/mac/sw_mac.h"
#define TRACE_GROUP "mTim"
/*-------------------MAC TIMER FUNCTIONS--------------------------*/
/**
* \brief Function starts MAC timer.
*
* \param event MAC event to timeout
* \param slots Number of MAC ticks (50us)
*
* \return none
*/
void timer_mac_start(protocol_interface_rf_mac_setup_s *rf_ptr, mac_event_t event, uint16_t slots)
{
/*Save MAC event*/
if (rf_ptr->mac_timer_id != -1) {
rf_ptr->timer_mac_event = event;
eventOS_callback_timer_start(rf_ptr->mac_timer_id, slots);
}
}
/**
* \brief Function stops MAC timer.
*
* \param none
*
* \return none
*/
void timer_mac_stop(protocol_interface_rf_mac_setup_s *rf_ptr)
{
platform_enter_critical();
if (rf_ptr->mac_timer_id != -1) {
eventOS_callback_timer_stop(rf_ptr->mac_timer_id);
rf_ptr->timer_mac_event = MAC_STATE_IDLE;
}
platform_exit_critical();
}
void timer_mac_interrupt(int timer_id, uint16_t slots)
{
(void)slots;
protocol_interface_rf_mac_setup_s *rf_mac_setup = get_sw_mac_ptr_by_timer(timer_id, ARM_NWK_MAC_TIMER);
if (rf_mac_setup) {
//SET State
rf_mac_setup->mac_tx_result = rf_mac_setup->timer_mac_event;
rf_mac_setup->timer_mac_event = MAC_STATE_IDLE;
mac_pd_sap_state_machine(rf_mac_setup);
}
}
|
734569.c | #include <std.h>
#include <daemons.h>
#include <magic.h>
inherit SPELL;
int modifier;
void create() {
::create();
set_author("nienne");
set_spell_name("umbral sight");
set_spell_level(([ "mage" : 2 ]));
set_spell_sphere("alteration");
set_syntax("cast CLASS umbral sight");
set_description("This spell will imbue the caster's vision with the stuff of darkness, allowing them to see easily "
"even in deep shadow. It will similarly protect their vision from extremes of light.");
set_verbal_comp();
set_somatic_comp();
set_helpful_spell(1);
set_feats_required(([ "mage" : "gift of the shadows"]));
}
string query_cast_string() {
tell_object(caster,"%^MAGENTA%^Passing a hand over your eyes, you draw upon the shadowweave to shroud your vision.%^RESET%^");
tell_room(place,"%^MAGENTA%^"+caster->QCN+" passes a hand over "+caster->QP+" eyes and focusses intently.%^RESET%^",caster);
return "display";
}
int preSpell() {
if(caster->query_property("darkvision")) {
tell_object(caster,"Your senses are already heightened.");
return 0;
}
return 1;
}
void spell_effect(int prof) {
int duration;
duration = (ROUND_LENGTH * 20) * (clevel + roll_dice(1, 20));
if(member_array((string)caster->query_race(),LIVING_D->night_races()) != -1) modifier = -10;
else modifier = 8;
tell_room(place,"%^MAGENTA%^"+caster->QCN+"'s pupils dilate, their blackness overwhelming all color in the irises.%^RESET%^",caster);
tell_object(caster,"%^MAGENTA%^The world around you drains of color and snaps into crystalline clarity.%^RESET%^");
addSpellToCaster();
spell_successful();
caster->add_sight_bonus(modifier);
caster->set_property("spelled",({TO}));
caster->set_property("darkvision",1);
}
void dest_effect() {
if(objectp(caster)) {
tell_object(caster,"%^MAGENTA%^You blink, and the color drains back into your vision as it loses its clarity.");
tell_room(environment(caster),"%^MAGENTA%^"+caster->QCN+" blinks, and suddenly "+caster->QP+" eyes look normal again.%^RESET%^",caster);
caster->add_sight_bonus(-1*modifier);
caster->remove_property("darkvision");
}
::dest_effect();
if(objectp(TO)) TO->remove();
}
|
355703.c | /*
Fontname: -FreeType-Koleeko-Medium-R-Normal--16-160-72-72-P-67-ISO10646-1
Copyright: geoff
Glyphs: 95/98
BBX Build Mode: 0
*/
const uint8_t u8g2_font_koleeko_tr[1134] U8G2_FONT_SECTION("u8g2_font_koleeko_tr") =
"_\0\3\3\4\4\1\4\5\14\16\377\375\11\375\12\377\1r\2\356\4Q \5\0\261\2!\7\223\221"
"\342\201f\42\11\65\335BB\221\244\0#\22\226\361F\22\222D\16\225P\344P\211\210\42\22\0$\21"
"\226\361F\22\222D\16\322\351!\42\11I\42\0%\16\230\61cD\11Yh\274\230\42\244\1&\22\232"
"q\213:\21N\244\324\32\211\62\23\315F\246\0'\7\63\235\342\20\1(\11\264\257J\242\244o\12)"
"\12\264\257B\246\244/J\0*\11E\327\42\222\62\232d+\12W\25k\70:\15G\0,\7D\257"
"f\305\2-\6\25\327\242\0.\6\63\221\342 /\16\246\361RM(\23\312\204\62\241\20\0\60\16\226"
"\361\206r\10Q,$\322!B\1\61\11\223\221*r\210\350\1\62\15\226\361\206b\224M(\263\331\241"
"\0\63\15\226\361\206b\224T\250\302C\204\2\64\16\227\21S\70#I\224$\207\333p\2\65\13\226\361"
"\342QX\25\36,\0\66\16\226\361jD\21\12+\42\322!B\1\67\11\227\21\343Q\343n\0\70\17"
"\226\361\206r\10\221$\24\21\351\20\241\0\71\16\226\361\206r\10\221$E\25\322\10\0:\10s\221\342"
" ;\10;\10t\261f\353\304\2<\10\227\21s\266\353\16=\10U\325\342\60=\14>\11\227\21c"
"\272\333\216\0\77\15\227\21\303r\270\221Hs\340\32\0@\30\253\217\353&\225\210F\24\25\212\12E\205"
"\242B\222\310\344\260C\4\0A\15\227\21\247r\70\214J\207\3\251\64B\16\227\21\303r\30\35\42\207"
"\321\341!\2C\16\227\21\247r\30\25\227\16\7I\5\0D\15\227\21\243d\71\214\232\16\17\21\0E"
"\13\227\21\343ah\261\14\17\17F\13\227\21\343ah\261\14\67\2G\15\227\21\247r\30N<\35$"
"\25\0H\13\227\21C\324tx\60\65\11I\13\225\321\342\60\31m\71\34\2J\12\226\361\246i\266\245"
"\205\4K\15\227\21c\324t\210\224,\242\246\1L\12\226\361b\266\333\341a\0M\21\231QG&\241"
"\34\36(\21K\304\22\261\331\6N\14\227\21cd\71\34(\246N\3O\15\227\21\247r\30u:\34"
"$\25\0P\16\227\21\243d\71\214J\207\210e\70\4Q\15\227\21\247r\30u\71H.\23\1R\16"
"\227\21\243d\71\214J\207\310AT\23S\15\227\21\247r\70L\253\207\7\11\0T\11\227\21\343\323p"
"O\0U\13\227\21c\324\247\303AR\1V\13\227\21c\324'Im\32\3W\25\233\221c$*\211"
"J\242\222\250$*\251\34d\223i,\6X\16\227\21cT:\210f\225\203\250i\0Y\14\227\21c"
"\324\351 \251\15\227\0Z\11\227\21\343\333\266\303\3[\11\205\321\342\20\332S\1\134\15\246\361B(\25"
"J\205R\241T(]\11\205\321\242\264\247C\0^\12H\36OJ\233Hf\2_\6'\15\343\1`"
"\6\63\235\302\42a\15\207\21\247r\225\34B\245\303\304\0b\16\247\21c\70\264\34F\235\16\207\10\0"
"c\13\207\21\247r\30n\274T\0d\14\247\21W\345p\20u:H\14e\14\207\21\247r\30\35\212"
"\303\213\1f\15\247\21\217T\31\316,\246\341\66\0g\17\267\13\347p\20\65\35\16\22\253\304R\1h"
"\13\247\21c\70\264\34F}\22i\10\223\221\302v\70\20j\13\305\313j\35\60\332\323e\4k\15\247"
"\21c\270\324r\220LLM\2l\7\223\221\342\203\1m\20\211Q\243\42\71\274H*\222\212\244\42\251"
"(n\12\207\21\247r\30\365I\0o\14\207\21\247r\30u:H*\0p\16\247\15\303r\30u:"
"\34\42\303!\0q\14\247\15\347p\20u:H\214\13r\12\207\21\247r\30\356\21\0s\15\207\21\347"
"p\220V\207\207\203\4\0t\14\245\321f\64\71LF\233H\3u\12\207\21c\324\247\203\244\2v\12"
"\207\21c\324'Im\4w\21\211QcX\221T$\25IERQ\271\225\0x\15\207\21cT:"
"\210f\225\203\250\64y\15\267\13C\324\247\303\304x\220\224\0z\11\207\21\343q\266\355p{\14\226\361"
"n\64\223\215\206C\341\2|\7\222q\342\201\0}\15\226\361b\70\24.\315d\243\31\0~\12G\25"
"GH\22\21%\0\0\0\0\4\377\377\0";
|
372045.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atrouill <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/02 09:36:14 by atrouill #+# #+# */
/* Updated: 2019/08/02 09:37:59 by atrouill ### ########.fr */
/* */
/* ************************************************************************** */
void ft_print_comb2(void);
int main()
{
ft_print_comb2();
}
|
132217.c | #include <stdio.h>
int main()
{
int p[10]= {12,16,24,2,18,20};
int a,b,c,d,e;
b=0; e=2;
for(c=1;c<=11;c=c+2)
{
b=b+p[c+1];
}
printf("%d",b);
d=(b+e)%2;
printf("\n%d",d);
return 0;
}
//o/p
//42
//0
|
115551.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__tanh_fp32_fp32)
// op(A') function: GB (_unop_tran__tanh_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = tanhf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = tanhf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = tanhf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_TANH || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__tanh_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = tanhf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = tanhf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__tanh_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
25385.c | #include <stdio.h>
main()
{
double x;
double e = 1.0;
int i;
int n = 20;
double term = 1.0;
scanf("%lf", &x);
for (i = 1; i <= n; i++) {
term *= (x / i);
e += term;
}
printf("%f\n", e);
return 0;
}
|
826143.c | /**
******************************************************************************
* @file stm32l0xx_ll_usart.c
* @author MCD Application Team
* @version V1.8.0
* @date 25-November-2016
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32l0xx_ll_usart.h"
#include "stm32l0xx_ll_rcc.h"
#include "stm32l0xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32L0xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART4) || defined (USART5)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 4000000U)
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
#if defined(USART1)
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1);
}
#endif /* USART1 */
#if defined(USART1)
else if (USARTx == USART2)
#else
if (USARTx == USART2)
#endif
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
#if defined(USART4)
else if (USARTx == USART4)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART4);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART4);
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART5);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART5);
}
#endif /* USART5 */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
#if (defined(USART4) || defined(USART5))
LL_RCC_ClocksTypeDef RCC_Clocks;
#endif
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration -----------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration -----------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration -----------------------
* Retrieve Clock frequency used for USART Peripheral
*/
#if defined(USART1)
if (USARTx == USART1)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
}
#endif /* USART1 */
#if defined(USART1)
else if (USARTx == USART2)
#else
if (USARTx == USART2)
#endif
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE);
}
#if defined(USART4)
else if (USARTx == USART4)
{
/* USART4 clock is PCLK1 */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* USART5 clock is PCLK1 */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART5 */
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
}
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR2 Configuration -----------------------*/
/* If Clock signal has to be output */
if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE)
{
/* Deactivate Clock signal delivery :
* - Disable Clock Output: USART_CR2_CLKEN cleared
*/
LL_USART_DisableSCLKOutput(USARTx);
}
else
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Enable Clock Output: USART_CR2_CLKEN set
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2 || USART4 || USART5 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
889901.c | /*
Copyright (C) The Weather Channel, Inc. 2002. All Rights Reserved.
The Weather Channel (TM) funded Tungsten Graphics to develop the
initial release of the Radeon 8500 driver under the XFree86 license.
This notice must be preserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice (including the
next paragraph) shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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.
**************************************************************************/
/*
* Authors:
* Keith Whitwell <[email protected]>
*/
#include <sched.h>
#include <errno.h>
#include "glheader.h"
#include "imports.h"
#include "macros.h"
#include "context.h"
#include "swrast/swrast.h"
#include "r200_context.h"
#include "r200_state.h"
#include "r200_ioctl.h"
#include "r200_tcl.h"
#include "r200_sanity.h"
#include "radeon_reg.h"
#include "drirenderbuffer.h"
#include "vblank.h"
#define R200_TIMEOUT 512
#define R200_IDLE_RETRY 16
static void r200WaitForIdle( r200ContextPtr rmesa );
/* At this point we were in FlushCmdBufLocked but we had lost our context, so
* we need to unwire our current cmdbuf, hook the one with the saved state in
* it, flush it, and then put the current one back. This is so commands at the
* start of a cmdbuf can rely on the state being kept from the previous one.
*/
static void r200BackUpAndEmitLostStateLocked( r200ContextPtr rmesa )
{
GLuint nr_released_bufs;
struct r200_store saved_store;
if (rmesa->backup_store.cmd_used == 0)
return;
if (R200_DEBUG & DEBUG_STATE)
fprintf(stderr, "Emitting backup state on lost context\n");
rmesa->lost_context = GL_FALSE;
nr_released_bufs = rmesa->dma.nr_released_bufs;
saved_store = rmesa->store;
rmesa->dma.nr_released_bufs = 0;
rmesa->store = rmesa->backup_store;
r200FlushCmdBufLocked( rmesa, __FUNCTION__ );
rmesa->dma.nr_released_bufs = nr_released_bufs;
rmesa->store = saved_store;
}
int r200FlushCmdBufLocked( r200ContextPtr rmesa, const char * caller )
{
int ret, i;
drm_radeon_cmd_buffer_t cmd;
if (rmesa->lost_context)
r200BackUpAndEmitLostStateLocked( rmesa );
if (R200_DEBUG & DEBUG_IOCTL) {
fprintf(stderr, "%s from %s\n", __FUNCTION__, caller);
if (0 & R200_DEBUG & DEBUG_VERBOSE)
for (i = 0 ; i < rmesa->store.cmd_used ; i += 4 )
fprintf(stderr, "%d: %x\n", i/4,
*(int *)(&rmesa->store.cmd_buf[i]));
}
if (R200_DEBUG & DEBUG_DMA)
fprintf(stderr, "%s: Releasing %d buffers\n", __FUNCTION__,
rmesa->dma.nr_released_bufs);
if (R200_DEBUG & DEBUG_SANITY) {
if (rmesa->state.scissor.enabled)
ret = r200SanityCmdBuffer( rmesa,
rmesa->state.scissor.numClipRects,
rmesa->state.scissor.pClipRects);
else
ret = r200SanityCmdBuffer( rmesa,
rmesa->numClipRects,
rmesa->pClipRects);
if (ret) {
fprintf(stderr, "drmSanityCommandWrite: %d\n", ret);
goto out;
}
}
if (R200_DEBUG & DEBUG_MEMORY) {
if (! driValidateTextureHeaps( rmesa->texture_heaps, rmesa->nr_heaps,
& rmesa->swapped ) ) {
fprintf( stderr, "%s: texture memory is inconsistent - expect "
"mangled textures\n", __FUNCTION__ );
}
}
cmd.bufsz = rmesa->store.cmd_used;
cmd.buf = rmesa->store.cmd_buf;
if (rmesa->state.scissor.enabled) {
cmd.nbox = rmesa->state.scissor.numClipRects;
cmd.boxes = (drm_clip_rect_t *)rmesa->state.scissor.pClipRects;
} else {
cmd.nbox = rmesa->numClipRects;
cmd.boxes = (drm_clip_rect_t *)rmesa->pClipRects;
}
ret = drmCommandWrite( rmesa->dri.fd,
DRM_RADEON_CMDBUF,
&cmd, sizeof(cmd) );
if (ret)
fprintf(stderr, "drmCommandWrite: %d\n", ret);
if (R200_DEBUG & DEBUG_SYNC) {
fprintf(stderr, "\nSyncing in %s\n\n", __FUNCTION__);
r200WaitForIdleLocked( rmesa );
}
out:
rmesa->store.primnr = 0;
rmesa->store.statenr = 0;
rmesa->store.cmd_used = 0;
rmesa->dma.nr_released_bufs = 0;
rmesa->save_on_next_emit = 1;
return ret;
}
/* Note: does not emit any commands to avoid recursion on
* r200AllocCmdBuf.
*/
void r200FlushCmdBuf( r200ContextPtr rmesa, const char *caller )
{
int ret;
LOCK_HARDWARE( rmesa );
ret = r200FlushCmdBufLocked( rmesa, caller );
UNLOCK_HARDWARE( rmesa );
if (ret) {
fprintf(stderr, "drmRadeonCmdBuffer: %d (exiting)\n", ret);
exit(ret);
}
}
/* =============================================================
* Hardware vertex buffer handling
*/
void r200RefillCurrentDmaRegion( r200ContextPtr rmesa )
{
struct r200_dma_buffer *dmabuf;
int fd = rmesa->dri.fd;
int index = 0;
int size = 0;
drmDMAReq dma;
int ret;
if (R200_DEBUG & (DEBUG_IOCTL|DEBUG_DMA))
fprintf(stderr, "%s\n", __FUNCTION__);
if (rmesa->dma.flush) {
rmesa->dma.flush( rmesa );
}
if (rmesa->dma.current.buf)
r200ReleaseDmaRegion( rmesa, &rmesa->dma.current, __FUNCTION__ );
if (rmesa->dma.nr_released_bufs > 4)
r200FlushCmdBuf( rmesa, __FUNCTION__ );
dma.context = rmesa->dri.hwContext;
dma.send_count = 0;
dma.send_list = NULL;
dma.send_sizes = NULL;
dma.flags = 0;
dma.request_count = 1;
dma.request_size = RADEON_BUFFER_SIZE;
dma.request_list = &index;
dma.request_sizes = &size;
dma.granted_count = 0;
LOCK_HARDWARE(rmesa); /* no need to validate */
while (1) {
ret = drmDMA( fd, &dma );
if (ret == 0)
break;
if (rmesa->dma.nr_released_bufs) {
r200FlushCmdBufLocked( rmesa, __FUNCTION__ );
}
if (rmesa->do_usleeps) {
UNLOCK_HARDWARE( rmesa );
DO_USLEEP( 1 );
LOCK_HARDWARE( rmesa );
}
}
UNLOCK_HARDWARE(rmesa);
if (R200_DEBUG & DEBUG_DMA)
fprintf(stderr, "Allocated buffer %d\n", index);
dmabuf = CALLOC_STRUCT( r200_dma_buffer );
dmabuf->buf = &rmesa->r200Screen->buffers->list[index];
dmabuf->refcount = 1;
rmesa->dma.current.buf = dmabuf;
rmesa->dma.current.address = dmabuf->buf->address;
rmesa->dma.current.end = dmabuf->buf->total;
rmesa->dma.current.start = 0;
rmesa->dma.current.ptr = 0;
}
void r200ReleaseDmaRegion( r200ContextPtr rmesa,
struct r200_dma_region *region,
const char *caller )
{
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "%s from %s\n", __FUNCTION__, caller);
if (!region->buf)
return;
if (rmesa->dma.flush)
rmesa->dma.flush( rmesa );
if (--region->buf->refcount == 0) {
drm_radeon_cmd_header_t *cmd;
if (R200_DEBUG & (DEBUG_IOCTL|DEBUG_DMA))
fprintf(stderr, "%s -- DISCARD BUF %d\n", __FUNCTION__,
region->buf->buf->idx);
cmd = (drm_radeon_cmd_header_t *)r200AllocCmdBuf( rmesa, sizeof(*cmd),
__FUNCTION__ );
cmd->dma.cmd_type = RADEON_CMD_DMA_DISCARD;
cmd->dma.buf_idx = region->buf->buf->idx;
FREE(region->buf);
rmesa->dma.nr_released_bufs++;
}
region->buf = NULL;
region->start = 0;
}
/* Allocates a region from rmesa->dma.current. If there isn't enough
* space in current, grab a new buffer (and discard what was left of current)
*/
void r200AllocDmaRegion( r200ContextPtr rmesa,
struct r200_dma_region *region,
int bytes,
int alignment )
{
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "%s %d\n", __FUNCTION__, bytes);
if (rmesa->dma.flush)
rmesa->dma.flush( rmesa );
if (region->buf)
r200ReleaseDmaRegion( rmesa, region, __FUNCTION__ );
alignment--;
rmesa->dma.current.start = rmesa->dma.current.ptr =
(rmesa->dma.current.ptr + alignment) & ~alignment;
if ( rmesa->dma.current.ptr + bytes > rmesa->dma.current.end )
r200RefillCurrentDmaRegion( rmesa );
region->start = rmesa->dma.current.start;
region->ptr = rmesa->dma.current.start;
region->end = rmesa->dma.current.start + bytes;
region->address = rmesa->dma.current.address;
region->buf = rmesa->dma.current.buf;
region->buf->refcount++;
rmesa->dma.current.ptr += bytes; /* bug - if alignment > 7 */
rmesa->dma.current.start =
rmesa->dma.current.ptr = (rmesa->dma.current.ptr + 0x7) & ~0x7;
assert( rmesa->dma.current.ptr <= rmesa->dma.current.end );
}
/* ================================================================
* SwapBuffers with client-side throttling
*/
static u_int32_t r200GetLastFrame(r200ContextPtr rmesa)
{
drm_radeon_getparam_t gp;
int ret;
u_int32_t frame;
gp.param = RADEON_PARAM_LAST_FRAME;
gp.value = (int *)&frame;
ret = drmCommandWriteRead( rmesa->dri.fd, DRM_RADEON_GETPARAM,
&gp, sizeof(gp) );
if ( ret ) {
fprintf( stderr, "%s: drmRadeonGetParam: %d\n", __FUNCTION__, ret );
exit(1);
}
return frame;
}
static void r200EmitIrqLocked( r200ContextPtr rmesa )
{
drm_radeon_irq_emit_t ie;
int ret;
ie.irq_seq = &rmesa->iw.irq_seq;
ret = drmCommandWriteRead( rmesa->dri.fd, DRM_RADEON_IRQ_EMIT,
&ie, sizeof(ie) );
if ( ret ) {
fprintf( stderr, "%s: drmRadeonIrqEmit: %d\n", __FUNCTION__, ret );
exit(1);
}
}
static void r200WaitIrq( r200ContextPtr rmesa )
{
int ret;
do {
ret = drmCommandWrite( rmesa->dri.fd, DRM_RADEON_IRQ_WAIT,
&rmesa->iw, sizeof(rmesa->iw) );
} while (ret && (errno == EINTR || errno == EBUSY));
if ( ret ) {
fprintf( stderr, "%s: drmRadeonIrqWait: %d\n", __FUNCTION__, ret );
exit(1);
}
}
static void r200WaitForFrameCompletion( r200ContextPtr rmesa )
{
drm_radeon_sarea_t *sarea = rmesa->sarea;
if (rmesa->do_irqs) {
if (r200GetLastFrame(rmesa) < sarea->last_frame) {
if (!rmesa->irqsEmitted) {
while (r200GetLastFrame (rmesa) < sarea->last_frame)
;
}
else {
UNLOCK_HARDWARE( rmesa );
r200WaitIrq( rmesa );
LOCK_HARDWARE( rmesa );
}
rmesa->irqsEmitted = 10;
}
if (rmesa->irqsEmitted) {
r200EmitIrqLocked( rmesa );
rmesa->irqsEmitted--;
}
}
else {
while (r200GetLastFrame (rmesa) < sarea->last_frame) {
UNLOCK_HARDWARE( rmesa );
if (rmesa->do_usleeps)
DO_USLEEP( 1 );
LOCK_HARDWARE( rmesa );
}
}
}
/* Copy the back color buffer to the front color buffer.
*/
void r200CopyBuffer( __DRIdrawablePrivate *dPriv,
const drm_clip_rect_t *rect)
{
r200ContextPtr rmesa;
GLint nbox, i, ret;
GLboolean missed_target;
int64_t ust;
__DRIscreenPrivate *psp = dPriv->driScreenPriv;
assert(dPriv);
assert(dPriv->driContextPriv);
assert(dPriv->driContextPriv->driverPrivate);
rmesa = (r200ContextPtr) dPriv->driContextPriv->driverPrivate;
if ( R200_DEBUG & DEBUG_IOCTL ) {
fprintf( stderr, "\n%s( %p )\n\n", __FUNCTION__, (void *)rmesa->glCtx );
}
R200_FIREVERTICES( rmesa );
LOCK_HARDWARE( rmesa );
/* Throttle the frame rate -- only allow one pending swap buffers
* request at a time.
*/
r200WaitForFrameCompletion( rmesa );
if (!rect)
{
UNLOCK_HARDWARE( rmesa );
driWaitForVBlank( dPriv, & missed_target );
LOCK_HARDWARE( rmesa );
}
nbox = dPriv->numClipRects; /* must be in locked region */
for ( i = 0 ; i < nbox ; ) {
GLint nr = MIN2( i + RADEON_NR_SAREA_CLIPRECTS , nbox );
drm_clip_rect_t *box = dPriv->pClipRects;
drm_clip_rect_t *b = rmesa->sarea->boxes;
GLint n = 0;
for ( ; i < nr ; i++ ) {
*b = box[i];
if (rect)
{
if (rect->x1 > b->x1)
b->x1 = rect->x1;
if (rect->y1 > b->y1)
b->y1 = rect->y1;
if (rect->x2 < b->x2)
b->x2 = rect->x2;
if (rect->y2 < b->y2)
b->y2 = rect->y2;
if (b->x1 >= b->x2 || b->y1 >= b->y2)
continue;
}
b++;
n++;
}
rmesa->sarea->nbox = n;
if (!n)
continue;
ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_SWAP );
if ( ret ) {
fprintf( stderr, "DRM_R200_SWAP_BUFFERS: return = %d\n", ret );
UNLOCK_HARDWARE( rmesa );
exit( 1 );
}
}
UNLOCK_HARDWARE( rmesa );
if (!rect)
{
rmesa->hw.all_dirty = GL_TRUE;
rmesa->swap_count++;
(*psp->systemTime->getUST)( & ust );
if ( missed_target ) {
rmesa->swap_missed_count++;
rmesa->swap_missed_ust = ust - rmesa->swap_ust;
}
rmesa->swap_ust = ust;
sched_yield();
}
}
void r200PageFlip( __DRIdrawablePrivate *dPriv )
{
r200ContextPtr rmesa;
GLint ret;
GLboolean missed_target;
__DRIscreenPrivate *psp = dPriv->driScreenPriv;
assert(dPriv);
assert(dPriv->driContextPriv);
assert(dPriv->driContextPriv->driverPrivate);
rmesa = (r200ContextPtr) dPriv->driContextPriv->driverPrivate;
if ( R200_DEBUG & DEBUG_IOCTL ) {
fprintf(stderr, "%s: pfCurrentPage: %d\n", __FUNCTION__,
rmesa->sarea->pfCurrentPage);
}
R200_FIREVERTICES( rmesa );
LOCK_HARDWARE( rmesa );
if (!dPriv->numClipRects) {
UNLOCK_HARDWARE( rmesa );
usleep( 10000 ); /* throttle invisible client 10ms */
return;
}
/* Need to do this for the perf box placement:
*/
{
drm_clip_rect_t *box = dPriv->pClipRects;
drm_clip_rect_t *b = rmesa->sarea->boxes;
b[0] = box[0];
rmesa->sarea->nbox = 1;
}
/* Throttle the frame rate -- only allow a few pending swap buffers
* request at a time.
*/
r200WaitForFrameCompletion( rmesa );
UNLOCK_HARDWARE( rmesa );
driWaitForVBlank( dPriv, & missed_target );
if ( missed_target ) {
rmesa->swap_missed_count++;
(void) (*psp->systemTime->getUST)( & rmesa->swap_missed_ust );
}
LOCK_HARDWARE( rmesa );
ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_FLIP );
UNLOCK_HARDWARE( rmesa );
if ( ret ) {
fprintf( stderr, "DRM_RADEON_FLIP: return = %d\n", ret );
exit( 1 );
}
rmesa->swap_count++;
(void) (*psp->systemTime->getUST)( & rmesa->swap_ust );
#if 000
if ( rmesa->sarea->pfCurrentPage == 1 ) {
rmesa->state.color.drawOffset = rmesa->r200Screen->frontOffset;
rmesa->state.color.drawPitch = rmesa->r200Screen->frontPitch;
} else {
rmesa->state.color.drawOffset = rmesa->r200Screen->backOffset;
rmesa->state.color.drawPitch = rmesa->r200Screen->backPitch;
}
R200_STATECHANGE( rmesa, ctx );
rmesa->hw.ctx.cmd[CTX_RB3D_COLOROFFSET] = rmesa->state.color.drawOffset
+ rmesa->r200Screen->fbLocation;
rmesa->hw.ctx.cmd[CTX_RB3D_COLORPITCH] = rmesa->state.color.drawPitch;
if (rmesa->sarea->tiling_enabled) {
rmesa->hw.ctx.cmd[CTX_RB3D_COLORPITCH] |= R200_COLOR_TILE_ENABLE;
}
#else
/* Get ready for drawing next frame. Update the renderbuffers'
* flippedOffset/Pitch fields so we draw into the right place.
*/
driFlipRenderbuffers(rmesa->glCtx->WinSysDrawBuffer,
rmesa->sarea->pfCurrentPage);
r200UpdateDrawBuffer(rmesa->glCtx);
#endif
}
/* ================================================================
* Buffer clear
*/
static void r200Clear( GLcontext *ctx, GLbitfield mask )
{
r200ContextPtr rmesa = R200_CONTEXT(ctx);
__DRIdrawablePrivate *dPriv = rmesa->dri.drawable;
GLuint flags = 0;
GLuint color_mask = 0;
GLint ret, i;
GLint cx, cy, cw, ch;
if ( R200_DEBUG & DEBUG_IOCTL ) {
fprintf( stderr, "r200Clear\n");
}
{
LOCK_HARDWARE( rmesa );
UNLOCK_HARDWARE( rmesa );
if ( dPriv->numClipRects == 0 )
return;
}
r200Flush( ctx );
if ( mask & BUFFER_BIT_FRONT_LEFT ) {
flags |= RADEON_FRONT;
color_mask = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
mask &= ~BUFFER_BIT_FRONT_LEFT;
}
if ( mask & BUFFER_BIT_BACK_LEFT ) {
flags |= RADEON_BACK;
color_mask = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
mask &= ~BUFFER_BIT_BACK_LEFT;
}
if ( mask & BUFFER_BIT_DEPTH ) {
flags |= RADEON_DEPTH;
mask &= ~BUFFER_BIT_DEPTH;
}
if ( (mask & BUFFER_BIT_STENCIL) && rmesa->state.stencil.hwBuffer ) {
flags |= RADEON_STENCIL;
mask &= ~BUFFER_BIT_STENCIL;
}
if ( mask ) {
if (R200_DEBUG & DEBUG_FALLBACKS)
fprintf(stderr, "%s: swrast clear, mask: %x\n", __FUNCTION__, mask);
_swrast_Clear( ctx, mask );
}
if ( !flags )
return;
if (rmesa->using_hyperz) {
flags |= RADEON_USE_COMP_ZBUF;
/* if (rmesa->r200Screen->chip_family == CHIP_FAMILY_R200)
flags |= RADEON_USE_HIERZ; */
if (!(rmesa->state.stencil.hwBuffer) ||
((flags & RADEON_DEPTH) && (flags & RADEON_STENCIL) &&
((rmesa->state.stencil.clear & R200_STENCIL_WRITE_MASK) == R200_STENCIL_WRITE_MASK))) {
flags |= RADEON_CLEAR_FASTZ;
}
}
LOCK_HARDWARE( rmesa );
/* compute region after locking: */
cx = ctx->DrawBuffer->_Xmin;
cy = ctx->DrawBuffer->_Ymin;
cw = ctx->DrawBuffer->_Xmax - cx;
ch = ctx->DrawBuffer->_Ymax - cy;
/* Flip top to bottom */
cx += dPriv->x;
cy = dPriv->y + dPriv->h - cy - ch;
/* Throttle the number of clear ioctls we do.
*/
while ( 1 ) {
drm_radeon_getparam_t gp;
int ret;
int clear;
gp.param = RADEON_PARAM_LAST_CLEAR;
gp.value = (int *)&clear;
ret = drmCommandWriteRead( rmesa->dri.fd,
DRM_RADEON_GETPARAM, &gp, sizeof(gp) );
if ( ret ) {
fprintf( stderr, "%s: drmRadeonGetParam: %d\n", __FUNCTION__, ret );
exit(1);
}
/* Clear throttling needs more thought.
*/
if ( rmesa->sarea->last_clear - clear <= 25 ) {
break;
}
if (rmesa->do_usleeps) {
UNLOCK_HARDWARE( rmesa );
DO_USLEEP( 1 );
LOCK_HARDWARE( rmesa );
}
}
/* Send current state to the hardware */
r200FlushCmdBufLocked( rmesa, __FUNCTION__ );
for ( i = 0 ; i < dPriv->numClipRects ; ) {
GLint nr = MIN2( i + RADEON_NR_SAREA_CLIPRECTS, dPriv->numClipRects );
drm_clip_rect_t *box = dPriv->pClipRects;
drm_clip_rect_t *b = rmesa->sarea->boxes;
drm_radeon_clear_t clear;
drm_radeon_clear_rect_t depth_boxes[RADEON_NR_SAREA_CLIPRECTS];
GLint n = 0;
if (cw != dPriv->w || ch != dPriv->h) {
/* clear subregion */
for ( ; i < nr ; i++ ) {
GLint x = box[i].x1;
GLint y = box[i].y1;
GLint w = box[i].x2 - x;
GLint h = box[i].y2 - y;
if ( x < cx ) w -= cx - x, x = cx;
if ( y < cy ) h -= cy - y, y = cy;
if ( x + w > cx + cw ) w = cx + cw - x;
if ( y + h > cy + ch ) h = cy + ch - y;
if ( w <= 0 ) continue;
if ( h <= 0 ) continue;
b->x1 = x;
b->y1 = y;
b->x2 = x + w;
b->y2 = y + h;
b++;
n++;
}
} else {
/* clear whole window */
for ( ; i < nr ; i++ ) {
*b++ = box[i];
n++;
}
}
rmesa->sarea->nbox = n;
clear.flags = flags;
clear.clear_color = rmesa->state.color.clear;
clear.clear_depth = rmesa->state.depth.clear; /* needed for hyperz */
clear.color_mask = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
clear.depth_mask = rmesa->state.stencil.clear;
clear.depth_boxes = depth_boxes;
n--;
b = rmesa->sarea->boxes;
for ( ; n >= 0 ; n-- ) {
depth_boxes[n].f[CLEAR_X1] = (float)b[n].x1;
depth_boxes[n].f[CLEAR_Y1] = (float)b[n].y1;
depth_boxes[n].f[CLEAR_X2] = (float)b[n].x2;
depth_boxes[n].f[CLEAR_Y2] = (float)b[n].y2;
depth_boxes[n].f[CLEAR_DEPTH] = ctx->Depth.Clear;
}
ret = drmCommandWrite( rmesa->dri.fd, DRM_RADEON_CLEAR,
&clear, sizeof(clear));
if ( ret ) {
UNLOCK_HARDWARE( rmesa );
fprintf( stderr, "DRM_RADEON_CLEAR: return = %d\n", ret );
exit( 1 );
}
}
UNLOCK_HARDWARE( rmesa );
rmesa->hw.all_dirty = GL_TRUE;
}
void r200WaitForIdleLocked( r200ContextPtr rmesa )
{
int ret;
int i = 0;
do {
ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_CP_IDLE);
if (ret)
DO_USLEEP( 1 );
} while (ret && ++i < 100);
if ( ret < 0 ) {
UNLOCK_HARDWARE( rmesa );
fprintf( stderr, "Error: R200 timed out... exiting\n" );
exit( -1 );
}
}
static void r200WaitForIdle( r200ContextPtr rmesa )
{
LOCK_HARDWARE(rmesa);
r200WaitForIdleLocked( rmesa );
UNLOCK_HARDWARE(rmesa);
}
void r200Flush( GLcontext *ctx )
{
r200ContextPtr rmesa = R200_CONTEXT( ctx );
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "%s\n", __FUNCTION__);
if (rmesa->dma.flush)
rmesa->dma.flush( rmesa );
r200EmitState( rmesa );
if (rmesa->store.cmd_used)
r200FlushCmdBuf( rmesa, __FUNCTION__ );
}
/* Make sure all commands have been sent to the hardware and have
* completed processing.
*/
void r200Finish( GLcontext *ctx )
{
r200ContextPtr rmesa = R200_CONTEXT(ctx);
r200Flush( ctx );
if (rmesa->do_irqs) {
LOCK_HARDWARE( rmesa );
r200EmitIrqLocked( rmesa );
UNLOCK_HARDWARE( rmesa );
r200WaitIrq( rmesa );
}
else
r200WaitForIdle( rmesa );
}
/* This version of AllocateMemoryMESA allocates only GART memory, and
* only does so after the point at which the driver has been
* initialized.
*
* Theoretically a valid context isn't required. However, in this
* implementation, it is, as I'm using the hardware lock to protect
* the kernel data structures, and the current context to get the
* device fd.
*/
void *r200AllocateMemoryMESA(__DRIscreen *screen, GLsizei size,
GLfloat readfreq, GLfloat writefreq,
GLfloat priority)
{
GET_CURRENT_CONTEXT(ctx);
r200ContextPtr rmesa;
int region_offset;
drm_radeon_mem_alloc_t alloc;
int ret;
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "%s sz %d %f/%f/%f\n", __FUNCTION__, size, readfreq,
writefreq, priority);
if (!ctx || !(rmesa = R200_CONTEXT(ctx)) || !rmesa->r200Screen->gartTextures.map)
return NULL;
if (getenv("R200_NO_ALLOC"))
return NULL;
alloc.region = RADEON_MEM_REGION_GART;
alloc.alignment = 0;
alloc.size = size;
alloc.region_offset = ®ion_offset;
ret = drmCommandWriteRead( rmesa->r200Screen->driScreen->fd,
DRM_RADEON_ALLOC,
&alloc, sizeof(alloc));
if (ret) {
fprintf(stderr, "%s: DRM_RADEON_ALLOC ret %d\n", __FUNCTION__, ret);
return NULL;
}
{
char *region_start = (char *)rmesa->r200Screen->gartTextures.map;
return (void *)(region_start + region_offset);
}
}
/* Called via glXFreeMemoryMESA() */
void r200FreeMemoryMESA(__DRIscreen *screen, GLvoid *pointer)
{
GET_CURRENT_CONTEXT(ctx);
r200ContextPtr rmesa;
ptrdiff_t region_offset;
drm_radeon_mem_free_t memfree;
int ret;
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "%s %p\n", __FUNCTION__, pointer);
if (!ctx || !(rmesa = R200_CONTEXT(ctx)) || !rmesa->r200Screen->gartTextures.map) {
fprintf(stderr, "%s: no context\n", __FUNCTION__);
return;
}
region_offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;
if (region_offset < 0 ||
region_offset > rmesa->r200Screen->gartTextures.size) {
fprintf(stderr, "offset %d outside range 0..%d\n", region_offset,
rmesa->r200Screen->gartTextures.size);
return;
}
memfree.region = RADEON_MEM_REGION_GART;
memfree.region_offset = region_offset;
ret = drmCommandWrite( rmesa->r200Screen->driScreen->fd,
DRM_RADEON_FREE,
&memfree, sizeof(memfree));
if (ret)
fprintf(stderr, "%s: DRM_RADEON_FREE ret %d\n", __FUNCTION__, ret);
}
/* Called via glXGetMemoryOffsetMESA() */
GLuint r200GetMemoryOffsetMESA(__DRIscreen *screen, const GLvoid *pointer)
{
GET_CURRENT_CONTEXT(ctx);
r200ContextPtr rmesa;
GLuint card_offset;
if (!ctx || !(rmesa = R200_CONTEXT(ctx)) ) {
fprintf(stderr, "%s: no context\n", __FUNCTION__);
return ~0;
}
if (!r200IsGartMemory( rmesa, pointer, 0 ))
return ~0;
card_offset = r200GartOffsetFromVirtual( rmesa, pointer );
return card_offset - rmesa->r200Screen->gart_base;
}
GLboolean r200IsGartMemory( r200ContextPtr rmesa, const GLvoid *pointer,
GLint size )
{
ptrdiff_t offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;
int valid = (size >= 0 &&
offset >= 0 &&
offset + size < rmesa->r200Screen->gartTextures.size);
if (R200_DEBUG & DEBUG_IOCTL)
fprintf(stderr, "r200IsGartMemory( %p ) : %d\n", pointer, valid );
return valid;
}
GLuint r200GartOffsetFromVirtual( r200ContextPtr rmesa, const GLvoid *pointer )
{
ptrdiff_t offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;
if (offset < 0 || offset > rmesa->r200Screen->gartTextures.size)
return ~0;
else
return rmesa->r200Screen->gart_texture_offset + offset;
}
void r200InitIoctlFuncs( struct dd_function_table *functions )
{
functions->Clear = r200Clear;
functions->Finish = r200Finish;
functions->Flush = r200Flush;
}
|
801605.c | /* Copyright (C) 1998-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1998.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <assert.h>
#include <errno.h>
#include <mntent.h>
#include <paths.h>
#include <stdbool.h>
#include <stdio_ext.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/statvfs.h>
#include "linux_fsinfo.h"
#include <kernel-features.h>
/* Special internal-only bit value. */
#define ST_VALID 0x0020
#ifndef STATFS
# define STATFS statfs
# define STATVFS statvfs
# define INTERNAL_STATVFS __internal_statvfs
# ifndef __ASSUME_STATFS_F_FLAGS
int
__statvfs_getflags (const char *name, int fstype, int fd)
{
struct stat64 st;
if ((fd < 0 ? stat64 (name, &st) : fstat64 (fd, &st)) < 0)
return 0;
const char *fsname = NULL;
const char *fsname2 = NULL;
const char *fsname3 = NULL;
/* Map the filesystem type we got from the statfs call to a string. */
switch (fstype)
{
case EXT2_SUPER_MAGIC:
fsname = "ext4";
fsname2 = "ext3";
fsname3 = "ext2";
break;
case DEVPTS_SUPER_MAGIC:
fsname= "devpts";
break;
case SHMFS_SUPER_MAGIC:
fsname = "tmpfs";
break;
case PROC_SUPER_MAGIC:
fsname = "proc";
break;
case USBDEVFS_SUPER_MAGIC:
fsname = "usbdevfs";
break;
case AUTOFS_SUPER_MAGIC:
fsname = "autofs";
break;
case NFS_SUPER_MAGIC:
fsname = "nfs";
break;
case SYSFS_MAGIC:
fsname = "sysfs";
break;
case REISERFS_SUPER_MAGIC:
fsname = "reiserfs";
break;
case XFS_SUPER_MAGIC:
fsname = "xfs";
break;
case JFS_SUPER_MAGIC:
fsname = "jfs";
break;
case HPFS_SUPER_MAGIC:
fsname = "hpfs";
break;
case DEVFS_SUPER_MAGIC:
fsname = "devfs";
break;
case ISOFS_SUPER_MAGIC:
fsname = "iso9660";
break;
case MSDOS_SUPER_MAGIC:
fsname = "msdos";
break;
case NTFS_SUPER_MAGIC:
fsname = "ntfs";
break;
case LOGFS_MAGIC_U32:
fsname = "logfs";
break;
case BTRFS_SUPER_MAGIC:
fsname = "btrfs";
break;
case CGROUP_SUPER_MAGIC:
fsname = "cgroup";
break;
case LUSTRE_SUPER_MAGIC:
fsname = "lustre";
break;
case F2FS_SUPER_MAGIC:
fsname = "f2fs";
break;
case EFIVARFS_MAGIC:
fsname = "efivarfs";
break;
}
FILE *mtab = __setmntent ("/proc/mounts", "r");
if (mtab == NULL)
mtab = __setmntent (_PATH_MOUNTED, "r");
int result = 0;
if (mtab != NULL)
{
bool success = false;
struct mntent mntbuf;
char tmpbuf[1024];
/* No locking needed. */
(void) __fsetlocking (mtab, FSETLOCKING_BYCALLER);
again:
while (__getmntent_r (mtab, &mntbuf, tmpbuf, sizeof (tmpbuf)))
{
/* In a first round we look for a given mount point, if
we have a name. */
if (name != NULL && strcmp (name, mntbuf.mnt_dir) != 0)
continue;
/* We need to look at the entry only if the filesystem
name matches. If we have a filesystem name. */
else if (fsname != NULL
&& strcmp (fsname, mntbuf.mnt_type) != 0
&& (fsname2 == NULL
|| strcmp (fsname2, mntbuf.mnt_type) != 0)
&& (fsname3 == NULL
|| strcmp (fsname3, mntbuf.mnt_type) != 0))
continue;
/* Find out about the device the current entry is for. */
struct stat64 fsst;
if (stat64 (mntbuf.mnt_dir, &fsst) >= 0
&& st.st_dev == fsst.st_dev)
{
/* Bingo, we found the entry for the device FD is on.
Now interpret the option string. */
char *cp = mntbuf.mnt_opts;
char *opt;
while ((opt = strsep (&cp, ",")) != NULL)
if (strcmp (opt, "ro") == 0)
result |= ST_RDONLY;
else if (strcmp (opt, "nosuid") == 0)
result |= ST_NOSUID;
else if (strcmp (opt, "noexec") == 0)
result |= ST_NOEXEC;
else if (strcmp (opt, "nodev") == 0)
result |= ST_NODEV;
else if (strcmp (opt, "sync") == 0)
result |= ST_SYNCHRONOUS;
else if (strcmp (opt, "mand") == 0)
result |= ST_MANDLOCK;
else if (strcmp (opt, "noatime") == 0)
result |= ST_NOATIME;
else if (strcmp (opt, "nodiratime") == 0)
result |= ST_NODIRATIME;
else if (strcmp (opt, "relatime") == 0)
result |= ST_RELATIME;
/* We can stop looking for more entries. */
success = true;
break;
}
}
/* Maybe the kernel names for the filesystems changed or the
statvfs call got a name which was not the mount point. Check
again, this time without checking for name matches first. */
if (! success && (name != NULL || fsname != NULL))
{
if (name != NULL)
/* Try without a mount point name. */
name = NULL;
else
{
/* Try without a filesystem name. */
assert (fsname != NULL);
fsname = fsname2 = fsname3 = NULL;
}
/* It is not strictly allowed to use rewind here. But
this code is part of the implementation so it is
acceptable. */
rewind (mtab);
goto again;
}
/* Close the file. */
__endmntent (mtab);
}
return result;
}
# endif
#else
extern int __statvfs_getflags (const char *name, int fstype, int fd);
#endif
void
INTERNAL_STATVFS (const char *name, struct STATVFS *buf,
struct STATFS *fsbuf, int fd)
{
/* Now fill in the fields we have information for. */
buf->f_bsize = fsbuf->f_bsize;
/* Linux has the f_frsize size only in later version of the kernel.
If the value is not filled in use f_bsize. */
buf->f_frsize = fsbuf->f_frsize ?: fsbuf->f_bsize;
buf->f_blocks = fsbuf->f_blocks;
buf->f_bfree = fsbuf->f_bfree;
buf->f_bavail = fsbuf->f_bavail;
buf->f_files = fsbuf->f_files;
buf->f_ffree = fsbuf->f_ffree;
if (sizeof (buf->f_fsid) == sizeof (fsbuf->f_fsid))
/* The shifting uses 'unsigned long long int' even though the target
field might only have 32 bits. This is OK since the 'if' branch
is not used in this case but the compiler would still generate
warnings. */
buf->f_fsid = ((fsbuf->f_fsid.__val[0]
& ((1ULL << (8 * sizeof (fsbuf->f_fsid.__val[0]))) - 1))
| ((unsigned long long int) fsbuf->f_fsid.__val[1]
<< (8 * (sizeof (buf->f_fsid)
- sizeof (fsbuf->f_fsid.__val[0])))));
else
/* We cannot help here. The statvfs element is not large enough to
contain both words of the statfs f_fsid field. */
buf->f_fsid = fsbuf->f_fsid.__val[0];
#ifdef _STATVFSBUF_F_UNUSED
buf->__f_unused = 0;
#endif
buf->f_namemax = fsbuf->f_namelen;
memset (buf->__f_spare, '\0', sizeof (buf->__f_spare));
/* What remains to do is to fill the fields f_favail and f_flag. */
/* XXX I have no idea how to compute f_favail. Any idea??? */
buf->f_favail = buf->f_ffree;
#ifndef __ASSUME_STATFS_F_FLAGS
if ((fsbuf->f_flags & ST_VALID) == 0)
/* Determining the flags is tricky. We have to read /proc/mounts or
the /etc/mtab file and search for the entry which matches the given
file. The way we can test for matching filesystem is using the
device number. */
buf->f_flag = __statvfs_getflags (name, fsbuf->f_type, fd);
else
#endif
buf->f_flag = fsbuf->f_flags ^ ST_VALID;
}
|
980974.c | #include "../headers.h"
#include "header_q5.h"
void * median(void * param)
{
struct q5_param * this = (struct q5_param *)param;
float *median = (float*)malloc(sizeof(float));
if(this-> len % 2)
{
*median = (this-> arr[this-> len / 2] + this-> arr[this-> len / 2])/ 2.00;
}
else
{
*median = this-> arr[this-> len / 2];
}
return median;
} |
392503.c | /*******************************************************************************
* File Name: cycfg_pins.c
*
* Description:
* Pin configuration
* This file was automatically generated and should not be modified.
* Tools Package 2.4.0.5721
* mtb-pdl-cat2 1.4.0.5338
* personalities 5.0.0.0
* udd 3.0.0.1428
*
********************************************************************************
* Copyright 2021 Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#include "cycfg_pins.h"
const cy_stc_gpio_pin_config_t CYBSP_CSD_SLD2_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_SLD2_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_SLD2_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_SLD2_PORT_NUM,
.channel_num = CYBSP_CSD_SLD2_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_SWDCK_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG,
.hsiom = CYBSP_SWDCK_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_SWDCK_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_SWDCK_PORT_NUM,
.channel_num = CYBSP_SWDCK_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_SWDIO_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG,
.hsiom = CYBSP_SWDIO_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_SWDIO_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_SWDIO_PORT_NUM,
.channel_num = CYBSP_SWDIO_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_SLD4_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_SLD4_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_SLD4_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_SLD4_PORT_NUM,
.channel_num = CYBSP_LED_SLD4_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_SLD1_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_SLD1_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_SLD1_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_SLD1_PORT_NUM,
.channel_num = CYBSP_LED_SLD1_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_SLD2_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_SLD2_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_SLD2_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_SLD2_PORT_NUM,
.channel_num = CYBSP_LED_SLD2_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_SLD3_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_SLD3_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_SLD3_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_SLD3_PORT_NUM,
.channel_num = CYBSP_LED_SLD3_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_BTN0_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_BTN0_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_BTN0_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_BTN0_PORT_NUM,
.channel_num = CYBSP_CSD_BTN0_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_BTN1_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_BTN1_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_BTN1_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_BTN1_PORT_NUM,
.channel_num = CYBSP_CSD_BTN1_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_BTN1_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_BTN1_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_BTN1_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_BTN1_PORT_NUM,
.channel_num = CYBSP_LED_BTN1_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_BTN0_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_BTN0_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_BTN0_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_BTN0_PORT_NUM,
.channel_num = CYBSP_LED_BTN0_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CMOD_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CMOD_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CMOD_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CMOD_PORT_NUM,
.channel_num = CYBSP_CMOD_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_LED_SLD0_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_STRONG_IN_OFF,
.hsiom = CYBSP_LED_SLD0_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_LED_SLD0_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_LED_SLD0_PORT_NUM,
.channel_num = CYBSP_LED_SLD0_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_SLD0_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_SLD0_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_SLD0_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_SLD0_PORT_NUM,
.channel_num = CYBSP_CSD_SLD0_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_SLD1_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_SLD1_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_SLD1_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_SLD1_PORT_NUM,
.channel_num = CYBSP_CSD_SLD1_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_SLD3_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_SLD3_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_SLD3_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_SLD3_PORT_NUM,
.channel_num = CYBSP_CSD_SLD3_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_CSD_SLD4_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_CSD_SLD4_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_CSD_SLD4_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_CSD_SLD4_PORT_NUM,
.channel_num = CYBSP_CSD_SLD4_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_USB_DP_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_USB_DP_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_USB_DP_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_USB_DP_PORT_NUM,
.channel_num = CYBSP_USB_DP_PIN,
};
#endif //defined (CY_USING_HAL)
const cy_stc_gpio_pin_config_t CYBSP_USB_DM_config =
{
.outVal = 1,
.driveMode = CY_GPIO_DM_ANALOG,
.hsiom = CYBSP_USB_DM_HSIOM,
.intEdge = CY_GPIO_INTR_DISABLE,
.vtrip = CY_GPIO_VTRIP_CMOS,
.slewRate = CY_GPIO_SLEW_FAST,
.vregEn = 0UL,
.ibufMode = 0UL,
.vtripSel = 0UL,
.vrefSel = 0UL,
.vohSel = 0UL,
};
#if defined (CY_USING_HAL)
const cyhal_resource_inst_t CYBSP_USB_DM_obj =
{
.type = CYHAL_RSC_GPIO,
.block_num = CYBSP_USB_DM_PORT_NUM,
.channel_num = CYBSP_USB_DM_PIN,
};
#endif //defined (CY_USING_HAL)
void init_cycfg_pins(void)
{
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_SLD2_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_SWDCK_PORT, CYBSP_SWDCK_PIN, &CYBSP_SWDCK_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_SWDCK_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_SWDIO_PORT, CYBSP_SWDIO_PIN, &CYBSP_SWDIO_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_SWDIO_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_SLD4_PORT, CYBSP_LED_SLD4_PIN, &CYBSP_LED_SLD4_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_SLD4_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_SLD1_PORT, CYBSP_LED_SLD1_PIN, &CYBSP_LED_SLD1_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_SLD1_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_SLD2_PORT, CYBSP_LED_SLD2_PIN, &CYBSP_LED_SLD2_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_SLD2_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_SLD3_PORT, CYBSP_LED_SLD3_PIN, &CYBSP_LED_SLD3_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_SLD3_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_BTN0_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_BTN1_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_BTN1_PORT, CYBSP_LED_BTN1_PIN, &CYBSP_LED_BTN1_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_BTN1_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_BTN0_PORT, CYBSP_LED_BTN0_PIN, &CYBSP_LED_BTN0_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_BTN0_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CMOD_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_LED_SLD0_PORT, CYBSP_LED_SLD0_PIN, &CYBSP_LED_SLD0_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_LED_SLD0_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_SLD0_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_SLD1_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_SLD3_obj);
#endif //defined (CY_USING_HAL)
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_CSD_SLD4_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_USB_DP_PORT, CYBSP_USB_DP_PIN, &CYBSP_USB_DP_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_USB_DP_obj);
#endif //defined (CY_USING_HAL)
Cy_GPIO_Pin_Init(CYBSP_USB_DM_PORT, CYBSP_USB_DM_PIN, &CYBSP_USB_DM_config);
#if defined (CY_USING_HAL)
cyhal_hwmgr_reserve(&CYBSP_USB_DM_obj);
#endif //defined (CY_USING_HAL)
}
|
908670.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
printf("%d \n",abs(-889)); // compute the absolute value of an integer
printf("%d \n",log(89)); //natural logarithmic function
printf("%f \n",pow(3,4)); //power functions
printf("%f \n",floor(3,4)); //largest integral value not greater than argument
return 0;
}
|
672818.c | /*
* PMC-Sierra SPC 8001 SAS/SATA based host adapters driver
*
* Copyright (c) 2008-2009 USI Co., Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*
*/
#include <linux/firmware.h>
#include <linux/slab.h>
#include "pm8001_sas.h"
#include "pm8001_ctl.h"
/* scsi host attributes */
/**
* pm8001_ctl_mpi_interface_rev_show - MPI interface revision number
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_mpi_interface_rev_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%d\n",
pm8001_ha->main_cfg_tbl.interface_rev);
}
static
DEVICE_ATTR(interface_rev, S_IRUGO, pm8001_ctl_mpi_interface_rev_show, NULL);
/**
* pm8001_ctl_fw_version_show - firmware version
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_fw_version_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%02x.%02x.%02x.%02x\n",
(u8)(pm8001_ha->main_cfg_tbl.firmware_rev >> 24),
(u8)(pm8001_ha->main_cfg_tbl.firmware_rev >> 16),
(u8)(pm8001_ha->main_cfg_tbl.firmware_rev >> 8),
(u8)(pm8001_ha->main_cfg_tbl.firmware_rev));
}
static DEVICE_ATTR(fw_version, S_IRUGO, pm8001_ctl_fw_version_show, NULL);
/**
* pm8001_ctl_max_out_io_show - max outstanding io supported
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_max_out_io_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%d\n",
pm8001_ha->main_cfg_tbl.max_out_io);
}
static DEVICE_ATTR(max_out_io, S_IRUGO, pm8001_ctl_max_out_io_show, NULL);
/**
* pm8001_ctl_max_devices_show - max devices support
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_max_devices_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%04d\n",
(u16)(pm8001_ha->main_cfg_tbl.max_sgl >> 16));
}
static DEVICE_ATTR(max_devices, S_IRUGO, pm8001_ctl_max_devices_show, NULL);
/**
* pm8001_ctl_max_sg_list_show - max sg list supported iff not 0.0 for no
* hardware limitation
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_max_sg_list_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%04d\n",
pm8001_ha->main_cfg_tbl.max_sgl & 0x0000FFFF);
}
static DEVICE_ATTR(max_sg_list, S_IRUGO, pm8001_ctl_max_sg_list_show, NULL);
#define SAS_1_0 0x1
#define SAS_1_1 0x2
#define SAS_2_0 0x4
static ssize_t
show_sas_spec_support_status(unsigned int mode, char *buf)
{
ssize_t len = 0;
if (mode & SAS_1_1)
len = sprintf(buf, "%s", "SAS1.1");
if (mode & SAS_2_0)
len += sprintf(buf + len, "%s%s", len ? ", " : "", "SAS2.0");
len += sprintf(buf + len, "\n");
return len;
}
/**
* pm8001_ctl_sas_spec_support_show - sas spec supported
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_sas_spec_support_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
unsigned int mode;
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
mode = (pm8001_ha->main_cfg_tbl.ctrl_cap_flag & 0xfe000000)>>25;
return show_sas_spec_support_status(mode, buf);
}
static DEVICE_ATTR(sas_spec_support, S_IRUGO,
pm8001_ctl_sas_spec_support_show, NULL);
/**
* pm8001_ctl_sas_address_show - sas address
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* This is the controller sas address
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_host_sas_address_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "0x%016llx\n",
be64_to_cpu(*(__be64 *)pm8001_ha->sas_addr));
}
static DEVICE_ATTR(host_sas_address, S_IRUGO,
pm8001_ctl_host_sas_address_show, NULL);
/**
* pm8001_ctl_logging_level_show - logging level
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read/write' shost attribute.
*/
static ssize_t pm8001_ctl_logging_level_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
return snprintf(buf, PAGE_SIZE, "%08xh\n", pm8001_ha->logging_level);
}
static ssize_t pm8001_ctl_logging_level_store(struct device *cdev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
int val = 0;
if (sscanf(buf, "%x", &val) != 1)
return -EINVAL;
pm8001_ha->logging_level = val;
return strlen(buf);
}
static DEVICE_ATTR(logging_level, S_IRUGO | S_IWUSR,
pm8001_ctl_logging_level_show, pm8001_ctl_logging_level_store);
/**
* pm8001_ctl_aap_log_show - aap1 event log
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_aap_log_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
int i;
#define AAP1_MEMMAP(r, c) \
(*(u32 *)((u8*)pm8001_ha->memoryMap.region[AAP1].virt_ptr + (r) * 32 \
+ (c)))
char *str = buf;
int max = 2;
for (i = 0; i < max; i++) {
str += sprintf(str, "0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x"
"0x%08x 0x%08x\n",
AAP1_MEMMAP(i, 0),
AAP1_MEMMAP(i, 4),
AAP1_MEMMAP(i, 8),
AAP1_MEMMAP(i, 12),
AAP1_MEMMAP(i, 16),
AAP1_MEMMAP(i, 20),
AAP1_MEMMAP(i, 24),
AAP1_MEMMAP(i, 28));
}
return str - buf;
}
static DEVICE_ATTR(aap_log, S_IRUGO, pm8001_ctl_aap_log_show, NULL);
/**
* pm8001_ctl_aap_log_show - IOP event log
* @cdev: pointer to embedded class device
* @buf: the buffer returned
*
* A sysfs 'read-only' shost attribute.
*/
static ssize_t pm8001_ctl_iop_log_show(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
#define IOP_MEMMAP(r, c) \
(*(u32 *)((u8*)pm8001_ha->memoryMap.region[IOP].virt_ptr + (r) * 32 \
+ (c)))
int i;
char *str = buf;
int max = 2;
for (i = 0; i < max; i++) {
str += sprintf(str, "0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x"
"0x%08x 0x%08x\n",
IOP_MEMMAP(i, 0),
IOP_MEMMAP(i, 4),
IOP_MEMMAP(i, 8),
IOP_MEMMAP(i, 12),
IOP_MEMMAP(i, 16),
IOP_MEMMAP(i, 20),
IOP_MEMMAP(i, 24),
IOP_MEMMAP(i, 28));
}
return str - buf;
}
static DEVICE_ATTR(iop_log, S_IRUGO, pm8001_ctl_iop_log_show, NULL);
#define FLASH_CMD_NONE 0x00
#define FLASH_CMD_UPDATE 0x01
#define FLASH_CMD_SET_NVMD 0x02
struct flash_command {
u8 command[8];
int code;
};
static struct flash_command flash_command_table[] =
{
{"set_nvmd", FLASH_CMD_SET_NVMD},
{"update", FLASH_CMD_UPDATE},
{"", FLASH_CMD_NONE} /* Last entry should be NULL. */
};
struct error_fw {
char *reason;
int err_code;
};
static struct error_fw flash_error_table[] =
{
{"Failed to open fw image file", FAIL_OPEN_BIOS_FILE},
{"image header mismatch", FLASH_UPDATE_HDR_ERR},
{"image offset mismatch", FLASH_UPDATE_OFFSET_ERR},
{"image CRC Error", FLASH_UPDATE_CRC_ERR},
{"image length Error.", FLASH_UPDATE_LENGTH_ERR},
{"Failed to program flash chip", FLASH_UPDATE_HW_ERR},
{"Flash chip not supported.", FLASH_UPDATE_DNLD_NOT_SUPPORTED},
{"Flash update disabled.", FLASH_UPDATE_DISABLED},
{"Flash in progress", FLASH_IN_PROGRESS},
{"Image file size Error", FAIL_FILE_SIZE},
{"Input parameter error", FAIL_PARAMETERS},
{"Out of memory", FAIL_OUT_MEMORY},
{"OK", 0} /* Last entry err_code = 0. */
};
static int pm8001_set_nvmd(struct pm8001_hba_info *pm8001_ha)
{
struct pm8001_ioctl_payload *payload;
DECLARE_COMPLETION_ONSTACK(completion);
u8 *ioctlbuffer = NULL;
u32 length = 0;
u32 ret = 0;
length = 1024 * 5 + sizeof(*payload) - 1;
ioctlbuffer = kzalloc(length, GFP_KERNEL);
if (!ioctlbuffer)
return -ENOMEM;
if ((pm8001_ha->fw_image->size <= 0) ||
(pm8001_ha->fw_image->size > 4096)) {
ret = FAIL_FILE_SIZE;
goto out;
}
payload = (struct pm8001_ioctl_payload *)ioctlbuffer;
memcpy((u8 *)payload->func_specific, (u8 *)pm8001_ha->fw_image->data,
pm8001_ha->fw_image->size);
payload->length = pm8001_ha->fw_image->size;
payload->id = 0;
pm8001_ha->nvmd_completion = &completion;
ret = PM8001_CHIP_DISP->set_nvmd_req(pm8001_ha, payload);
wait_for_completion(&completion);
out:
kfree(ioctlbuffer);
return ret;
}
static int pm8001_update_flash(struct pm8001_hba_info *pm8001_ha)
{
struct pm8001_ioctl_payload *payload;
DECLARE_COMPLETION_ONSTACK(completion);
u8 *ioctlbuffer = NULL;
u32 length = 0;
struct fw_control_info *fwControl;
u32 loopNumber, loopcount = 0;
u32 sizeRead = 0;
u32 partitionSize, partitionSizeTmp;
u32 ret = 0;
u32 partitionNumber = 0;
struct pm8001_fw_image_header *image_hdr;
length = 1024 * 16 + sizeof(*payload) - 1;
ioctlbuffer = kzalloc(length, GFP_KERNEL);
image_hdr = (struct pm8001_fw_image_header *)pm8001_ha->fw_image->data;
if (!ioctlbuffer)
return -ENOMEM;
if (pm8001_ha->fw_image->size < 28) {
ret = FAIL_FILE_SIZE;
goto out;
}
while (sizeRead < pm8001_ha->fw_image->size) {
partitionSizeTmp =
*(u32 *)((u8 *)&image_hdr->image_length + sizeRead);
partitionSize = be32_to_cpu(partitionSizeTmp);
loopcount = (partitionSize + HEADER_LEN)/IOCTL_BUF_SIZE;
if (loopcount % IOCTL_BUF_SIZE)
loopcount++;
if (loopcount == 0)
loopcount++;
for (loopNumber = 0; loopNumber < loopcount; loopNumber++) {
payload = (struct pm8001_ioctl_payload *)ioctlbuffer;
payload->length = 1024*16;
payload->id = 0;
fwControl =
(struct fw_control_info *)payload->func_specific;
fwControl->len = IOCTL_BUF_SIZE; /* IN */
fwControl->size = partitionSize + HEADER_LEN;/* IN */
fwControl->retcode = 0;/* OUT */
fwControl->offset = loopNumber * IOCTL_BUF_SIZE;/*OUT */
/* for the last chunk of data in case file size is not even with
4k, load only the rest*/
if (((loopcount-loopNumber) == 1) &&
((partitionSize + HEADER_LEN) % IOCTL_BUF_SIZE)) {
fwControl->len =
(partitionSize + HEADER_LEN) % IOCTL_BUF_SIZE;
memcpy((u8 *)fwControl->buffer,
(u8 *)pm8001_ha->fw_image->data + sizeRead,
(partitionSize + HEADER_LEN) % IOCTL_BUF_SIZE);
sizeRead +=
(partitionSize + HEADER_LEN) % IOCTL_BUF_SIZE;
} else {
memcpy((u8 *)fwControl->buffer,
(u8 *)pm8001_ha->fw_image->data + sizeRead,
IOCTL_BUF_SIZE);
sizeRead += IOCTL_BUF_SIZE;
}
pm8001_ha->nvmd_completion = &completion;
ret = PM8001_CHIP_DISP->fw_flash_update_req(pm8001_ha, payload);
wait_for_completion(&completion);
if (ret || (fwControl->retcode > FLASH_UPDATE_IN_PROGRESS)) {
ret = fwControl->retcode;
kfree(ioctlbuffer);
ioctlbuffer = NULL;
break;
}
}
if (ret)
break;
partitionNumber++;
}
out:
kfree(ioctlbuffer);
return ret;
}
static ssize_t pm8001_store_update_fw(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
char *cmd_ptr, *filename_ptr;
int res, i;
int flash_command = FLASH_CMD_NONE;
int err = 0;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
cmd_ptr = kzalloc(count*2, GFP_KERNEL);
if (!cmd_ptr) {
err = FAIL_OUT_MEMORY;
goto out;
}
filename_ptr = cmd_ptr + count;
res = sscanf(buf, "%s %s", cmd_ptr, filename_ptr);
if (res != 2) {
err = FAIL_PARAMETERS;
goto out1;
}
for (i = 0; flash_command_table[i].code != FLASH_CMD_NONE; i++) {
if (!memcmp(flash_command_table[i].command,
cmd_ptr, strlen(cmd_ptr))) {
flash_command = flash_command_table[i].code;
break;
}
}
if (flash_command == FLASH_CMD_NONE) {
err = FAIL_PARAMETERS;
goto out1;
}
if (pm8001_ha->fw_status == FLASH_IN_PROGRESS) {
err = FLASH_IN_PROGRESS;
goto out1;
}
err = request_firmware(&pm8001_ha->fw_image,
filename_ptr,
pm8001_ha->dev);
if (err) {
PM8001_FAIL_DBG(pm8001_ha,
pm8001_printk("Failed to load firmware image file %s,"
" error %d\n", filename_ptr, err));
err = FAIL_OPEN_BIOS_FILE;
goto out1;
}
switch (flash_command) {
case FLASH_CMD_UPDATE:
pm8001_ha->fw_status = FLASH_IN_PROGRESS;
err = pm8001_update_flash(pm8001_ha);
break;
case FLASH_CMD_SET_NVMD:
pm8001_ha->fw_status = FLASH_IN_PROGRESS;
err = pm8001_set_nvmd(pm8001_ha);
break;
default:
pm8001_ha->fw_status = FAIL_PARAMETERS;
err = FAIL_PARAMETERS;
break;
}
release_firmware(pm8001_ha->fw_image);
out1:
kfree(cmd_ptr);
out:
pm8001_ha->fw_status = err;
if (!err)
return count;
else
return -err;
}
static ssize_t pm8001_show_update_fw(struct device *cdev,
struct device_attribute *attr, char *buf)
{
int i;
struct Scsi_Host *shost = class_to_shost(cdev);
struct sas_ha_struct *sha = SHOST_TO_SAS_HA(shost);
struct pm8001_hba_info *pm8001_ha = sha->lldd_ha;
for (i = 0; flash_error_table[i].err_code != 0; i++) {
if (flash_error_table[i].err_code == pm8001_ha->fw_status)
break;
}
if (pm8001_ha->fw_status != FLASH_IN_PROGRESS)
pm8001_ha->fw_status = FLASH_OK;
return snprintf(buf, PAGE_SIZE, "status=%x %s\n",
flash_error_table[i].err_code,
flash_error_table[i].reason);
}
static DEVICE_ATTR(update_fw, S_IRUGO|S_IWUGO,
pm8001_show_update_fw, pm8001_store_update_fw);
struct device_attribute *pm8001_host_attrs[] = {
&dev_attr_interface_rev,
&dev_attr_fw_version,
&dev_attr_update_fw,
&dev_attr_aap_log,
&dev_attr_iop_log,
&dev_attr_max_out_io,
&dev_attr_max_devices,
&dev_attr_max_sg_list,
&dev_attr_sas_spec_support,
&dev_attr_logging_level,
&dev_attr_host_sas_address,
NULL,
};
|
838387.c | /*
** print_help.c for in /home/trambe_m/CPE_2014_corewar/bonus/asmdsm/src
**
** Made by Manuel Trambert
** Login <[email protected]>
**
** Started on Sun Apr 12 17:22:48 2015 Manuel Trambert
** Last update Sun Apr 12 17:26:42 2015 Manuel Trambert
*/
#include <stdlib.h>
#include "string_error.h"
#include "my.h"
void print_cmd_help(int i)
{
my_putstr("to the command: ", 1);
my_putstr(g_string_param_err[i][0], 1);
my_putstr("\n\tit take as first argument: ", 1);
my_putstr(g_string_param_err[i][1], 1);
if (g_string_param_err[i][2] != NULL)
{
my_putstr("\n\tit take as second argument: ", 1);
my_putstr(g_string_param_err[i][2], 1);
}
if (g_string_param_err[i][3] != NULL)
{
my_putstr("\n\tit take as third argument: ", 1);
my_putstr(g_string_param_err[i][3], 1);
}
if (g_string_param_err[i][4] != NULL)
{
my_putstr("\n\tit take as fourth argument: ", 1);
my_putstr(g_string_param_err[i][4], 1);
}
my_putchar('\n', 1);
}
void print_every_help()
{
int i;
i = 0;
while (g_string_param_err[i][0] != NULL)
{
print_cmd_help(i);
i += 1;
}
}
void print_help(char *str)
{
int i;
i = 0;
while (g_string_param_err[i][0] != NULL
&& my_strcmp(g_string_param_err[i][0], str) == 0)
i += 1;
if (g_string_param_err[i][0] == NULL)
print_every_help();
else
print_cmd_help(i);
}
|
94903.c | /*
* Copyright (c) 2018 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ztest.h>
#include <irq_offload.h>
#include <ksched.h>
#include <misc/__assert.h>
#include <misc/util.h>
/*
* @file
* @brief Test fifo APIs timeout
*
* This module tests following fifo timeout scenarios
*
* First, the thread waits with a timeout and times out. Then it wait with a
* timeout, but gets the data in time.
*
* Then, multiple timeout tests are done for the threads, to test the ordering
* of queueing/dequeueing when timeout occurs, first on one fifo, then on
* multiple fifos.
*
* Finally, multiple threads pend on one fifo, and they all get the
* data in time, except the last one: this tests that the timeout is
* recomputed correctly when timeouts are aborted.
*/
struct scratch_fifo_packet {
void *link_in_fifo;
void *data_if_needed;
};
struct reply_packet {
void *link_in_fifo;
s32_t reply;
};
struct timeout_order_data {
void *link_in_fifo;
struct k_fifo *fifo;
u32_t timeout;
s32_t timeout_order;
s32_t q_order;
};
#define NUM_SCRATCH_FIFO_PACKETS 20
struct scratch_fifo_packet scratch_fifo_packets[NUM_SCRATCH_FIFO_PACKETS];
struct k_fifo scratch_fifo_packets_fifo;
static struct k_fifo fifo_timeout[2];
struct k_fifo timeout_order_fifo;
struct timeout_order_data timeout_order_data[] = {
{0, &fifo_timeout[0], 20, 2, 0},
{0, &fifo_timeout[0], 40, 4, 1},
{0, &fifo_timeout[0], 0, 0, 2},
{0, &fifo_timeout[0], 10, 1, 3},
{0, &fifo_timeout[0], 30, 3, 4},
};
struct timeout_order_data timeout_order_data_mult_fifo[] = {
{0, &fifo_timeout[1], 0, 0, 0},
{0, &fifo_timeout[0], 30, 3, 1},
{0, &fifo_timeout[0], 50, 5, 2},
{0, &fifo_timeout[1], 80, 8, 3},
{0, &fifo_timeout[1], 70, 7, 4},
{0, &fifo_timeout[0], 10, 1, 5},
{0, &fifo_timeout[0], 60, 6, 6},
{0, &fifo_timeout[0], 20, 2, 7},
{0, &fifo_timeout[1], 40, 4, 8},
};
#define TIMEOUT_ORDER_NUM_THREADS ARRAY_SIZE(timeout_order_data_mult_fifo)
#define TSTACK_SIZE 1024
#define FIFO_THREAD_PRIO -5
static K_THREAD_STACK_ARRAY_DEFINE(ttstack,
TIMEOUT_ORDER_NUM_THREADS, TSTACK_SIZE);
static struct k_thread ttdata[TIMEOUT_ORDER_NUM_THREADS];
static k_tid_t tid[TIMEOUT_ORDER_NUM_THREADS];
static void *get_scratch_packet(void)
{
void *packet = k_fifo_get(&scratch_fifo_packets_fifo, K_NO_WAIT);
zassert_true(packet != NULL, NULL);
return packet;
}
static void put_scratch_packet(void *packet)
{
k_fifo_put(&scratch_fifo_packets_fifo, packet);
}
static bool is_timeout_in_range(u32_t start_time, u32_t timeout)
{
u32_t stop_time, diff;
stop_time = k_cycle_get_32();
diff = SYS_CLOCK_HW_CYCLES_TO_NS(stop_time -
start_time) / NSEC_PER_USEC;
diff = diff / USEC_PER_MSEC;
return timeout <= diff;
}
/* a thread sleeps then puts data on the fifo */
static void test_thread_put_timeout(void *p1, void *p2, void *p3)
{
u32_t timeout = *((u32_t *)p2);
k_sleep(timeout);
k_fifo_put((struct k_fifo *)p1, get_scratch_packet());
}
/* a thread pends on a fifo then times out */
static void test_thread_pend_and_timeout(void *p1, void *p2, void *p3)
{
struct timeout_order_data *d = (struct timeout_order_data *)p1;
u32_t start_time;
void *packet;
start_time = k_cycle_get_32();
packet = k_fifo_get(d->fifo, d->timeout);
zassert_true(packet == NULL, NULL);
zassert_true(is_timeout_in_range(start_time, d->timeout), NULL);
k_fifo_put(&timeout_order_fifo, d);
}
/* Spins several threads that pend and timeout on fifos */
static int test_multiple_threads_pending(struct timeout_order_data *test_data,
int test_data_size)
{
int ii;
for (ii = 0; ii < test_data_size; ii++) {
tid[ii] = k_thread_create(&ttdata[ii], ttstack[ii], TSTACK_SIZE,
test_thread_pend_and_timeout,
&test_data[ii], NULL, NULL,
FIFO_THREAD_PRIO, K_INHERIT_PERMS, 0);
}
for (ii = 0; ii < test_data_size; ii++) {
struct timeout_order_data *data =
k_fifo_get(&timeout_order_fifo, K_FOREVER);
if (data->timeout_order == ii) {
TC_PRINT(" thread (q order: %d, t/o: %d, fifo %p)\n",
data->q_order, data->timeout, data->fifo);
} else {
TC_ERROR(" *** thread %d woke up, expected %d\n",
data->timeout_order, ii);
return TC_FAIL;
}
}
return TC_PASS;
}
/* a thread pends on a fifo with a timeout and gets the data in time */
static void test_thread_pend_and_get_data(void *p1, void *p2, void *p3)
{
struct timeout_order_data *d = (struct timeout_order_data *)p1;
void *packet;
packet = k_fifo_get(d->fifo, d->timeout);
zassert_true(packet != NULL, NULL);
put_scratch_packet(packet);
k_fifo_put(&timeout_order_fifo, d);
}
/* Spins child threads that get fifo data in time, except the last one */
static int test_multiple_threads_get_data(struct timeout_order_data *test_data,
int test_data_size)
{
struct timeout_order_data *data;
int ii;
for (ii = 0; ii < test_data_size-1; ii++) {
tid[ii] = k_thread_create(&ttdata[ii], ttstack[ii], TSTACK_SIZE,
test_thread_pend_and_get_data,
&test_data[ii], NULL, NULL,
K_PRIO_PREEMPT(0), K_INHERIT_PERMS, 0);
}
tid[ii] = k_thread_create(&ttdata[ii], ttstack[ii], TSTACK_SIZE,
test_thread_pend_and_timeout,
&test_data[ii], NULL, NULL,
K_PRIO_PREEMPT(0), K_INHERIT_PERMS, 0);
for (ii = 0; ii < test_data_size-1; ii++) {
k_fifo_put(test_data[ii].fifo, get_scratch_packet());
data = k_fifo_get(&timeout_order_fifo, K_FOREVER);
if (data->q_order == ii) {
TC_PRINT(" thread (q order: %d, t/o: %d, fifo %p)\n",
data->q_order, data->timeout, data->fifo);
} else {
TC_ERROR(" *** thread %d woke up, expected %d\n",
data->q_order, ii);
return TC_FAIL;
}
}
data = k_fifo_get(&timeout_order_fifo, K_FOREVER);
if (data && data->q_order == ii) {
TC_PRINT(" thread (q order: %d, t/o: %d, fifo %p)\n",
data->q_order, data->timeout, data->fifo);
} else {
TC_ERROR(" *** thread %d woke up, expected %d\n",
data->timeout_order, ii);
return TC_FAIL;
}
return TC_PASS;
}
/* try getting data on fifo with special timeout value, return result in fifo */
static void test_thread_timeout_reply_values(void *p1, void *p2, void *p3)
{
struct reply_packet *reply_packet = (struct reply_packet *)p1;
reply_packet->reply =
!!k_fifo_get(&fifo_timeout[0], K_NO_WAIT);
k_fifo_put(&timeout_order_fifo, reply_packet);
}
static void test_thread_timeout_reply_values_wfe(void *p1, void *p2, void *p3)
{
struct reply_packet *reply_packet = (struct reply_packet *)p1;
reply_packet->reply =
!!k_fifo_get(&fifo_timeout[0], K_FOREVER);
k_fifo_put(&timeout_order_fifo, reply_packet);
}
/*test cases*/
static void test_timeout_empty_fifo(void)
{
void *packet;
u32_t start_time, timeout;
/* Test empty fifo with timeout */
timeout = 10;
start_time = k_cycle_get_32();
packet = k_fifo_get(&fifo_timeout[0], timeout);
zassert_true(packet == NULL, NULL);
zassert_true(is_timeout_in_range(start_time, timeout), NULL);
/* Test empty fifo with timeout of K_NO_WAIT */
packet = k_fifo_get(&fifo_timeout[0], K_NO_WAIT);
zassert_true(packet == NULL, NULL);
}
static void test_timeout_non_empty_fifo(void)
{
void *packet, *scratch_packet;
/* Test k_fifo_get with K_NO_WAIT */
scratch_packet = get_scratch_packet();
k_fifo_put(&fifo_timeout[0], scratch_packet);
packet = k_fifo_get(&fifo_timeout[0], K_NO_WAIT);
zassert_true(packet != NULL, NULL);
put_scratch_packet(scratch_packet);
/* Test k_fifo_get with K_FOREVER */
scratch_packet = get_scratch_packet();
k_fifo_put(&fifo_timeout[0], scratch_packet);
packet = k_fifo_get(&fifo_timeout[0], K_FOREVER);
zassert_true(packet != NULL, NULL);
put_scratch_packet(scratch_packet);
}
static void test_timeout_fifo_thread(void)
{
void *packet, *scratch_packet;
struct reply_packet reply_packet;
u32_t start_time, timeout;
/*
* Test fifo with some timeout and child thread that puts
* data on the fifo on time
*/
timeout = 10;
start_time = k_cycle_get_32();
tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
test_thread_put_timeout, &fifo_timeout[0],
&timeout, NULL,
FIFO_THREAD_PRIO, K_INHERIT_PERMS, 0);
packet = k_fifo_get(&fifo_timeout[0], timeout + 10);
zassert_true(packet != NULL, NULL);
zassert_true(is_timeout_in_range(start_time, timeout), NULL);
put_scratch_packet(packet);
/*
* Test k_fifo_get with timeout of K_NO_WAIT and the fifo
* should be filled be filled by the child thread based on
* the data availability on another fifo. In this test child
* thread does not find data on fifo.
*/
tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
test_thread_timeout_reply_values,
&reply_packet, NULL, NULL,
FIFO_THREAD_PRIO, K_INHERIT_PERMS, 0);
k_yield();
packet = k_fifo_get(&timeout_order_fifo, K_NO_WAIT);
zassert_true(packet != NULL, NULL);
zassert_false(reply_packet.reply, NULL);
/*
* Test k_fifo_get with timeout of K_NO_WAIT and the fifo
* should be filled be filled by the child thread based on
* the data availability on another fifo. In this test child
* thread does find data on fifo.
*/
scratch_packet = get_scratch_packet();
k_fifo_put(&fifo_timeout[0], scratch_packet);
tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
test_thread_timeout_reply_values,
&reply_packet, NULL, NULL,
FIFO_THREAD_PRIO, K_INHERIT_PERMS, 0);
k_yield();
packet = k_fifo_get(&timeout_order_fifo, K_NO_WAIT);
zassert_true(packet != NULL, NULL);
zassert_true(reply_packet.reply, NULL);
put_scratch_packet(scratch_packet);
/*
* Test k_fifo_get with timeout of K_FOREVER and the fifo
* should be filled be filled by the child thread based on
* the data availability on another fifo. In this test child
* thread does find data on fifo.
*/
scratch_packet = get_scratch_packet();
k_fifo_put(&fifo_timeout[0], scratch_packet);
tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
test_thread_timeout_reply_values_wfe,
&reply_packet, NULL, NULL,
FIFO_THREAD_PRIO, K_INHERIT_PERMS, 0);
packet = k_fifo_get(&timeout_order_fifo, K_FOREVER);
zassert_true(packet != NULL, NULL);
zassert_true(reply_packet.reply, NULL);
put_scratch_packet(scratch_packet);
}
static void test_timeout_threads_pend_on_fifo(void)
{
s32_t rv, test_data_size;
/*
* Test multiple threads pending on the same
* fifo with different timeouts
*/
test_data_size = ARRAY_SIZE(timeout_order_data);
rv = test_multiple_threads_pending(timeout_order_data, test_data_size);
zassert_equal(rv, TC_PASS, NULL);
}
static void test_timeout_threads_pend_on_dual_fifos(void)
{
s32_t rv, test_data_size;
/*
* Test multiple threads pending on different
* fifos with different timeouts
*/
test_data_size = ARRAY_SIZE(timeout_order_data_mult_fifo);
rv = test_multiple_threads_pending(timeout_order_data_mult_fifo,
test_data_size);
zassert_equal(rv, TC_PASS, NULL);
}
static void test_timeout_threads_pend_fail_on_fifo(void)
{
s32_t rv, test_data_size;
/*
* Test multiple threads pending on same
* fifo with different timeouts, but getting
* the data in time, except the last one.
*/
test_data_size = ARRAY_SIZE(timeout_order_data);
rv = test_multiple_threads_get_data(timeout_order_data, test_data_size);
zassert_equal(rv, TC_PASS, NULL);
}
static void test_timeout_setup(void)
{
s32_t ii;
/* Init kernel objects */
k_fifo_init(&fifo_timeout[0]);
k_fifo_init(&fifo_timeout[1]);
k_fifo_init(&timeout_order_fifo);
k_fifo_init(&scratch_fifo_packets_fifo);
/* Fill scratch fifo */
for (ii = 0; ii < NUM_SCRATCH_FIFO_PACKETS; ii++) {
scratch_fifo_packets[ii].data_if_needed = (void *)ii;
k_fifo_put(&scratch_fifo_packets_fifo,
(void *)&scratch_fifo_packets[ii]);
}
}
/*test case main entry*/
void test_main(void)
{
test_timeout_setup();
ztest_test_suite(test_fifo_timeout,
ztest_unit_test(test_timeout_empty_fifo),
ztest_unit_test(test_timeout_non_empty_fifo),
ztest_unit_test(test_timeout_fifo_thread),
ztest_unit_test(test_timeout_threads_pend_on_fifo),
ztest_unit_test(test_timeout_threads_pend_on_dual_fifos),
ztest_unit_test(test_timeout_threads_pend_fail_on_fifo));
ztest_run_test_suite(test_fifo_timeout);
}
|
445144.c | /******************************************************************************
* Copyright 2017 - 2018, Opulinks Technology Ltd.
* ---------------------------------------------------------------------------
* Statement:
* ----------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of Opulinks Technology Ltd. (C) 2018
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "network_config.h"
// TODO:Get DHCP, IP configuration from flash
int32_t dhcp_config_init(void)
{
return (USE_DHCP == 0) ? STA_IP_MODE_STATIC : STA_IP_MODE_DHCP;
}
int32_t tcpip_config_init(lwip_tcpip_config_t *tcpip_config)
{
/* Static IP assignment */
ip4addr_aton(STA_IPADDR, &(tcpip_config->sta_ip));
ip4addr_aton(STA_NETMASK, &tcpip_config->sta_mask);
ip4addr_aton(STA_GATEWAY, &tcpip_config->sta_gw);
return 0;
}
|
462602.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__malloc_char_loop_44.c
Label Definition File: CWE127_Buffer_Underread__malloc.label.xml
Template File: sources-sink-44.tmpl.c
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: loop
* BadSink : Copy data to string using a loop
* Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
static void badSink(char * data)
{
{
size_t i;
char dest[100];
memset(dest, 'C', 100-1); /* fill with 'C's */
dest[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
for (i = 0; i < 100; i++)
{
dest[i] = data[i];
}
/* Ensure null termination */
dest[100-1] = '\0';
printLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
void CWE127_Buffer_Underread__malloc_char_loop_44_bad()
{
char * data;
/* define a function pointer */
void (*funcPtr) (char *) = badSink;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
/* use the function pointer */
funcPtr(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(char * data)
{
{
size_t i;
char dest[100];
memset(dest, 'C', 100-1); /* fill with 'C's */
dest[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
for (i = 0; i < 100; i++)
{
dest[i] = data[i];
}
/* Ensure null termination */
dest[100-1] = '\0';
printLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
static void goodG2B()
{
char * data;
void (*funcPtr) (char *) = goodG2BSink;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
funcPtr(data);
}
void CWE127_Buffer_Underread__malloc_char_loop_44_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE127_Buffer_Underread__malloc_char_loop_44_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE127_Buffer_Underread__malloc_char_loop_44_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
622450.c | #include <stdint.h>
#include <stdlib.h>
#include "list.h"
#include "uthread.h"
#define STACK_SIZE (8*4096)
typedef struct uthread_context {
uint64_t r15;
uint64_t r14;
uint64_t r13;
uint64_t r12;
uint64_t rbx;
uint64_t rbp;
void (*ret_addr)();
} UTHREAD_CONTEXT, *PUTHREAD_CONTEXT;
typedef struct uthread {
uint64_t sp; // fixed at offset 0 (do not move) [see ctxsw.s]
void * stack;
LIST_ENTRY node;
void (*start_routine)(void *);
void * argument;
} UTHREAD, *PUTHREAD;
static unsigned int number_of_threads;
static LIST_ENTRY ready_queue;
PUTHREAD running_thread;
static PUTHREAD main_thread;
static void internal_start() {
// call thread function with argument
running_thread->start_routine(running_thread->argument);
// cleanup thread
ut_exit(); // never returns
}
void internal_exit(PUTHREAD currThread, PUTHREAD nextThread);
void context_switch(PUTHREAD currThread, PUTHREAD nextThread);
void cleanup_thread(PUTHREAD thread) {
free(thread->stack);
free(thread);
}
__attribute__((always_inline))
static inline PUTHREAD extract_next_ready_thread() {
if (isListEmpty(&ready_queue)) {
return main_thread;
}
PLIST_ENTRY thread_node = removeHeadList(&ready_queue);
PUTHREAD next_thread = container_of(thread_node, UTHREAD, node);
return next_thread;
}
void ut_init() {
number_of_threads = 0;
initializeListHead(&ready_queue);
}
void ut_end() {
// nothing to do
}
void ut_run() {
UTHREAD thread;
if (isListEmpty(&ready_queue)) {
return;
}
main_thread = &thread;
PUTHREAD first_thread = extract_next_ready_thread();
context_switch(main_thread, first_thread);
main_thread = running_thread = NULL;
}
void ut_create(void (*start_routine) (void *), void *arg) {
PUTHREAD thread = (PUTHREAD)malloc(sizeof (UTHREAD));
thread->stack = malloc(STACK_SIZE);
thread->start_routine = start_routine;
thread->argument = arg;
PUTHREAD_CONTEXT context = (PUTHREAD_CONTEXT)
(
(char *)thread->stack
+ STACK_SIZE
- sizeof (uint64_t) * 5
- sizeof (UTHREAD_CONTEXT)
);
context->r15 = 0x5555555555555555;
context->r14 = 0x4444444444444444;
context->r13 = 0x3333333333333333;
context->r12 = 0x2222222222222222;
context->rbx = 0x1111111111111111;
context->rbp = 0x0000000000000000; // mandatory for debuggers
context->ret_addr = internal_start;
thread->sp = (uint64_t)context;
number_of_threads += 1;
insertTailList(&ready_queue, &(thread->node));
}
void ut_exit() {
number_of_threads -= 1;
PUTHREAD next_thread = extract_next_ready_thread();
internal_exit(running_thread, next_thread);
}
void ut_yield() {
if (!isListEmpty(&ready_queue)) {
insertTailList(&ready_queue, &(running_thread->node));
PUTHREAD next_thread = extract_next_ready_thread();
context_switch(running_thread, next_thread);
}
}
|
605316.c | /*
* C Extension module to test Python internal C APIs (Include/internal).
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
/* Always enable assertions */
#undef NDEBUG
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "pycore_atomic_funcs.h" // _Py_atomic_int_get()
#include "pycore_bitutils.h" // _Py_bswap32()
#include "pycore_fileutils.h" // _Py_normpath
#include "pycore_gc.h" // PyGC_Head
#include "pycore_hashtable.h" // _Py_hashtable_new()
#include "pycore_initconfig.h" // _Py_GetConfigsAsDict()
#include "pycore_pathconfig.h" // _PyPathConfig_ClearGlobal()
#include "pycore_interp.h" // _PyInterpreterState_GetConfigCopy()
#include "pycore_pyerrors.h" // _Py_UTF8_Edit_Cost()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "osdefs.h" // MAXPATHLEN
static PyObject *
get_configs(PyObject *self, PyObject *Py_UNUSED(args))
{
return _Py_GetConfigsAsDict();
}
static PyObject*
get_recursion_depth(PyObject *self, PyObject *Py_UNUSED(args))
{
PyThreadState *tstate = _PyThreadState_GET();
/* subtract one to ignore the frame of the get_recursion_depth() call */
return PyLong_FromLong(tstate->recursion_limit - tstate->recursion_remaining - 1);
}
static PyObject*
test_bswap(PyObject *self, PyObject *Py_UNUSED(args))
{
uint16_t u16 = _Py_bswap16(UINT16_C(0x3412));
if (u16 != UINT16_C(0x1234)) {
PyErr_Format(PyExc_AssertionError,
"_Py_bswap16(0x3412) returns %u", u16);
return NULL;
}
uint32_t u32 = _Py_bswap32(UINT32_C(0x78563412));
if (u32 != UINT32_C(0x12345678)) {
PyErr_Format(PyExc_AssertionError,
"_Py_bswap32(0x78563412) returns %lu", u32);
return NULL;
}
uint64_t u64 = _Py_bswap64(UINT64_C(0xEFCDAB9078563412));
if (u64 != UINT64_C(0x1234567890ABCDEF)) {
PyErr_Format(PyExc_AssertionError,
"_Py_bswap64(0xEFCDAB9078563412) returns %llu", u64);
return NULL;
}
Py_RETURN_NONE;
}
static int
check_popcount(uint32_t x, int expected)
{
// Use volatile to prevent the compiler to optimize out the whole test
volatile uint32_t u = x;
int bits = _Py_popcount32(u);
if (bits != expected) {
PyErr_Format(PyExc_AssertionError,
"_Py_popcount32(%lu) returns %i, expected %i",
(unsigned long)x, bits, expected);
return -1;
}
return 0;
}
static PyObject*
test_popcount(PyObject *self, PyObject *Py_UNUSED(args))
{
#define CHECK(X, RESULT) \
do { \
if (check_popcount(X, RESULT) < 0) { \
return NULL; \
} \
} while (0)
CHECK(0, 0);
CHECK(1, 1);
CHECK(0x08080808, 4);
CHECK(0x10101010, 4);
CHECK(0x10204080, 4);
CHECK(0xDEADCAFE, 22);
CHECK(0xFFFFFFFF, 32);
Py_RETURN_NONE;
#undef CHECK
}
static int
check_bit_length(unsigned long x, int expected)
{
// Use volatile to prevent the compiler to optimize out the whole test
volatile unsigned long u = x;
int len = _Py_bit_length(u);
if (len != expected) {
PyErr_Format(PyExc_AssertionError,
"_Py_bit_length(%lu) returns %i, expected %i",
x, len, expected);
return -1;
}
return 0;
}
static PyObject*
test_bit_length(PyObject *self, PyObject *Py_UNUSED(args))
{
#define CHECK(X, RESULT) \
do { \
if (check_bit_length(X, RESULT) < 0) { \
return NULL; \
} \
} while (0)
CHECK(0, 0);
CHECK(1, 1);
CHECK(0x1000, 13);
CHECK(0x1234, 13);
CHECK(0x54321, 19);
CHECK(0x7FFFFFFF, 31);
CHECK(0xFFFFFFFF, 32);
Py_RETURN_NONE;
#undef CHECK
}
#define TO_PTR(ch) ((void*)(uintptr_t)ch)
#define FROM_PTR(ptr) ((uintptr_t)ptr)
#define VALUE(key) (1 + ((int)(key) - 'a'))
static Py_uhash_t
hash_char(const void *key)
{
char ch = (char)FROM_PTR(key);
return ch;
}
static int
hashtable_cb(_Py_hashtable_t *table,
const void *key_ptr, const void *value_ptr,
void *user_data)
{
int *count = (int *)user_data;
char key = (char)FROM_PTR(key_ptr);
int value = (int)FROM_PTR(value_ptr);
assert(value == VALUE(key));
*count += 1;
return 0;
}
static PyObject*
test_hashtable(PyObject *self, PyObject *Py_UNUSED(args))
{
_Py_hashtable_t *table = _Py_hashtable_new(hash_char,
_Py_hashtable_compare_direct);
if (table == NULL) {
return PyErr_NoMemory();
}
// Using an newly allocated table must not crash
assert(table->nentries == 0);
assert(table->nbuckets > 0);
assert(_Py_hashtable_get(table, TO_PTR('x')) == NULL);
// Test _Py_hashtable_set()
char key;
for (key='a'; key <= 'z'; key++) {
int value = VALUE(key);
if (_Py_hashtable_set(table, TO_PTR(key), TO_PTR(value)) < 0) {
_Py_hashtable_destroy(table);
return PyErr_NoMemory();
}
}
assert(table->nentries == 26);
assert(table->nbuckets > table->nentries);
// Test _Py_hashtable_get_entry()
for (key='a'; key <= 'z'; key++) {
_Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(table, TO_PTR(key));
assert(entry != NULL);
assert(entry->key == TO_PTR(key));
assert(entry->value == TO_PTR(VALUE(key)));
}
// Test _Py_hashtable_get()
for (key='a'; key <= 'z'; key++) {
void *value_ptr = _Py_hashtable_get(table, TO_PTR(key));
assert((int)FROM_PTR(value_ptr) == VALUE(key));
}
// Test _Py_hashtable_steal()
key = 'p';
void *value_ptr = _Py_hashtable_steal(table, TO_PTR(key));
assert((int)FROM_PTR(value_ptr) == VALUE(key));
assert(table->nentries == 25);
assert(_Py_hashtable_get_entry(table, TO_PTR(key)) == NULL);
// Test _Py_hashtable_foreach()
int count = 0;
int res = _Py_hashtable_foreach(table, hashtable_cb, &count);
assert(res == 0);
assert(count == 25);
// Test _Py_hashtable_clear()
_Py_hashtable_clear(table);
assert(table->nentries == 0);
assert(table->nbuckets > 0);
assert(_Py_hashtable_get(table, TO_PTR('x')) == NULL);
_Py_hashtable_destroy(table);
Py_RETURN_NONE;
}
static PyObject *
test_get_config(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args))
{
PyConfig config;
PyConfig_InitIsolatedConfig(&config);
if (_PyInterpreterState_GetConfigCopy(&config) < 0) {
PyConfig_Clear(&config);
return NULL;
}
PyObject *dict = _PyConfig_AsDict(&config);
PyConfig_Clear(&config);
return dict;
}
static PyObject *
test_set_config(PyObject *Py_UNUSED(self), PyObject *dict)
{
PyConfig config;
PyConfig_InitIsolatedConfig(&config);
if (_PyConfig_FromDict(&config, dict) < 0) {
goto error;
}
if (_PyInterpreterState_SetConfig(&config) < 0) {
goto error;
}
PyConfig_Clear(&config);
Py_RETURN_NONE;
error:
PyConfig_Clear(&config);
return NULL;
}
static PyObject *
test_reset_path_config(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(arg))
{
_PyPathConfig_ClearGlobal();
Py_RETURN_NONE;
}
static PyObject*
test_atomic_funcs(PyObject *self, PyObject *Py_UNUSED(args))
{
// Test _Py_atomic_size_get() and _Py_atomic_size_set()
Py_ssize_t var = 1;
_Py_atomic_size_set(&var, 2);
assert(_Py_atomic_size_get(&var) == 2);
Py_RETURN_NONE;
}
static int
check_edit_cost(const char *a, const char *b, Py_ssize_t expected)
{
int ret = -1;
PyObject *a_obj = NULL;
PyObject *b_obj = NULL;
a_obj = PyUnicode_FromString(a);
if (a_obj == NULL) {
goto exit;
}
b_obj = PyUnicode_FromString(b);
if (a_obj == NULL) {
goto exit;
}
Py_ssize_t result = _Py_UTF8_Edit_Cost(a_obj, b_obj, -1);
if (result != expected) {
PyErr_Format(PyExc_AssertionError,
"Edit cost from '%s' to '%s' returns %zd, expected %zd",
a, b, result, expected);
goto exit;
}
// Check that smaller max_edits thresholds are exceeded.
Py_ssize_t max_edits = result;
while (max_edits > 0) {
max_edits /= 2;
Py_ssize_t result2 = _Py_UTF8_Edit_Cost(a_obj, b_obj, max_edits);
if (result2 <= max_edits) {
PyErr_Format(PyExc_AssertionError,
"Edit cost from '%s' to '%s' (threshold %zd) "
"returns %zd, expected greater than %zd",
a, b, max_edits, result2, max_edits);
goto exit;
}
}
// Check that bigger max_edits thresholds don't change anything
Py_ssize_t result3 = _Py_UTF8_Edit_Cost(a_obj, b_obj, result * 2 + 1);
if (result3 != result) {
PyErr_Format(PyExc_AssertionError,
"Edit cost from '%s' to '%s' (threshold %zd) "
"returns %zd, expected %zd",
a, b, result * 2, result3, result);
goto exit;
}
ret = 0;
exit:
Py_XDECREF(a_obj);
Py_XDECREF(b_obj);
return ret;
}
static PyObject *
test_edit_cost(PyObject *self, PyObject *Py_UNUSED(args))
{
#define CHECK(a, b, n) do { \
if (check_edit_cost(a, b, n) < 0) { \
return NULL; \
} \
} while (0) \
CHECK("", "", 0);
CHECK("", "a", 2);
CHECK("a", "A", 1);
CHECK("Apple", "Aple", 2);
CHECK("Banana", "B@n@n@", 6);
CHECK("Cherry", "Cherry!", 2);
CHECK("---0---", "------", 2);
CHECK("abc", "y", 6);
CHECK("aa", "bb", 4);
CHECK("aaaaa", "AAAAA", 5);
CHECK("wxyz", "wXyZ", 2);
CHECK("wxyz", "wXyZ123", 8);
CHECK("Python", "Java", 12);
CHECK("Java", "C#", 8);
CHECK("AbstractFoobarManager", "abstract_foobar_manager", 3+2*2);
CHECK("CPython", "PyPy", 10);
CHECK("CPython", "pypy", 11);
CHECK("AttributeError", "AttributeErrop", 2);
CHECK("AttributeError", "AttributeErrorTests", 10);
#undef CHECK
Py_RETURN_NONE;
}
static PyObject *
normalize_path(PyObject *self, PyObject *filename)
{
Py_ssize_t size = -1;
wchar_t *encoded = PyUnicode_AsWideCharString(filename, &size);
if (encoded == NULL) {
return NULL;
}
PyObject *result = PyUnicode_FromWideChar(_Py_normpath(encoded, size), -1);
PyMem_Free(encoded);
return result;
}
static PyObject *
get_getpath_codeobject(PyObject *self, PyObject *Py_UNUSED(args)) {
return _Py_Get_Getpath_CodeObject();
}
static PyObject *
encode_locale_ex(PyObject *self, PyObject *args)
{
PyObject *unicode;
int current_locale = 0;
wchar_t *wstr;
PyObject *res = NULL;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "U|is", &unicode, ¤t_locale, &errors)) {
return NULL;
}
wstr = PyUnicode_AsWideCharString(unicode, NULL);
if (wstr == NULL) {
return NULL;
}
_Py_error_handler error_handler = _Py_GetErrorHandler(errors);
char *str = NULL;
size_t error_pos;
const char *reason = NULL;
int ret = _Py_EncodeLocaleEx(wstr,
&str, &error_pos, &reason,
current_locale, error_handler);
PyMem_Free(wstr);
switch(ret) {
case 0:
res = PyBytes_FromString(str);
PyMem_RawFree(str);
break;
case -1:
PyErr_NoMemory();
break;
case -2:
PyErr_Format(PyExc_RuntimeError, "encode error: pos=%zu, reason=%s",
error_pos, reason);
break;
case -3:
PyErr_SetString(PyExc_ValueError, "unsupported error handler");
break;
default:
PyErr_SetString(PyExc_ValueError, "unknown error code");
break;
}
return res;
}
static PyObject *
decode_locale_ex(PyObject *self, PyObject *args)
{
char *str;
int current_locale = 0;
PyObject *res = NULL;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "y|is", &str, ¤t_locale, &errors)) {
return NULL;
}
_Py_error_handler error_handler = _Py_GetErrorHandler(errors);
wchar_t *wstr = NULL;
size_t wlen = 0;
const char *reason = NULL;
int ret = _Py_DecodeLocaleEx(str,
&wstr, &wlen, &reason,
current_locale, error_handler);
switch(ret) {
case 0:
res = PyUnicode_FromWideChar(wstr, wlen);
PyMem_RawFree(wstr);
break;
case -1:
PyErr_NoMemory();
break;
case -2:
PyErr_Format(PyExc_RuntimeError, "decode error: pos=%zu, reason=%s",
wlen, reason);
break;
case -3:
PyErr_SetString(PyExc_ValueError, "unsupported error handler");
break;
default:
PyErr_SetString(PyExc_ValueError, "unknown error code");
break;
}
return res;
}
static PyMethodDef TestMethods[] = {
{"get_configs", get_configs, METH_NOARGS},
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
{"test_bswap", test_bswap, METH_NOARGS},
{"test_popcount", test_popcount, METH_NOARGS},
{"test_bit_length", test_bit_length, METH_NOARGS},
{"test_hashtable", test_hashtable, METH_NOARGS},
{"get_config", test_get_config, METH_NOARGS},
{"set_config", test_set_config, METH_O},
{"reset_path_config", test_reset_path_config, METH_NOARGS},
{"test_atomic_funcs", test_atomic_funcs, METH_NOARGS},
{"test_edit_cost", test_edit_cost, METH_NOARGS},
{"normalize_path", normalize_path, METH_O, NULL},
{"get_getpath_codeobject", get_getpath_codeobject, METH_NOARGS, NULL},
{"EncodeLocaleEx", encode_locale_ex, METH_VARARGS},
{"DecodeLocaleEx", decode_locale_ex, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef _testcapimodule = {
PyModuleDef_HEAD_INIT,
"_testinternalcapi",
NULL,
-1,
TestMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__testinternalcapi(void)
{
PyObject *module = PyModule_Create(&_testcapimodule);
if (module == NULL) {
return NULL;
}
if (PyModule_AddObject(module, "SIZEOF_PYGC_HEAD",
PyLong_FromSsize_t(sizeof(PyGC_Head))) < 0) {
goto error;
}
return module;
error:
Py_DECREF(module);
return NULL;
}
|
764921.c | /*
* arch/s390/kernel/delay.c
* Precise Delay Loops for S390
*
* S390 version
* Copyright (C) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky ([email protected]),
*
* Derived from "arch/i386/lib/delay.c"
* Copyright (C) 1993 Linus Torvalds
* Copyright (C) 1997 Martin Mares <[email protected]>
*/
#include <linux/config.h>
#include <linux/sched.h>
#include <linux/delay.h>
#ifdef CONFIG_SMP
#include <asm/smp.h>
#endif
void __delay(unsigned long loops)
{
__asm__ __volatile__(
"0: ahi %0,-1\n"
" jnm 0b"
: /* no outputs */ : "r" (loops) );
}
inline void __const_udelay(unsigned long xloops)
{
__asm__("LR 3,%1\n\t"
"MR 2,%2\n\t"
"LR %0,2\n\t"
: "=r" (xloops)
: "r" (xloops) , "r" (loops_per_sec)
: "2" , "3");
__delay(xloops);
}
void __udelay(unsigned long usecs)
{
__const_udelay(usecs * 0x000010c6); /* 2**32 / 1000000 */
}
|
482344.c | #include <stdio.h>
#ifndef LLHTTP__TEST
# include "suil/http/llhttp.h"
#else
# define llhttp_t llparse_t
#endif /* */
int llhttp_message_needs_eof(const llhttp_t* parser);
int llhttp_should_keep_alive(const llhttp_t* parser);
int llhttp__before_headers_complete(llhttp_t* parser, const char* p,
const char* endp) {
/* Set this here so that on_headers_complete() callbacks can see it */
if ((parser->flags & F_UPGRADE) &&
(parser->flags & F_CONNECTION_UPGRADE)) {
/* For responses, "Upgrade: foo" and "Connection: upgrade" are
* mandatory only when it is a 101 Switching Protocols response,
* otherwise it is purely informational, to announce support.
*/
parser->upgrade =
(parser->type == HTTP_REQUEST || parser->status_code == 101);
} else {
parser->upgrade = (parser->method == HTTP_CONNECT);
}
return 0;
}
/* Return values:
* 0 - No body, `restart`, message_complete
* 1 - CONNECT request, `restart`, message_complete, and pause
* 2 - chunk_size_start
* 3 - body_identity
* 4 - body_identity_eof
* 5 - invalid transfer-encoding for request
*/
int llhttp__after_headers_complete(llhttp_t* parser, const char* p,
const char* endp) {
int hasBody;
hasBody = parser->flags & F_CHUNKED || parser->content_length > 0;
if (parser->upgrade && (parser->method == HTTP_CONNECT ||
(parser->flags & F_SKIPBODY) || !hasBody)) {
/* Exit, the rest of the message is in a different protocol. */
return 1;
}
if (parser->flags & F_SKIPBODY) {
return 0;
} else if (parser->flags & F_CHUNKED) {
/* chunked encoding - ignore Content-Length header, prepare for a chunk */
return 2;
} else if (parser->flags & F_TRANSFER_ENCODING) {
if (parser->type == HTTP_REQUEST &&
(parser->lenient_flags & LENIENT_CHUNKED_LENGTH) == 0) {
/* RFC 7230 3.3.3 */
/* If a Transfer-Encoding header field
* is present in a request and the chunked transfer coding is not
* the final encoding, the message body length cannot be determined
* reliably; the server MUST respond with the 400 (Bad Request)
* status code and then close the connection.
*/
return 5;
} else {
/* RFC 7230 3.3.3 */
/* If a Transfer-Encoding header field is present in a response and
* the chunked transfer coding is not the final encoding, the
* message body length is determined by reading the connection until
* it is closed by the server.
*/
return 4;
}
} else {
if (!(parser->flags & F_CONTENT_LENGTH)) {
if (!llhttp_message_needs_eof(parser)) {
/* Assume content-length 0 - read the next */
return 0;
} else {
/* Read body until EOF */
return 4;
}
} else if (parser->content_length == 0) {
/* Content-Length header given but zero: Content-Length: 0\r\n */
return 0;
} else {
/* Content-Length header given and non-zero */
return 3;
}
}
}
int llhttp__after_message_complete(llhttp_t* parser, const char* p,
const char* endp) {
int should_keep_alive;
should_keep_alive = llhttp_should_keep_alive(parser);
parser->finish = HTTP_FINISH_SAFE;
parser->flags = 0;
/* NOTE: this is ignored in loose parsing mode */
return should_keep_alive;
}
int llhttp_message_needs_eof(const llhttp_t* parser) {
if (parser->type == HTTP_REQUEST) {
return 0;
}
/* See RFC 2616 section 4.4 */
if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */
parser->status_code == 204 || /* No Content */
parser->status_code == 304 || /* Not Modified */
(parser->flags & F_SKIPBODY)) { /* response to a HEAD request */
return 0;
}
/* RFC 7230 3.3.3, see `llhttp__after_headers_complete` */
if ((parser->flags & F_TRANSFER_ENCODING) &&
(parser->flags & F_CHUNKED) == 0) {
return 1;
}
if (parser->flags & (F_CHUNKED | F_CONTENT_LENGTH)) {
return 0;
}
return 1;
}
int llhttp_should_keep_alive(const llhttp_t* parser) {
if (parser->http_major > 0 && parser->http_minor > 0) {
/* HTTP/1.1 */
if (parser->flags & F_CONNECTION_CLOSE) {
return 0;
}
} else {
/* HTTP/1.0 or earlier */
if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) {
return 0;
}
}
return !llhttp_message_needs_eof(parser);
}
|
Subsets and Splits